From c9ced06c906691b0c58f9173fc06400cc565f106 Mon Sep 17 00:00:00 2001 From: Robert Varga Date: Sat, 16 Mar 2019 00:59:32 +0100 Subject: [PATCH] Remove binding spec2 Binding spec v2 is rather incompatible and we have decided to not make a jump to it, as it is not really feasible. Rather than that we will backport its fixes to binding v1 in a gradual way. Remove all binding-v2 artifacts. Change-Id: Ic58f13372cfe6cbc6f5088e1e507acac14c11c19 Signed-off-by: Robert Varga --- artifacts/pom.xml | 110 -- binding2/mdsal-binding2-api/pom.xml | 97 -- .../binding/javav2/api/BindingService.java | 25 - .../api/CursorAwareWriteTransaction.java | 75 - .../mdsal/binding/javav2/api/DataBroker.java | 53 - .../javav2/api/DataTreeCommitCohort.java | 76 - .../api/DataTreeCommitCohortRegistry.java | 37 - .../binding/javav2/api/DataTreeCursor.java | 82 - .../javav2/api/DataTreeCursorProvider.java | 34 - .../javav2/api/DataTreeIdentifier.java | 94 - .../binding/javav2/api/DataTreeListener.java | 46 - .../api/DataTreeListeningException.java | 34 - .../javav2/api/DataTreeLoopException.java | 30 - .../javav2/api/DataTreeModification.java | 37 - .../binding/javav2/api/DataTreeProducer.java | 106 -- .../api/DataTreeProducerBusyException.java | 33 - .../javav2/api/DataTreeProducerException.java | 26 - .../javav2/api/DataTreeProducerFactory.java | 28 - .../binding/javav2/api/DataTreeService.java | 71 - .../javav2/api/DataTreeWriteCursor.java | 55 - .../mdsal/binding/javav2/api/MountPoint.java | 32 - .../javav2/api/MountPointListener.java | 33 - .../binding/javav2/api/MountPointService.java | 41 - .../api/NotificationPublishService.java | 50 - .../api/NotificationRejectedException.java | 32 - .../javav2/api/NotificationService.java | 127 -- .../binding/javav2/api/ReadTransaction.java | 78 - .../javav2/api/RpcActionConsumerRegistry.java | 66 - .../javav2/api/RpcActionProviderService.java | 76 - .../mdsal/binding/javav2/api/Transaction.java | 24 - .../binding/javav2/api/TransactionChain.java | 82 - .../api/TransactionChainClosedException.java | 23 - .../javav2/api/TransactionChainListener.java | 37 - .../javav2/api/TransactionFactory.java | 82 - .../javav2/api/TreeNodeModification.java | 201 --- .../binding/javav2/api/WriteTransaction.java | 562 ------ .../javav2/api/annotation/RoutingContext.java | 27 - .../javav2/api/DataTreeIdentifierTest.java | 65 - .../api/DataTreeListeningExceptionTest.java | 24 - .../javav2/api/DataTreeLoopExceptionTest.java | 24 - .../DataTreeProducerBusyExceptionTest.java | 24 - .../api/DataTreeProducerExceptionTest.java | 25 - .../NotificationRejectedExceptionTest.java | 24 - .../javav2/api/TreeNodeModificationTest.java | 21 - binding2/mdsal-binding2-dom-adapter/pom.xml | 121 -- .../extractor/ContextReferenceExtractor.java | 119 -- .../DirectGetterRouteContextExtractor.java | 46 - .../GetValueRouteContextExtractor.java | 55 - .../data/BindingDOMDataBrokerAdapter.java | 114 -- ...DOMCursorAwareWriteTransactionAdapter.java | 62 - ...BindingDOMDataTreeCommitCohortAdapter.java | 65 - ...OMDataTreeCommitCohortRegistryAdapter.java | 74 - .../BindingDOMDataTreeListenerAdapter.java | 94 - .../BindingDOMDataTreeProducerAdapter.java | 78 - .../BindingDOMDataTreeServiceAdapter.java | 70 - .../BindingDOMDataTreeWriteCursorAdapter.java | 115 -- .../BindingDOMMountPointListenerAdapter.java | 86 - .../BindingDOMMountPointServiceAdapter.java | 71 - .../mountpoint/BindingMountPointAdapter.java | 59 - ...BindingDOMNotificationListenerAdapter.java | 113 -- ...gDOMNotificationPublishServiceAdapter.java | 95 -- .../BindingDOMNotificationServiceAdapter.java | 95 -- .../NotificationListenerInvoker.java | 130 -- .../impl/operation/ActionServiceAdapter.java | 156 -- ...ingDOMOperationProviderServiceAdapter.java | 214 --- .../BindingDOMOperationServiceAdapter.java | 118 -- .../operation/LazyDOMActionResultFuture.java | 132 -- .../operation/LazyDOMRpcResultFuture.java | 131 -- .../impl/operation/RpcServiceAdapter.java | 225 --- .../BindingDOMReadTransactionAdapter.java | 43 - .../BindingDOMTransactionChainAdapter.java | 138 -- .../BindingDOMWriteTransactionAdapter.java | 63 - ...indingDOMOperationAdapterRegistration.java | 35 - .../BindingDataTreeListenerRegistration.java | 38 - .../spi/AbstractForwardedDataBroker.java | 109 -- .../spi/AbstractForwardedTransaction.java | 74 - .../adapter/spi/AbstractWriteTransaction.java | 172 -- .../adapter/spi/builder/AdapterBuilder.java | 63 - .../spi/builder/BindingDOMAdapterBuilder.java | 61 - .../dom/adapter/spi/loader/AdapterLoader.java | 49 - .../spi/loader/BindingDOMAdapterLoader.java | 61 - ...DirectGetterRouteContextExtractorTest.java | 47 - ...ursorAwareWriteTransactionAdapterTest.java | 67 - ...ingDOMDataTreeCommitCohortAdapterTest.java | 74 - ...BindingDOMDataTreeListenerAdapterTest.java | 56 - ...BindingDOMDataTreeProducerAdapterTest.java | 90 - .../BindingDOMDataTreeServiceAdapterTest.java | 60 - ...dingDOMDataTreeWriteCursorAdapterTest.java | 88 - ...ndingDOMMountPointListenerAdapterTest.java | 72 - ...indingDOMMountPointServiceAdapterTest.java | 52 - .../BindingMountPointAdapterTest.java | 32 - .../BindingDOMOperationAdapterTest.java | 261 --- .../spi/builder/AdapterBuilderTest.java | 43 - .../loader/BindingDOMAdapterLoaderTest.java | 77 - .../adapter/test/AbstractDataBrokerTest.java | 58 - .../adapter/test/AbstractSchemaAwareTest.java | 43 - .../dom/adapter/test/BasicLeafValueTest.java | 33 - .../test/BindingBrokerTestFactory.java | 58 - .../dom/adapter/test/BindingTestContext.java | 228 --- .../test/DataBrokerTestCustomizer.java | 124 -- .../dom/adapter/test/MockSchemaService.java | 60 - ...BindingDOMTransactionChainAdapterTest.java | 85 - binding2/mdsal-binding2-dom-codec/pom.xml | 98 -- .../dom/codec/api/AugmentationReader.java | 36 - .../BindingNormalizedNodeCachingCodec.java | 38 - .../codec/api/BindingNormalizedNodeCodec.java | 45 - .../dom/codec/api/BindingTreeCodec.java | 59 - .../dom/codec/api/BindingTreeNodeCodec.java | 166 -- .../BindingNormalizedNodeWriterFactory.java | 115 -- .../api/factory/BindingTreeCodecFactory.java | 42 - .../BindingNormalizedNodeSerializer.java | 131 -- .../api/TreeNodeSerializerGenerator.java | 34 - .../generator/impl/StaticBindingProperty.java | 75 - .../generator/impl/StreamWriterGenerator.java | 139 -- .../impl/TreeNodeSerializerPrototype.java | 47 - .../spi/generator/AbstractGenerator.java | 27 - .../AbstractStreamWriterGenerator.java | 344 ---- .../AbstractAugmentSerializerSource.java | 48 - ...entableDataNodeContainerEmitterSource.java | 40 - ...ractDataNodeContainerSerializerSource.java | 263 --- .../generator/spi/source/AbstractSource.java | 224 --- .../AbstractTreeNodeSerializerSource.java | 340 ---- .../javav2/dom/codec/impl/AnyxmlCodec.java | 48 - .../BindingNormalizedNodeCodecRegistry.java | 362 ---- .../impl/BindingToNormalizedNodeCodec.java | 581 ------- .../javav2/dom/codec/impl/FutureSchema.java | 118 -- .../dom/codec/impl/IdentifiableItemCodec.java | 147 -- .../javav2/dom/codec/impl/IdentityCodec.java | 49 - .../codec/impl/InstanceIdentifierCodec.java | 69 - .../codec/impl/MissingSchemaException.java | 57 - .../dom/codec/impl/NonCachingCodec.java | 48 - .../dom/codec/impl/OperationInputCodec.java | 29 - .../javav2/dom/codec/impl/UnionTypeCodec.java | 152 -- .../impl/UnmappedOperationInputCodec.java | 47 - ...tractBindingNormalizedNodeCacheHolder.java | 63 - .../cache/BindingNormalizedNodeCache.java | 59 - .../cache/CachingNormalizedNodeCodec.java | 54 - .../impl/context/AugmentationNodeContext.java | 52 - .../impl/context/CaseNodeCodecContext.java | 75 - .../impl/context/ChoiceNodeCodecContext.java | 237 --- .../context/ContainerNodeCodecContext.java | 52 - .../context/KeyedListNodeCodecContext.java | 118 -- .../impl/context/ListNodeCodecContext.java | 94 - .../context/NotificationCodecContext.java | 59 - .../impl/context/SchemaRootCodecContext.java | 373 ---- .../impl/context/UnionValueOptionContext.java | 143 -- .../dom/codec/impl/context/ValueContext.java | 83 - .../context/base/AnyxmlNodeCodecContext.java | 149 -- .../context/base/BindingCodecContext.java | 512 ------ .../base/DataContainerCodecContext.java | 221 --- .../base/DataContainerCodecPrototype.java | 160 -- .../base/IncorrectNestingException.java | 45 - .../codec/impl/context/base/LazyTreeNode.java | 237 --- .../context/base/LeafNodeCodecContext.java | 249 --- ...issingClassInLoadingStrategyException.java | 39 - .../base/MissingSchemaForClassException.java | 57 - .../impl/context/base/NodeCodecContext.java | 115 -- .../context/base/NodeContextSupplier.java | 23 - .../context/base/TreeNodeCodecContext.java | 421 ----- .../AugmentableDispatchSerializer.java | 78 - .../BindingToNormalizedStreamWriter.java | 258 --- .../CachingNormalizedNodeSerializer.java | 148 -- .../serializer/ChoiceDispatchSerializer.java | 66 - .../ForwardingBindingStreamEventWriter.java | 122 -- .../NormalizedNodeWithAddChildWriter.java | 36 - .../dom/codec/impl/value/BitsCodec.java | 124 -- .../codec/impl/value/CompositeValueCodec.java | 38 - .../impl/value/EncapsulatedValueCodec.java | 93 - .../codec/impl/value/EnumerationCodec.java | 66 - .../impl/value/ReflectionBasedCodec.java | 27 - .../dom/codec/impl/value/ValueTypeCodec.java | 118 -- .../modification/BindingStructuralType.java | 131 -- .../LazyDataTreeModification.java | 114 -- .../LazyTreeNodeModification.java | 235 --- .../LazySerializedContainerNode.java | 153 -- .../LazySerializedDOMNotification.java | 80 - .../impl/AbstractBindingRuntimeTest.java | 37 - ...nceIdentifierSerializeDeserializeTest.java | 56 - .../codec/impl/InstanceIdentifierTest.java | 56 - .../impl/LeafrefSerializeDeserializeTest.java | 84 - .../dom/codec/impl/NonCachingCodecTest.java | 31 - ...ormalizedNodeSerializeDeserializeTest.java | 161 -- .../javav2/dom/codec/impl/TypedefTest.java | 105 -- .../context/UnionValueOptionContextTest.java | 72 - .../impl/value/EnumerationCodecTest.java | 37 - .../LazyDataTreeModificationTest.java | 60 - binding2/mdsal-binding2-generator-api/pom.xml | 33 - .../generator/api/BindingGenerator.java | 56 - .../generator/api/ClassLoadingStrategy.java | 38 - .../generator/api/ModuleInfoRegistry.java | 27 - .../generator/context/ModuleContext.java | 257 --- .../javav2/generator/spi/TypeProvider.java | 76 - .../javav2/model/api/AccessModifier.java | 60 - .../javav2/model/api/AnnotationType.java | 127 -- .../model/api/BaseTypeWithRestrictions.java | 24 - .../javav2/model/api/CodeGenerator.java | 54 - .../javav2/model/api/ConcreteType.java | 20 - .../binding/javav2/model/api/Constant.java | 78 - .../javav2/model/api/DocumentedType.java | 56 - .../binding/javav2/model/api/Enumeration.java | 76 - .../javav2/model/api/GeneratedProperty.java | 37 - .../model/api/GeneratedTransferObject.java | 91 - .../javav2/model/api/GeneratedType.java | 139 -- .../model/api/GeneratedTypeForBuilder.java | 32 - .../javav2/model/api/MethodSignature.java | 71 - .../javav2/model/api/ParameterizedType.java | 41 - .../javav2/model/api/Restrictions.java | 26 - .../mdsal/binding/javav2/model/api/Type.java | 51 - .../binding/javav2/model/api/TypeComment.java | 29 - .../binding/javav2/model/api/TypeMember.java | 78 - .../binding/javav2/model/api/UnitName.java | 24 - .../javav2/model/api/WildcardType.java | 22 - .../model/api/YangSourceDefinition.java | 127 -- .../type/builder/AnnotationTypeBuilder.java | 93 - .../model/api/type/builder/EnumBuilder.java | 78 - .../builder/GeneratedPropertyBuilder.java | 48 - .../api/type/builder/GeneratedTOBuilder.java | 101 -- .../type/builder/GeneratedTypeBuilder.java | 30 - .../builder/GeneratedTypeBuilderBase.java | 274 --- .../type/builder/MethodSignatureBuilder.java | 72 - .../api/type/builder/TypeMemberBuilder.java | 84 - .../mdsal-binding2-generator-impl/pom.xml | 89 - .../generator/impl/AugmentToGenType.java | 410 ----- .../generator/impl/AuxiliaryGenUtils.java | 394 ----- .../generator/impl/BindingGeneratorImpl.java | 164 -- .../javav2/generator/impl/GenHelperUtil.java | 1438 ---------------- .../impl/GeneratedClassLoadingStrategy.java | 39 - .../generator/impl/ModuleToGenType.java | 241 --- .../generator/impl/RpcActionGenHelper.java | 329 ---- .../generator/yang/types/BaseYangTypes.java | 245 --- .../GroupingDefinitionDependencySort.java | 153 -- .../generator/yang/types/NodeWrappedType.java | 62 - .../generator/yang/types/TypeGenHelper.java | 502 ------ .../yang/types/TypeProviderImpl.java | 1074 ------------ .../generator/impl/AugmentToGenTypeTest.java | 743 -------- .../generator/impl/AuxiliaryGenUtilsTest.java | 383 ----- .../impl/BindingGeneratorImplTest.java | 413 ----- .../javav2/generator/impl/Bug8542Test.java | 43 - .../javav2/generator/impl/Bug8575Test.java | 49 - .../GeneratedClassLoadingStrategyTest.java | 34 - .../impl/RpcActionGenHelperTest.java | 310 ---- .../generator/impl/UnionTypeDefTest.java | 68 - .../action/examples/MyActionCallInput.java | 24 - .../action/examples/MyActionCallOutput.java | 25 - .../MyActionModuleMyActionCallAction.java | 47 - .../impl/action/examples/MyCont.java | 18 - .../action/examples/ListActionCallInput.java | 24 - .../action/examples/ListActionCallOutput.java | 26 - .../ListActionModuleListActionCall.java | 48 - .../impl/list/action/examples/MyList.java | 19 - .../impl/list/action/examples/MyListKey.java | 32 - .../impl/rpc/examples/MyCallInput.java | 24 - .../impl/rpc/examples/MyCallOutput.java | 25 - .../impl/rpc/examples/MyModuleMyCallRpc.java | 43 - .../test/resources/anydata/test-anydata.yang | 24 - .../test/resources/anyxml/test-anyxml.yang | 24 - .../test-augment-choice-case.yang | 140 -- .../test-augment-identifier.yang | 39 - .../test-augment-uses-grouping.yang | 38 - .../augment-group/test-augment-uses.yang | 29 - .../resources/augment-group/test-augment.yang | 22 - .../src/test/resources/base/test-bits.yang | 26 - .../base/test-leaf-with-description.yang | 13 - .../src/test/resources/base/test-module.yang | 10 - .../base/test-rpc-and-notification.yang | 25 - .../src/test/resources/base/test-union.yang | 18 - .../base/with_import/test-import.yang | 11 - .../with_import/test-typedef-with-import.yang | 17 - .../bug-8542/recursive-uses-augment.yang | 53 - .../src/test/resources/bug-8575/foo.yang | 21 - .../choice/test-choice-case-choice.yang | 94 - .../test/resources/choice/test-choice.yang | 29 - .../test/resources/generator/apple-test.yang | 21 - .../resources/generator/my-rpc-module.yang | 21 - .../resources/generator/test-augment.yang | 17 - .../test/resources/generator/test-cont.yang | 13 - .../test/resources/generator/test-leaf.yang | 12 - .../test/resources/generator/test-list.yang | 25 - .../test/resources/generator/test-type.yang | 13 - .../resources/generator/test-typedef.yang | 38 - .../test/resources/generator/test-union.yang | 16 - .../src/test/resources/generator/test.yang | 11 - .../resources/identity/identity-import.yang | 11 - .../src/test/resources/identity/identity.yang | 27 - .../test/resources/identity/identity2.yang | 15 - .../test/resources/identity/identity3.yang | 25 - .../test/resources/identity/identity4.yang | 24 - .../src/test/resources/ietf/iana-if-type.yang | 1516 ----------------- .../test/resources/ietf/ietf-inet-types.yang | 418 ----- .../test/resources/ietf/ietf-interfaces.yang | 469 ----- .../test/resources/ietf/ietf-yang-types.yang | 396 ----- .../test/resources/leafref/test-leafref.yang | 34 - .../test/resources/leafref/test-leafref2.yang | 34 - .../test/resources/leafref/test-leafref3.yang | 27 - .../leafref_typedef_union/bug8449.yang | 49 - .../test/resources/list/test-leaf-list.yang | 24 - .../src/test/resources/list/test-list.yang | 20 - .../src/test/resources/list/test-list2.yang | 25 - .../resources/namespace/class-type-test.yang | 25 - .../namespace/namespace-test-dto.yang | 21 - .../namespace/namespace-test-foo1.yang | 21 - .../resources/operations/test-action.yang | 48 - .../union-test-models/abstract-topology.yang | 120 -- ...endaylight-binding-top-level-via-uses.yang | 22 - .../opendaylight-sal-test-store.yang | 49 - .../test-augment-statement1.yang | 24 - .../test-augment-statement2.yang | 38 - .../uses-statement/test-identity-base.yang | 23 - .../uses-statement/test-identity.yang | 22 - .../uses-statement/test-typeref-base.yang | 17 - .../uses-statement/test-typeref.yang | 32 - .../uses-statement/test-typeref2.yang | 30 - .../uses-statement/test-uses-choice.yang | 22 - .../test-uses-leaf-innertype-base.yang | 31 - .../test-uses-leaf-innertype.yang | 12 - .../test-uses-leaf-innertype2-base.yang | 58 - .../test-uses-leaf-innertype2.yang | 12 - .../test-uses-leaf-innertype3-base.yang | 15 - .../test-uses-leaf-innertype3.yang | 45 - .../uses-statement/test-uses-list.yang | 25 - .../test-uses-statement-augment.yang | 25 - .../uses-statement/test-uses-statement1.yang | 19 - .../uses-statement/test-uses-statement2.yang | 18 - .../mdsal-binding2-generator-util/pom.xml | 80 - .../generator/util/AbstractBaseType.java | 146 -- .../generator/util/BindingGeneratorUtil.java | 528 ------ .../javav2/generator/util/BindingTypes.java | 68 - .../generator/util/FormattingUtils.java | 114 -- .../javav2/generator/util/JavaIdentifier.java | 29 - .../util/JavaIdentifierNormalizer.java | 566 ------ .../generator/util/ReferencedTypeImpl.java | 57 - .../javav2/generator/util/TypeComments.java | 62 - .../binding/javav2/generator/util/Types.java | 453 ----- .../generator/util/YangSnippetCleaner.java | 132 -- .../type/builder/AbstractGeneratedType.java | 225 --- .../builder/AbstractGeneratedTypeBuilder.java | 309 ---- .../type/builder/AbstractTypeMember.java | 131 -- .../builder/AbstractTypeMemberBuilder.java | 170 -- .../builder/AnnotationTypeBuilderImpl.java | 318 ---- .../generated/type/builder/ConstantImpl.java | 99 -- .../type/builder/EnumerationBuilderImpl.java | 362 ---- .../builder/GeneratedPropertyBuilderImpl.java | 74 - .../type/builder/GeneratedPropertyImpl.java | 70 - .../type/builder/GeneratedTOBuilderImpl.java | 374 ---- .../builder/GeneratedTypeBuilderImpl.java | 191 --- .../type/builder/MethodParameterImpl.java | 72 - .../builder/MethodSignatureBuilderImpl.java | 105 -- .../type/builder/MethodSignatureImpl.java | 97 -- .../util/JavaIdentifierNormalizerTest.java | 502 ------ .../util/YangSnippetCleanerTest.java | 45 - .../builder/EnumerationBuilderImplTest.java | 151 -- .../test/resources/yangs/break_ws/bad-ws.yang | 48 - .../yangs/break_ws/fixed-bad-ws.yang | 21 - .../mdsal-binding2-java-api-generator/pom.xml | 165 -- .../java/api/generator/BuilderGenerator.java | 53 - .../java/api/generator/EnumGenerator.java | 45 - .../java/api/generator/GeneratorJavaFile.java | 228 --- .../api/generator/InterfaceGenerator.java | 49 - .../java/api/generator/TOGenerator.java | 53 - .../AbstractBigRangeGenerator.java | 79 - .../AbstractPrimitiveRangeGenerator.java | 135 -- .../AbstractRangeGenerator.java | 132 -- .../AbstractSubIntegerRangeGenerator.java | 22 - ...AbstractUnsignedIntegerRangeGenerator.java | 36 - .../BigDecimalRangeGenerator.java | 48 - .../BigIntegerRangeGenerator.java | 42 - .../range_generators/ByteRangeGenerator.java | 19 - .../IntegerRangeGenerator.java | 24 - .../range_generators/LengthGenerator.java | 117 -- .../range_generators/LongRangeGenerator.java | 25 - .../range_generators/ShortRangeGenerator.java | 19 - .../generator/range_generators/TypeUtils.java | 59 - .../Uint16RangeGenerator.java | 21 - .../Uint32RangeGenerator.java | 22 - .../Uint64RangeGenerator.java | 24 - .../range_generators/Uint8RangeGenerator.java | 21 - .../api/generator/renderers/BaseRenderer.java | 359 ---- .../generator/renderers/BuilderRenderer.java | 379 ----- .../generator/renderers/ClassRenderer.java | 306 ---- .../api/generator/renderers/EnumRenderer.java | 56 - .../renderers/InterfaceRenderer.java | 215 --- .../renderers/UnionBuilderRenderer.java | 35 - .../generator/renderers/UnionRenderer.java | 240 --- .../YangModuleInfoTemplateRenderer.java | 229 --- .../AlphabeticallyTypeMemberComparator.java | 26 - .../generator/util/JavaCodePrettyPrint.java | 256 --- .../api/generator/util/TextTemplateUtil.java | 593 ------- ...builderConstructorHelperTemplate.scala.txt | 33 - .../api/generator/builderTemplate.scala.txt | 547 ------ .../api/generator/classTemplate.scala.txt | 211 --- .../classTemplateConstructors.scala.txt | 76 - .../classTemplateRestrictions.scala.txt | 27 - .../classTemplateUnionConstr.scala.txt | 27 - .../api/generator/constantsTemplate.scala.txt | 53 - .../java/api/generator/enumTemplate.scala.txt | 64 - .../api/generator/interfaceTemplate.scala.txt | 40 - .../generator/modelProviderTemplate.scala.txt | 21 - .../generator/unionBuilderTemplate.scala.txt | 35 - .../api/generator/unionTemplate.scala.txt | 85 - .../yangModuleInfoTemplate.scala.txt | 153 -- .../api/generator/GeneratorJavaFileTest.java | 82 - .../renderers/BuilderRendererTest.java | 176 -- .../generator/util/TextTemplateUtilTest.java | 29 - .../base/with_import/test-import.yang | 14 - .../resources/base/with_import/test-rpc.yang | 21 - .../with_import/test-typedef-with-import.yang | 17 - .../src/test/resources/test-bits.yang | 15 - .../src/test/resources/test-decimal64.yang | 23 - .../src/test/resources/test-identityref.yang | 24 - .../test/test-operation-service.yang | 76 - .../src/test/resources/unions.yang | 45 - .../yang-template/yang-template-import.yang | 23 - .../yang-template/yang-template-test.yang | 162 -- .../pom.xml | 79 - .../api/gen/plugin/CodeGeneratorImpl.java | 194 --- binding2/mdsal-binding2-runtime/pom.xml | 36 - .../context/BindingRuntimeContext.java | 545 ------ .../context/ModuleInfoBackedContext.java | 235 --- .../util/BindingSchemaContextUtils.java | 260 --- .../runtime/javassist/ClassCustomizer.java | 28 - .../runtime/javassist/ClassGenerator.java | 28 - .../runtime/javassist/JavassistUtils.java | 372 ---- .../runtime/javassist/MethodGenerator.java | 28 - .../javassist/SourceCodeGenerator.java | 37 - .../reflection/AugmentationFieldGetter.java | 113 -- .../reflection/BindingReflections.java | 667 -------- .../context/BindingRuntimeContextTest.java | 39 - .../context/ModuleInfoBackedContextTest.java | 39 - .../util/BindingSchemaContextUtilsTest.java | 47 - .../runtime/javassist/JavassistUtilsTest.java | 64 - .../AugmentationFieldGetterTest.java | 68 - .../reflection/BindingReflectionsTest.java | 92 - .../reflection/test/mock/FooChild.java | 15 - .../reflection/test/mock/GroupingFoo.java | 14 - .../src/test/resources/yang/test-runtime.yang | 22 - binding2/mdsal-binding2-spec/pom.xml | 47 - .../binding/javav2/spec/base/Action.java | 36 - .../javav2/spec/base/BaseIdentity.java | 16 - .../javav2/spec/base/IdentifiableItem.java | 55 - .../mdsal/binding/javav2/spec/base/Input.java | 17 - .../javav2/spec/base/InstanceIdentifier.java | 566 ------ .../spec/base/InstanceIdentifierBuilder.java | 81 - .../base/InstanceIdentifierBuilderImpl.java | 134 -- .../javav2/spec/base/Instantiable.java | 25 - .../mdsal/binding/javav2/spec/base/Item.java | 40 - .../spec/base/KeyedInstanceIdentifier.java | 58 - .../binding/javav2/spec/base/ListAction.java | 40 - .../javav2/spec/base/Notification.java | 22 - .../binding/javav2/spec/base/Operation.java | 18 - .../binding/javav2/spec/base/Output.java | 16 - .../mdsal/binding/javav2/spec/base/Rpc.java | 27 - .../binding/javav2/spec/base/RpcCallback.java | 21 - .../javav2/spec/base/TreeArgument.java | 51 - .../binding/javav2/spec/base/TreeNode.java | 24 - .../binding/javav2/spec/base/TreeRoot.java | 16 - .../javav2/spec/runtime/BindingCodec.java | 38 - .../spec/runtime/BindingDeserializer.java | 29 - .../spec/runtime/BindingNamespaceType.java | 59 - .../spec/runtime/BindingSerializer.java | 29 - .../runtime/BindingStreamEventWriter.java | 494 ------ .../javav2/spec/runtime/CodeHelpers.java | 203 --- .../spec/runtime/NotificationListener.java | 32 - .../spec/runtime/TreeNodeSerializer.java | 30 - .../TreeNodeSerializerImplementation.java | 28 - .../runtime/TreeNodeSerializerRegistry.java | 27 - .../runtime/YangModelBindingProvider.java | 30 - .../javav2/spec/runtime/YangModuleInfo.java | 71 - .../javav2/spec/structural/Augmentable.java | 45 - .../javav2/spec/structural/Augmentation.java | 22 - .../spec/structural/AugmentationHolder.java | 31 - .../javav2/spec/structural/TreeChildNode.java | 31 - .../src/site/asciidoc/binding-2.adoc | 1238 -------------- .../src/test/resources/_.yang | 83 - .../src/test/resources/__.yang | 26 - .../test/resources/odl-test-double..dot.yang | 14 - .../src/test/resources/odl-test-foo-Bar.yang | 14 - .../src/test/resources/odl-test-foo-bar.yang | 14 - .../src/test/resources/odl-test-foo.bar.yang | 14 - .../test/resources/odl-test-identifiers.yang | 52 - .../test/resources/odl-test-namespaces.yang | 78 - .../src/test/resources/odl-test-toplevel.yang | 99 -- binding2/mdsal-binding2-spi/pom.xml | 72 - .../javav2/spi/ForwardingDataBroker.java | 60 - .../javav2/spi/ForwardingReadTransaction.java | 50 - .../spi/ForwardingWriteTransaction.java | 76 - binding2/mdsal-binding2-test-model/pom.xml | 44 - .../data/ContInt32RefUnionInt32Builder.java | 26 - .../rev170516/data/ContRefBuilder.java | 26 - .../type/Int32StringUnionBuilder.java | 25 - .../rev180408/type/NumberUnionBuilder.java | 28 - .../src/main/yang/bug8449.yang | 60 - .../yang/opendaylight-mdsal-augment-test.yang | 189 -- .../yang/opendaylight-mdsal-binding-test.yang | 147 -- .../src/main/yang/test-list.yang | 25 - .../src/main/yang/test-operation-service.yang | 76 - .../src/main/yang/test-pattern.yang | 37 - .../src/main/yang/test-runtime.yang | 22 - .../src/main/yang/test-typedef.yang | 47 - .../src/main/yang/test-unsigned-integer.yang | 93 - .../src/main/yang/test.yang | 18 - binding2/mdsal-binding2-util/pom.xml | 34 - .../binding/javav2/util/BindingMapping.java | 189 -- .../javav2/util/StringValueObjectFactory.java | 135 -- binding2/mdsal-model-binding2-parent/pom.xml | 135 -- binding2/pom.xml | 54 - features/features-mdsal-experimental/pom.xml | 32 - features/odl-mdsal-binding2-api/pom.xml | 55 - features/odl-mdsal-binding2-base/pom.xml | 39 - .../src/main/feature/feature.xml | 6 - .../odl-mdsal-binding2-dom-adapter/pom.xml | 36 - features/odl-mdsal-binding2-runtime/pom.xml | 62 - .../src/main/feature/feature.xml | 8 - features/odl-mdsal-binding2/pom.xml | 37 - features/pom.xml | 7 - model-binding2/pom.xml | 35 - model-binding2/yang-ext/pom.xml | 28 - .../yang-ext/src/main/yang/yang-ext.yang | 78 - pom.xml | 2 - 518 files changed, 54317 deletions(-) delete mode 100644 binding2/mdsal-binding2-api/pom.xml delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/BindingService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/CursorAwareWriteTransaction.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataBroker.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohort.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohortRegistry.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursor.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursorProvider.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifier.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListener.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeModification.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducer.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerFactory.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeWriteCursor.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPoint.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointListener.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationPublishService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/ReadTransaction.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionConsumerRegistry.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionProviderService.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/Transaction.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChain.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainClosedException.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainListener.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionFactory.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModification.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/WriteTransaction.java delete mode 100644 binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/annotation/RoutingContext.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifierTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningExceptionTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopExceptionTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyExceptionTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerExceptionTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedExceptionTest.java delete mode 100644 binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModificationTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/pom.xml delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/ContextReferenceExtractor.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractor.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/GetValueRouteContextExtractor.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/BindingDOMDataBrokerAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortRegistryAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationListenerAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationPublishServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/NotificationListenerInvoker.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/ActionServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationProviderServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMActionResultFuture.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMRpcResultFuture.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/RpcServiceAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMReadTransactionAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMTransactionChainAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMWriteTransactionAdapter.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDOMOperationAdapterRegistration.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDataTreeListenerRegistration.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedDataBroker.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedTransaction.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractWriteTransaction.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilder.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/BindingDOMAdapterBuilder.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/AdapterLoader.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoader.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractorTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilderTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoaderTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractDataBrokerTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractSchemaAwareTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BasicLeafValueTest.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingBrokerTestFactory.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingTestContext.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/DataBrokerTestCustomizer.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/MockSchemaService.java delete mode 100644 binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/transaction/BindingDOMTransactionChainAdapterTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/pom.xml delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/AugmentationReader.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCachingCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeNodeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingNormalizedNodeWriterFactory.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingTreeCodecFactory.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/serializer/BindingNormalizedNodeSerializer.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/api/TreeNodeSerializerGenerator.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StaticBindingProperty.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StreamWriterGenerator.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/TreeNodeSerializerPrototype.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractGenerator.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractStreamWriterGenerator.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentSerializerSource.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentableDataNodeContainerEmitterSource.java delete mode 100755 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractDataNodeContainerSerializerSource.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractSource.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractTreeNodeSerializerSource.java delete mode 100755 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AnyxmlCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingNormalizedNodeCodecRegistry.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingToNormalizedNodeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/FutureSchema.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentifiableItemCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentityCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/MissingSchemaException.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/OperationInputCodec.java delete mode 100755 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnionTypeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnmappedOperationInputCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/AbstractBindingNormalizedNodeCacheHolder.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/BindingNormalizedNodeCache.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/CachingNormalizedNodeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/AugmentationNodeContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/CaseNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ChoiceNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ContainerNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/KeyedListNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ListNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/NotificationCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/SchemaRootCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ValueContext.java delete mode 100755 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/AnyxmlNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/BindingCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecPrototype.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/IncorrectNestingException.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LazyTreeNode.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LeafNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingClassInLoadingStrategyException.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingSchemaForClassException.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeContextSupplier.java delete mode 100755 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/TreeNodeCodecContext.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/AugmentableDispatchSerializer.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/BindingToNormalizedStreamWriter.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/CachingNormalizedNodeSerializer.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ChoiceDispatchSerializer.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ForwardingBindingStreamEventWriter.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/NormalizedNodeWithAddChildWriter.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/BitsCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/CompositeValueCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EncapsulatedValueCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ReflectionBasedCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ValueTypeCodec.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/BindingStructuralType.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModification.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyTreeNodeModification.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedContainerNode.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedDOMNotification.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AbstractBindingRuntimeTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierSerializeDeserializeTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/LeafrefSerializeDeserializeTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodecTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NormalizedNodeSerializeDeserializeTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/TypedefTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContextTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodecTest.java delete mode 100644 binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModificationTest.java delete mode 100644 binding2/mdsal-binding2-generator-api/pom.xml delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/BindingGenerator.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ClassLoadingStrategy.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ModuleInfoRegistry.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/context/ModuleContext.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/spi/TypeProvider.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AccessModifier.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AnnotationType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/BaseTypeWithRestrictions.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/CodeGenerator.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ConcreteType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Constant.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/DocumentedType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Enumeration.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedProperty.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTransferObject.java delete mode 100755 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTypeForBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/MethodSignature.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ParameterizedType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Restrictions.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Type.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeComment.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeMember.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/UnitName.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/WildcardType.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/YangSourceDefinition.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/AnnotationTypeBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/EnumBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedPropertyBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTOBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilderBase.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/MethodSignatureBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/TypeMemberBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-impl/pom.xml delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenType.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtils.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImpl.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GenHelperUtil.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategy.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/ModuleToGenType.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelper.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/BaseYangTypes.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/GroupingDefinitionDependencySort.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/NodeWrappedType.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeGenHelper.java delete mode 100755 binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeProviderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenTypeTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtilsTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImplTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8542Test.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8575Test.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategyTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelperTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/UnionTypeDefTest.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallInput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallOutput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionModuleMyActionCallAction.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyCont.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallInput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallOutput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionModuleListActionCall.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyList.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyListKey.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallInput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallOutput.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyModuleMyCallRpc.java delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/anydata/test-anydata.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/anyxml/test-anyxml.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-choice-case.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-identifier.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses-grouping.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-bits.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-leaf-with-description.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-module.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-rpc-and-notification.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-union.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-import.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-typedef-with-import.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8542/recursive-uses-augment.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8575/foo.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice-case-choice.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/apple-test.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/my-rpc-module.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-augment.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-cont.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-leaf.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-list.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-type.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-typedef.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-union.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity-import.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity3.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity4.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/iana-if-type.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-inet-types.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-interfaces.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-yang-types.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref3.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-leaf-list.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/class-type-test.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-dto.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-foo1.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/operations/test-action.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/union-test-models/abstract-topology.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-binding-top-level-via-uses.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-sal-test-store.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement1.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity-base.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref-base.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-choice.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype-base.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2-base.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3-base.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-list.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement-augment.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement1.yang delete mode 100644 binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement2.yang delete mode 100644 binding2/mdsal-binding2-generator-util/pom.xml delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/AbstractBaseType.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingGeneratorUtil.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingTypes.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/FormattingUtils.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifier.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizer.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/ReferencedTypeImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/TypeComments.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/Types.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleaner.java delete mode 100755 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedType.java delete mode 100755 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMember.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AnnotationTypeBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/ConstantImpl.java delete mode 100755 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java delete mode 100755 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodParameterImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureImpl.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizerTest.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleanerTest.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImplTest.java delete mode 100644 binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/bad-ws.yang delete mode 100644 binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/fixed-bad-ws.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/pom.xml delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/BuilderGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/EnumGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFile.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/InterfaceGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/TOGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractBigRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractPrimitiveRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractSubIntegerRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractUnsignedIntegerRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigDecimalRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigIntegerRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ByteRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/IntegerRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LengthGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LongRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ShortRangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/TypeUtils.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint16RangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint32RangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint64RangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint8RangeGenerator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BaseRenderer.java delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/ClassRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/EnumRenderer.java delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/InterfaceRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionBuilderRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/YangModuleInfoTemplateRenderer.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/AlphabeticallyTypeMemberComparator.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/JavaCodePrettyPrint.java delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtil.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderConstructorHelperTemplate.scala.txt delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateConstructors.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateRestrictions.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateUnionConstr.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/constantsTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/enumTemplate.scala.txt delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/interfaceTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/modelProviderTemplate.scala.txt delete mode 100755 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionBuilderTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/yangModuleInfoTemplate.scala.txt delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFileTest.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRendererTest.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtilTest.java delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-import.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-rpc.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-typedef-with-import.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/test-bits.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/test-decimal64.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/test-identityref.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/test/test-operation-service.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/unions.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-import.yang delete mode 100644 binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-test.yang delete mode 100644 binding2/mdsal-binding2-maven-api-gen-plugin/pom.xml delete mode 100644 binding2/mdsal-binding2-maven-api-gen-plugin/src/main/java/org/opendaylight/mdsal/binding/javav2/maven/api/gen/plugin/CodeGeneratorImpl.java delete mode 100644 binding2/mdsal-binding2-runtime/pom.xml delete mode 100755 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContext.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContext.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtils.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassCustomizer.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassGenerator.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtils.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/MethodGenerator.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/SourceCodeGenerator.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetter.java delete mode 100644 binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflections.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContextTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContextTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtilsTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtilsTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetterTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflectionsTest.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/FooChild.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/GroupingFoo.java delete mode 100644 binding2/mdsal-binding2-runtime/src/test/resources/yang/test-runtime.yang delete mode 100644 binding2/mdsal-binding2-spec/pom.xml delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Action.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/BaseIdentity.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/IdentifiableItem.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Input.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifier.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilder.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilderImpl.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Instantiable.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Item.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/KeyedInstanceIdentifier.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/ListAction.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Notification.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Operation.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Output.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Rpc.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/RpcCallback.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeArgument.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeNode.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeRoot.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingCodec.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingDeserializer.java delete mode 100755 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingNamespaceType.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingSerializer.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingStreamEventWriter.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/CodeHelpers.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/NotificationListener.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializer.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerImplementation.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerRegistry.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModelBindingProvider.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModuleInfo.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentable.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentation.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/AugmentationHolder.java delete mode 100644 binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/TreeChildNode.java delete mode 100644 binding2/mdsal-binding2-spec/src/site/asciidoc/binding-2.adoc delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/_.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/__.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-double..dot.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-Bar.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-bar.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo.bar.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-identifiers.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-namespaces.yang delete mode 100644 binding2/mdsal-binding2-spec/src/test/resources/odl-test-toplevel.yang delete mode 100644 binding2/mdsal-binding2-spi/pom.xml delete mode 100644 binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingDataBroker.java delete mode 100644 binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingReadTransaction.java delete mode 100644 binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingWriteTransaction.java delete mode 100644 binding2/mdsal-binding2-test-model/pom.xml delete mode 100644 binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContInt32RefUnionInt32Builder.java delete mode 100644 binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContRefBuilder.java delete mode 100755 binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/opendaylight/params/xml/ns/yang/mdsal/test/binding/rev140701/type/Int32StringUnionBuilder.java delete mode 100644 binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/test/unsigned/rev180408/type/NumberUnionBuilder.java delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/bug8449.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang delete mode 100755 binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-binding-test.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/test-list.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/test-operation-service.yang delete mode 100755 binding2/mdsal-binding2-test-model/src/main/yang/test-pattern.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/test-runtime.yang delete mode 100755 binding2/mdsal-binding2-test-model/src/main/yang/test-typedef.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/test-unsigned-integer.yang delete mode 100644 binding2/mdsal-binding2-test-model/src/main/yang/test.yang delete mode 100644 binding2/mdsal-binding2-util/pom.xml delete mode 100644 binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/BindingMapping.java delete mode 100644 binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/StringValueObjectFactory.java delete mode 100644 binding2/mdsal-model-binding2-parent/pom.xml delete mode 100644 binding2/pom.xml delete mode 100644 features/odl-mdsal-binding2-api/pom.xml delete mode 100644 features/odl-mdsal-binding2-base/pom.xml delete mode 100644 features/odl-mdsal-binding2-base/src/main/feature/feature.xml delete mode 100644 features/odl-mdsal-binding2-dom-adapter/pom.xml delete mode 100644 features/odl-mdsal-binding2-runtime/pom.xml delete mode 100644 features/odl-mdsal-binding2-runtime/src/main/feature/feature.xml delete mode 100644 features/odl-mdsal-binding2/pom.xml delete mode 100644 model-binding2/pom.xml delete mode 100644 model-binding2/yang-ext/pom.xml delete mode 100644 model-binding2/yang-ext/src/main/yang/yang-ext.yang diff --git a/artifacts/pom.xml b/artifacts/pom.xml index ad705d8a19..83d67a6ba8 100644 --- a/artifacts/pom.xml +++ b/artifacts/pom.xml @@ -175,79 +175,6 @@ 2.0.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-maven-api-gen-plugin - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-runtime - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-dom-codec - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-api - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-dom-adapter - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-spi - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-test-model - 0.16.0-SNAPSHOT - test - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-spec - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-java-api-generator - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-generator-util - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal - mdsal-binding2-util - 0.16.0-SNAPSHOT - - - org.opendaylight.mdsal.model.binding2 - yang-ext - 2013.09.07.16.0-SNAPSHOT - - org.opendaylight.mdsal mdsal-eos-common-api @@ -343,43 +270,6 @@ xml - - - ${project.groupId} - odl-mdsal-binding2 - 4.0.0-SNAPSHOT - features - xml - - - ${project.groupId} - odl-mdsal-binding2-base - 4.0.0-SNAPSHOT - features - xml - - - ${project.groupId} - odl-mdsal-binding2-runtime - 4.0.0-SNAPSHOT - features - xml - - - ${project.groupId} - odl-mdsal-binding2-api - 4.0.0-SNAPSHOT - features - xml - - - ${project.groupId} - odl-mdsal-binding2-dom-adapter - 4.0.0-SNAPSHOT - features - xml - - ${project.groupId} diff --git a/binding2/mdsal-binding2-api/pom.xml b/binding2/mdsal-binding2-api/pom.xml deleted file mode 100644 index 6e61d3acd3..0000000000 --- a/binding2/mdsal-binding2-api/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-api - 0.16.0-SNAPSHOT - bundle - - - - com.google.guava - guava - - - org.opendaylight.mdsal - mdsal-common-api - - - org.opendaylight.mdsal.model - general-entity - - - org.opendaylight.yangtools - concepts - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - org.opendaylight.mdsal - yang-binding - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-data-api - - - org.osgi - org.osgi.core - - - org.apache.commons - commons-lang3 - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - !javax.annotation, - * - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - - scm:git:http://git.opendaylight.org/gerrit/mdsal.git - scm:git:ssh://git.opendaylight.org:29418/mdsal.git - HEAD - https://wiki.opendaylight.org/view/MD-SAL:Main - - diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/BindingService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/BindingService.java deleted file mode 100644 index e24e5efc26..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/BindingService.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; - -/** - * Marker interface for MD-SAL services which are available for users of MD-SAL. - * - *

- * BindingService is marker interface for infrastructure services provided by - * the SAL. These services may be session-specific, and wrapped by custom - * delegator patterns in order to introduce additional semantics / checks - * to the system. - * - */ -@Beta -public interface BindingService { -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/CursorAwareWriteTransaction.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/CursorAwareWriteTransaction.java deleted file mode 100644 index bdf4268da5..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/CursorAwareWriteTransaction.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.function.BiConsumer; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.TransactionCommitFailedException; - -/** - * Write transaction that provides cursor's with write access to the data tree. - */ -@Beta -public interface CursorAwareWriteTransaction extends DataTreeCursorProvider { - - /** - * Create a {@link DataTreeWriteCursor} anchored at the specified path. - * There can only be one cursor open at a time. - * - *

- * @param path Path at which the cursor is to be anchored - * @return write cursor at the desired location. - * @throws IllegalStateException when there's an open cursor, or this transaction is closed already. - */ - @Nullable - @Override - DataTreeCursor createCursor(@Nonnull DataTreeIdentifier path); - - /** - * Cancels the transaction. - * - *

- * Transactions can only be cancelled if it was not yet submited. - * - *

- * Invoking cancel() on failed or already canceled will have no effect, and transaction is - * considered cancelled. - * - *

- * Invoking cancel() on finished transaction (future returned by {@link #submit(BiConsumer)} already - * successfully completed) will always fail (return false). - * - * @return false if the task could not be cancelled, typically because it has already - * completed normally; true otherwise - * - */ - boolean cancel(); - - /** - * Submits this transaction to be asynchronously applied to update the logical data tree. Callback - * conveys the result of applying the data changes. - * - *

- * This call logically seals the transaction, which prevents the client from further changing - * data tree using this transaction's cursor. Any subsequent calls to - * createCursorCursor(DOMDataTreeIdentifier - * or any of the cursor's methods will fail with {@link IllegalStateException}. - * - *

- * The transaction is marked as submitted and enqueued into the shard back-end for - * processing. - * - * @param callback result callback - * @param result type - */ - void submit(BiConsumer callback); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataBroker.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataBroker.java deleted file mode 100644 index 536de55eca..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataBroker.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; - -/** - * Provides access to a conceptual data tree store and also provides the ability to - * subscribe for changes to data under a given branch of the tree. - * - *

- * All operations on the data tree are performed via one of the transactions: - *

    - *
  • Read-Only - allocated using {@link #newReadOnlyTransaction()} - *
  • Write-Only - allocated using {@link #newWriteOnlyTransaction()} - *
- * - *

- * These transactions provide a stable isolated view of data tree, which is guaranteed to be not - * affected by other concurrent transactions, until transaction is committed. - * - *

- * For a detailed explanation of how transaction are isolated and how transaction-local changes are - * committed to global data tree, see {@link ReadTransaction}, {@link WriteTransaction} - * and {@link WriteTransaction#commit()}. - * - *

- * It is strongly recommended to use the type of transaction, which provides only the minimal - * capabilities you need. This allows for optimizations at the data broker / data store level. For - * example, implementations may optimize the transaction for reading if they know ahead of time that - * you only need to read data - such as not keeping additional meta-data, which may be required for - * write transactions. - * - *

- * Implementation Note: This interface is not intended to be implemented by users of MD-SAL, - * but only to be consumed by them. - */ -@Beta -public interface DataBroker extends BindingService, TransactionFactory, DataTreeService { - /** - * Create a new transaction chain. The chain will be initialized to read from its backing datastore, with - * no outstanding transaction. Listener will be registered to handle chain-level events. - * - * @param listener Transaction chain event listener - * @return A new transaction chain. - */ - TransactionChain createTransactionChain(TransactionChainListener listener); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohort.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohort.java deleted file mode 100644 index 45394d4483..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohort.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import java.util.function.BiConsumer; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.DataValidationFailedException; -import org.opendaylight.mdsal.common.api.PostCanCommitStep; - -/** - * Commit cohort participating in commit of data modification, which can validate data tree - * modifications, with option to reject supplied modification, and with callbacks describing state - * of commit. - * - *

Performance implications

- * - * {@link DataTreeCommitCohort}s are hooked up into commit of data tree changes and MAY - * negatively affect performance of data broker / store. - * - *

- * Implementations of this interface are discouraged, unless you really need ability to veto data - * tree changes, or to provide external state change in sync with visibility of commited data. - * - *

Implementation requirements

- * - *

Correctness assumptions

Implementation SHOULD use only provided - * {@link DataTreeModification} for validation purposes. - * - *

- * Use of any other external mutable state is discouraged, implementation MUST NOT use any - * transaction related APIs on same data broker / data store instance during invocation of - * callbacks, except ones provided as argument. Note that this MAY BE enforced by some - * implementations of {@link DataBroker} or Commit coordinator - * - *

- * Note that this may be enforced by some implementations of {@link DataTreeCommitCohortRegistry} - * and such calls may fail. - * - *

DataTreeCandidate assumptions

Implementation SHOULD NOT make any assumptions on - * {@link DataTreeModification} being successfully committed until associated - * {@link PostCanCommitStep#preCommit()} and - * {@link org.opendaylight.mdsal.common.api.PostPreCommitStep#commit()} callback was invoked. - * - *

Usage patterns

- * - *

Data Tree Validator

- * - *

- * Validator is implementation, which only validates {@link DataTreeModification} and does not - * retain any state derived from edited data - does not care if {@link DataTreeModification} was - * rejected afterwards or transaction was cancelled. - * - *

- * Implementation may opt-out from receiving {@code preCommit()}, {@code commit()}, {@code abort()} - * callbacks by returning {@link PostCanCommitStep#NOOP}. - */ -@Beta -public interface DataTreeCommitCohort { - /** - * Performs canCommit? message in three-phase commit algorithm. - * - * @param txId Transaction identifier - * @param modifications the {@link DataTreeModification} to validate - * @param callback result callback - */ - void canCommit(Object txId, Collection> modifications, - BiConsumer callback); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohortRegistry.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohortRegistry.java deleted file mode 100644 index a632b2772e..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCommitCohortRegistry.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -/** - * Commit Cohort registry. - * - *

- * See {@link DataTreeCommitCohort} for more details. - * - */ -@Beta -public interface DataTreeCommitCohortRegistry { - - /** - * Register commit cohort which will participate in three-phase commit protocols of write - * transaction in data broker associated with this instance of extension. - * - * @param subtree Subtree path on which commit cohort operates. - * @param cohort Commit cohort - * @param data type - * @param cohort type - * @return Registration object for DOM Data Three Commit cohort. - */ - > ObjectRegistration registerCommitCohort( - DataTreeIdentifier subtree, T cohort); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursor.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursor.java deleted file mode 100644 index c3fceaf9ad..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursor.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import javax.annotation.concurrent.NotThreadSafe; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * A cursor holding a logical position within a conceptual data tree. It allows operations relative - * to that position, as well as moving the position up or down the tree. - */ -@Beta -@NotThreadSafe -public interface DataTreeCursor extends AutoCloseable { - - /** - * Move the cursor to the specified child of the current position. - * - * @param child Child identifier - * @throws IllegalArgumentException when specified identifier does not identify a valid child, - * or if that child is not an instance of {@link TreeNode}. - */ - void enter(@Nonnull TreeArgument child); - - /** - * Move the cursor to the specified child of the current position. This is the equivalent of - * multiple invocations of {@link #enter(TreeArgument)}, except the operation is performed all - * at once. - * - * @param path Nested child identifier - * @throws IllegalArgumentException when specified path does not identify a valid child, or if - * that child is not an instance of {@link TreeNode}. - */ - void enter(@Nonnull TreeArgument... path); - - /** - * Move the cursor to the specified child of the current position. This is equivalent to - * {@link #enter(TreeArgument...)}, except it takes an {@link Iterable} argument. - * - * @param path Nested child identifier - * @throws IllegalArgumentException when specified path does not identify a valid child, or if - * that child is not an instance of {@link TreeNode}. - */ - void enter(@Nonnull Iterable> path); - - /** - * Move the cursor up to the parent of current position. This is equivalent of invoking - * exit(1). - * - * @throws IllegalStateException when exiting would violate containment, typically by attempting - * to exit more levels than previously entered. - */ - void exit(); - - /** - * Move the cursor up by specified amounts of steps from the current position. This is - * equivalent of invoking {@link #exit()} multiple times, except the operation is performed - * atomically. - * - * @param depth number of steps to exit - * @throws IllegalArgumentException when depth is negative. - * @throws IllegalStateException when exiting would violate containment, typically by attempting - * to exit more levels than previously entered. - */ - void exit(int depth); - - /** - * Close this cursor. Attempting any further operations on the cursor will lead to undefined - * behavior. - */ - @Override - void close() throws Exception; -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursorProvider.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursorProvider.java deleted file mode 100644 index 7bc0fa81fd..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeCursorProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Provides access to {#link DataTreeCursor}'s anchored at the specified path. - */ -@Beta -public interface DataTreeCursorProvider { - - /** - * Create a new {@link DataTreeCursor} at specified path. May fail if specified path - * does not exist. - * - * @param path Path at which the cursor is to be anchored - * @param data tree type - * @return A new cursor, or null if the path does not exist. - * @throws IllegalStateException if there is another cursor currently open, or the transaction - * is already closed (closed or submitted). - */ - @Nullable - DataTreeCursor createCursor(@Nonnull DataTreeIdentifier path); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifier.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifier.java deleted file mode 100644 index 6eda831e44..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifier.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.io.Serializable; -import java.util.Objects; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.yangtools.concepts.Immutable; -import org.opendaylight.yangtools.concepts.Path; - -/** - * A unique identifier for a particular subtree. It's composed of the logical - * data store type and the instance identifier of the root node. - */ -@Beta -public final class DataTreeIdentifier implements Immutable, - Path>, Serializable { - - private static final long serialVersionUID = 1L; - private final InstanceIdentifier rootIdentifier; - private final LogicalDatastoreType datastoreType; - - private DataTreeIdentifier(final LogicalDatastoreType datastoreType, final InstanceIdentifier rootIdentifier) { - this.datastoreType = requireNonNull(datastoreType); - this.rootIdentifier = requireNonNull(rootIdentifier); - } - - public static DataTreeIdentifier create(final LogicalDatastoreType datastoreType, - final InstanceIdentifier rootIdentifier) { - return new DataTreeIdentifier<>(datastoreType, rootIdentifier); - } - - /** - * Return the logical data store type. - * - * @return Logical data store type. Guaranteed to be non-null. - */ - @Nonnull - public LogicalDatastoreType getDatastoreType() { - return datastoreType; - } - - /** - * Return the {@link InstanceIdentifier} of the root node. - * - * @return Instance identifier corresponding to the root node. - */ - @Nonnull - public InstanceIdentifier getRootIdentifier() { - return rootIdentifier; - } - - /** - * Checks whether this identifier contains some other. - * @param other Other path, may not be null. - * @return true/false - */ - @Override - public boolean contains(@Nonnull final DataTreeIdentifier other) { - return datastoreType == other.datastoreType && rootIdentifier.contains(other.rootIdentifier); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof DataTreeIdentifier)) { - return false; - } - final DataTreeIdentifier other = (DataTreeIdentifier) obj; - if (datastoreType != other.datastoreType) { - return false; - } - return rootIdentifier.equals(other.rootIdentifier); - } - - @Override - public int hashCode() { - return Objects.hash(rootIdentifier, datastoreType); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListener.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListener.java deleted file mode 100644 index d428110b48..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListener.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import java.util.EventListener; -import java.util.Map; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Interface implemented by data consumers, e.g. processes wanting to act on data after it has been - * introduced to the conceptual data tree. - */ -@Beta -public interface DataTreeListener extends EventListener { - - /** - * Invoked whenever one or more registered subtrees change. The logical changes are reported, as - * well as the roll up of new state for all subscribed subtrees. - * - * @param changes The set of changes being reported. Each subscribed subtree may be present at - * most once. - * @param subtrees Per-subtree state as visible after the reported changes have been applied. - * This includes all the subtrees this listener is subscribed to, even those which have - * not changed. - */ - void onDataTreeChanged(@Nonnull Collection> changes, - @Nonnull Map, TreeNode> subtrees); - - /** - * Invoked when a subtree listening failure occurs. This can be triggered, for example, when a - * connection to external subtree source is broken. The listener will not receive any other - * callbacks, but its registration still needs to be closed to prevent resource leak. - * - * @param causes Collection of failure causes, may not be null or empty. - */ - void onDataTreeFailed(@Nonnull Collection causes); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningException.java deleted file mode 100644 index a49e507a74..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Base exception for various causes why and {@link DataTreeListener} may be terminated by the - * {@link DataTreeService} implementation. - */ -@Beta -public class DataTreeListeningException extends Exception { - - private static final long serialVersionUID = 1L; - - public DataTreeListeningException(@Nonnull String message, @Nullable Throwable cause) { - super(requireNonNull(message, "message"), cause); - } - - public DataTreeListeningException(@Nonnull String message) { - super(requireNonNull(message, "message")); - } - -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopException.java deleted file mode 100644 index cca76d4312..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; - -/** - * Exception thrown when a loop is detected in the way {@link DataTreeListener} and - * {@link DataTreeProducer} instances would be connected. - */ -@Beta -public class DataTreeLoopException extends DataTreeProducerException { - - private static final long serialVersionUID = 1L; - - public DataTreeLoopException(@Nonnull final String message, @Nonnull final Throwable cause) { - super(message, cause); - } - - public DataTreeLoopException(@Nonnull final String message) { - super(message); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeModification.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeModification.java deleted file mode 100644 index e35ad05408..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeModification.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Represents root of modification. - */ -@Beta -public interface DataTreeModification { - - /** - * Get the modification root path. This is the path of the root node - * relative to the root of InstanceIdentifier namespace. - * - * @return absolute path of the root node - */ - @Nonnull - DataTreeIdentifier getRootPath(); - - /** - * Get the modification root node. - * - * @return modification root node - */ - @Nonnull - TreeNodeModification getRootNode(); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducer.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducer.java deleted file mode 100644 index d7ab767c93..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducer.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import javax.annotation.Nonnull; - -/** - * A data producer context. It allows transactions to be submitted to the subtrees specified at - * instantiation time. At any given time there may be a single transaction open. It needs to be - * either submitted or cancelled before another one can be open. Once a transaction is submitted, it - * will proceed to be committed asynchronously. - * - *

- * Each instance has an upper bound on the number of transactions which can be in-flight, once that - * capacity is exceeded, an attempt to create a new transaction will block until some transactions - * complete. - * - *

- * Each {@link DataTreeProducer} can be in two logical states, bound and unbound, which define the - * lifecycle rules for when is it legal to create and submit transactions in relationship with - * {@link DataTreeListener} callbacks. - * - *

- * When a producer is first created, it is unbound. In this state the producer can be accessed by - * any application thread to allocate or submit transactions, as long as the 'single open - * transaction' rule is maintained. The producer and any transaction object MUST NOT be accessed, - * directly or indirectly, from a {@link DataTreeListener} callback. - * - *

- * When a producer is referenced in a call to - * {@link DataTreeService#registerListener(DataTreeListener, java.util.Collection, boolean, java.util.Collection)} - * , an attempt will be made to bind the producer to the specified {@link DataTreeListener}. Such an - * attempt will fail the producer is already bound, or it has an open transaction. Once bound, the - * producer can only be accessed from within the {@link DataTreeListener} callback on that - * particular instance. Any transaction which is not submitted by the time the callback returns will - * be implicitly cancelled. A producer becomes unbound when the listener it is bound to becomes - * unregistered. - * - */ -@Beta -public interface DataTreeProducer extends DataTreeProducerFactory, AutoCloseable { - - /** - * Allocate a new open transaction on this producer. Any and all transactions previously - * allocated must have been either submitted or cancelled by the time this method is invoked. - * - * @param isolated Indicates whether this transaction should be a barrier. A barrier transaction - * is processed separately from any preceding transactions. Non-barrier transactions may - * be merged and processed in a batch, such that any observers see the modifications - * contained in them as if the modifications were made in a single transaction. - * @return A new {@link CursorAwareWriteTransaction} - * @throws IllegalStateException if a previous transaction was not closed. - * @throws IllegalThreadStateException if the calling thread context does not match the - * lifecycle rules enforced by the producer state (e.g. bound or unbound). This - * exception is thrown on a best effort basis and programs should not rely on it for - * correct operation. - */ - @Nonnull - CursorAwareWriteTransaction createTransaction(boolean isolated); - - /** - * {@inheritDoc}. - * - *

- * When invoked on a {@link DataTreeProducer}, this method has additional restrictions. There - * may not be an open transaction from this producer. The method needs to be invoked in - * appropriate context, e.g. bound or unbound. - * - *

- * Specified subtrees must be accessible by this producer. Accessible means they are a subset of - * the subtrees specified when the producer is instantiated. The set is further reduced as child - * producers are instantiated -- if you create a producer for /a and then a child for /a/b, /a/b - * is not accessible from the first producer. - * - *

- * Once this method returns successfully, this (parent) producer loses the ability to access the - * specified paths until the resulting (child) producer is shut down. - * - * @throws IllegalStateException if there is an open transaction - * @throws IllegalArgumentException if subtrees contains a subtree which is not accessible by - * this producer - * @throws IllegalThreadStateException if the calling thread context does not match the - * lifecycle rules enforced by the producer state (e.g. bound or unbound). This - * exception is thrown on a best effort basis and programs should not rely on it for - * correct operation. - */ - @Override - @Nonnull - DataTreeProducer createProducer(@Nonnull Collection> subtrees); - - /** - * {@inheritDoc}. - * - * @throws DataTreeProducerBusyException when there is an open transaction. - */ - @Override - void close() throws DataTreeProducerException; -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyException.java deleted file mode 100644 index c005db927e..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; - -/** - * Exception indicating that the {@link DataTreeProducer} has an open user transaction and cannot be - * closed. - */ -@Beta -public class DataTreeProducerBusyException extends DataTreeProducerException { - - private static final long serialVersionUID = 1L; - - - public DataTreeProducerBusyException(@Nonnull final String message, @Nonnull final Throwable cause) { - super(requireNonNull(message, "message"), cause); - } - - public DataTreeProducerBusyException(@Nonnull final String message) { - super(requireNonNull(message, "message")); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerException.java deleted file mode 100644 index b3d1678b7c..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; - -@Beta -public class DataTreeProducerException extends Exception { - - private static final long serialVersionUID = 1L; - - public DataTreeProducerException(@Nonnull final String message, @Nonnull final Throwable cause) { - super(message, cause); - } - - public DataTreeProducerException(@Nonnull final String message) { - super(message); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerFactory.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerFactory.java deleted file mode 100644 index 8066df8c2c..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; - -/** - * Factory which allows a creation of producer. - */ -@Beta -public interface DataTreeProducerFactory { - - /** - * Create a producer, which is able to access to a set of trees. - * - * @param subtrees The collection of subtrees the resulting producer should have access to. - * @return A {@link DataTreeProducer} instance. - * @throws IllegalArgumentException if subtrees is empty. - */ - DataTreeProducer createProducer(Collection> subtrees); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeService.java deleted file mode 100644 index 11ae2550b7..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeService.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import javax.annotation.Nonnull; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * A {@link BindingService} providing access to the conceptual data tree. Interactions with the data - * tree are split into data producers and consumers (listeners). Each of them operate on a set of - * subtrees, which need to be declared at instantiation time. - * - *

- * Returned instances are not thread-safe and expected to be used by a single thread at a time. - * Furthermore, producers may not be accessed from consumer callbacks unless they were specified - * when the listener is registered. - * - *

- * The service maintains a loop-free topology of producers and consumers. What this means is that a - * consumer is not allowed to access a producer, which affects any of the subtrees it is subscribed - * to. This restriction is in place to ensure the system does not go into a feedback loop, where it - * is impossible to block either a producer or a consumer without accumulating excess work in the - * backlog stemming from its previous activity. - */ -@Beta -public interface DataTreeService extends DataTreeProducerFactory, BindingService { - - /** - * Register a {@link DataTreeListener} instance. Once registered, the listener will start - * receiving changes on the selected subtrees. If the listener cannot keep up with the rate of - * changes, and allowRxMerges is set to true, this service is free to merge the changes, so that - * a smaller number of them will be reported, possibly hiding some data transitions (like - * flaps). - * - *

- * If the listener wants to write into any producer, that producer has to be mentioned in the - * call to this method. Those producers will be bound exclusively to the registration, so that - * accessing them outside of this listener's callback will trigger an error. Any producers - * mentioned must be idle, e.g. they may not have an open transaction at the time this method is - * invoked. - * - *

- * Each listener instance can be registered at most once. Implementations of this interface have - * to guarantee that the listener's methods will not be invoked concurrently from multiple - * threads. - * - * @param listener {@link DataTreeListener} that is being registered - * @param subtrees Conceptual subtree identifier of subtrees which should be monitored for - * changes. May not be null or empty. - * @param allowRxMerges True if the backend may perform ingress state compression. - * @param producers {@link DataTreeProducer} instances to bind to the listener. - * @param listener type - * @return A listener registration. Once closed, the listener will no longer be invoked and the - * producers will be unbound. - * @throws IllegalArgumentException if subtrees is empty or the listener is already bound - * @throws DataTreeLoopException if the registration of the listener to the specified subtrees - * with specified producers would form a feedback loop - */ - @Nonnull - ListenerRegistration registerListener(@Nonnull T listener, - @Nonnull Collection> subtrees, boolean allowRxMerges, - @Nonnull Collection producers) throws DataTreeLoopException; -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeWriteCursor.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeWriteCursor.java deleted file mode 100644 index aad1da440f..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeWriteCursor.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.tree.BackendFailedException; - -/** - * {@inheritDoc} - * - *

- * In addition this cursor also provides write operations(delete, merge, write). - */ -@Beta -public interface DataTreeWriteCursor extends DataTreeCursor { - - /** - * Delete the specified child. - * - * @param child Child identifier - * @throws BackendFailedException when implementation-specific errors occurs while servicing the - * request. - */ - void delete(TreeArgument child); - - /** - * Merge the specified data with the currently-present data at specified path. - * - * @param child Child identifier - * @param data Data to be merged - * @param data type - * @throws BackendFailedException when implementation-specific errors occurs while servicing the - * request. - */ - void merge(TreeArgument child, T data); - - /** - * Replace the data at specified path with supplied data. - * - * @param child Child identifier - * @param data New node data - * @param data type - * @throws BackendFailedException when implementation-specific errors occurs while servicing the - * request. - */ - void write(TreeArgument child, T data); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPoint.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPoint.java deleted file mode 100644 index b79986b8c0..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPoint.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * A Node can be behind a mount point. In this case, the URI has to be in format - * identifier/yang-ext:mount/identifier. The first identifier is the path to - * a mount point and the second identifier is the path to a node behind the mount point. - * A URI can end in a mount point itself by using identifier/yang-ext:mount. - */ -@Beta -public interface MountPoint extends Identifiable> { - - /** - * Based on given service class, it returns binding service (from cache). - * @param service service class - * @param service type - * @return optional of binding service - */ - Optional getService(Class service); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointListener.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointListener.java deleted file mode 100644 index 5c694fa2dd..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.EventListener; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; - -/** - * Interface implemented by classes interested in receiving notifications about - * mount point changes. - */ -@Beta -public interface MountPointListener extends EventListener { - - /** - * Invoked whenever mount point is created at given path represented by instance identifier. - * @param path given path - */ - void onMountPointCreated(InstanceIdentifier path); - - /** - * Invoked whenever mount point is removed from given path represented by instance identifier. - * @param path given path - */ - void onMountPointRemoved(InstanceIdentifier path); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointService.java deleted file mode 100644 index 9056a51d2e..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/MountPointService.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * A {@link BindingService} providing access to mount point. - */ -@Beta -public interface MountPointService extends BindingService { - - /** - * Returns optional of mount point at given path represented by instance identifier. - * @param mountPoint mount point instance identifier - * @return optional of mount point - */ - Optional getMountPoint(InstanceIdentifier mountPoint); - - /** - * Register a {@link MountPointListener} instance. Once registered, the listener will start - * receiving changes on the selected path. - * - * @param path given path to listen to changes - * @param listener {@link MountPointListener} that is being registered - * @param listener type - * @return Listener registration object, which may be used to unregister - * your listener using {@link ListenerRegistration#close()} to stop - * delivery of mount point change events. - */ - ListenerRegistration registerListener(InstanceIdentifier path, T listener); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationPublishService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationPublishService.java deleted file mode 100644 index d6f7c0d808..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationPublishService.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.TimeUnit; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; - -/** - * A {@link NotificationService} which also allows its users to submit YANG-modeled notifications for delivery. - * - *

- * There are three methods of submission, following the patters from {@link java.util.concurrent.BlockingQueue}: - * - *

- * - {@link #putNotification(org.opendaylight.mdsal.binding.javav2.spec.base.Notification)}, which may block - * indefinitely if the implementation cannot allocate resources to accept the notification, - * - {@link #offerNotification(org.opendaylight.mdsal.binding.javav2.spec.base.Notification)}, which does not block if - * face of resource starvation, - * - {@link #offerNotification(org.opendaylight.mdsal.binding.javav2.spec.base.Notification, int, TimeUnit)}, which may - * block for specified time if resources are thin. - * - *

- * The actual delivery to listeners is asynchronous and implementation-specific. - * Users of this interface should not make any assumptions as to whether the - * notification has or has not been seen. - */ - -@Beta -public interface NotificationPublishService extends BindingService { - - ListenableFuture REJECTED = Futures.immediateFailedFuture( - new NotificationRejectedException("Rejected due to resource constraints.")); - - void putNotification(Notification notification) throws InterruptedException; - - ListenableFuture offerNotification(Notification notification); - - ListenableFuture offerNotification(Notification notification, int timeout, TimeUnit unit) - throws InterruptedException; - -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedException.java deleted file mode 100644 index 90bd6ff731..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; - -/** - * This exception indicates that given notification can not be processed by corresponding mechanism. - * More info can be provided in message. - * - *

- * Expected use: {@link NotificationPublishService} - */ -@Beta -public class NotificationRejectedException extends Exception { - - private static final long serialVersionUID = 1L; - - public NotificationRejectedException(final String message) { - super(message); - } - - public NotificationRejectedException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationService.java deleted file mode 100644 index 08768e308f..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/NotificationService.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * Notification broker which allows clients to subscribe for and publish YANG-modeled notifications. - * - *

- * Each YANG module which defines notifications results in a generated interface - * {ModuleName}Listener which handles all the notifications defined in the YANG model. - * Each notification type translates to a specific method of the form - * on{NotificationType} on the generated interface. The generated interface also - * extends the {@link org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener} interface and - * implementations are registered using - * {@link #registerNotificationListener(org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener)} - * method. - * - * Dispatch Listener Example - * - *

- * Lets assume we have following YANG model: - * - *

- * module example {
- *      ...
- *
- *      notification start {
- *          ...
- *      }
- *
- *      notification stop {
- *           ...
- *      }
- * }
- * 
- * - *

- * The generated interface will be: - * - *

- * public interface ExampleListener extends NotificationListener {
- *     void onStart(Start notification);
- *
- *     void onStop(Stop notification);
- * }
- * 
- * - *

- * The following defines an implementation of the generated interface: - * - *

- * public class MyExampleListener implements ExampleListener {
- *     public void onStart(Start notification) {
- *         // do something
- *     }
- *
- *     public void onStop(Stop notification) {
- *         // do something
- *     }
- * }
- * 
- * - *

- * The implementation is registered as follows: - * - *

- * MyExampleListener listener = new MyExampleListener();
- * ListenerRegistration<NotificationListener> reg = service.registerNotificationListener(listener);
- * 
- * - *

- * The onStart method will be invoked when someone publishes a Start - * notification and the onStop method will be invoked when someone publishes a - * Stop notification. - * - *

- * YANG 1.1: in case of notification tied to data note (container, list): - * - *

- * module example {
- *      ...
- *
- *      container cont {
- *          notification notify {
- *              ...
- *          }
- *      ...
- *      }
- * }
- * 
- * - *

- * The generated interface will be: - * - *

- * public interface ExampleListener extends NotificationListener {
- *     void onContNotify(Notify notification);
- *
- * }
- * 
- */ -@Beta -public interface NotificationService extends BindingService { - - /** - * Registers a listener which implements a YANG-generated notification interface derived from - * {@link NotificationListener}. The listener is registered for all notifications present in - * the implemented interface. - * - *

- * @param listener the listener implementation that will receive notifications. - * @param listener type - * @return a {@link ListenerRegistration} instance that should be used to unregister the listener - * by invoking the {@link ListenerRegistration#close()} method when no longer needed. - */ - ListenerRegistration registerNotificationListener(T listener); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/ReadTransaction.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/ReadTransaction.java deleted file mode 100644 index 21dc6850e9..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/ReadTransaction.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.function.BiConsumer; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.common.api.ReadFailedException; -import org.opendaylight.yangtools.concepts.Registration; - -/** - * A transaction that provides read access to a logical data store. - * - *

- * View of the data tree is a stable point-in-time snapshot of the current data tree state when the - * transaction was created. It's state and underlying data tree is not affected by other - * concurrently running transactions. - * - *

- * Implementation Note: This interface is not intended to be implemented by users of MD-SAL, - * but only to be consumed by them. - * - *

Transaction isolation example

- * Lets assume initial state of data tree for PATH is A. - * - * - * txRead = broker.newReadOnlyTransaction(); // read Transaction is snapshot of data - * txWrite = broker.newReadWriteTransactoin(); // concurrent write transaction - * txRead.read(OPERATIONAL, PATH).get(); // will return Optional containing A - * txWrite = broker.put(OPERATIONAL, PATH, B); // writes B to PATH - * txRead.read(OPERATIONAL, PATH).get(); // still returns Optional containing A - * txWrite.submit().get(); // data tree is updated, PATH contains B - * txRead.read(OPERATIONAL, PATH).get(); // still returns Optional containing A - * txAfterCommit = broker.newReadOnlyTransaction(); // read Transaction is snapshot of new state - * txAfterCommit.read(OPERATIONAL, PATH).get(); // returns Optional containing B; - * - * - *

- * Note: example contains blocking calls on future only to illustrate that action happened after other - * asynchronous action. Use of blocking call {@link com.google.common.util.concurrent.FluentFuture#get()} is - * discouraged for most uses and you should use - * {@link com.google.common.util.concurrent.FluentFuture#addCallback(com.google.common.util.concurrent.FutureCallback, - * java.util.concurrent.Executor)} or other functions from {@link com.google.common.util.concurrent.Futures} to register - * more specific listeners. - */ -@Beta -public interface ReadTransaction extends Transaction, Registration { - /** - * Reads data from the provided logical data store located at the provided path. - * - *

- * If the target is a subtree, then the whole subtree is read (and will be - * accessible from the returned data object). - * - * @param store - * Logical data store from which read should occur. - * @param path - * Path which uniquely identifies subtree which client want to - * read - * @param callback result callback - * @param result type - */ - void read(LogicalDatastoreType store, InstanceIdentifier path, - BiConsumer callback); - - /** - * Closes this transaction and releases all resources associated with it. - */ - @Override - void close(); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionConsumerRegistry.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionConsumerRegistry.java deleted file mode 100644 index ad95dc3ad4..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionConsumerRegistry.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.ListAction; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Provides access to registered Remote Procedure Call (RPC) and Action service implementations. - * RPCs and Actions are defined in YANG models. - * - *

- * RPC/Action implementations are registered using the {@link RpcActionProviderService}. - */ -@Beta -public interface RpcActionConsumerRegistry extends BindingService { - - /** - * Returns an implementation of a requested RPC service. - * - *

- * The returned instance is not an actual implementation of the RPC service interface, but a - * proxy implementation of the interface that forwards to an actual implementation, if any. - * - * @param serviceInterface given service interface - * @param interface type - * @return returns proxy for the requested RPC - */ - > T getRpcService(Class serviceInterface); - - /** - * Returns an implementation of a requested Action service. - * - *

- * The returned instance is not an actual implementation of the Action service interface, but a - * proxy implementation of the interface that forwards to an actual implementation, if any. - * - * @param serviceInterface given service interface - * @param interface type - * @return returns proxy for the requested Action - */ - > T getActionService(Class serviceInterface); - - /** - * Returns an implementation of a requested ListAction service. - * - *

- * The returned instance is not an actual implementation of the ListAction service interface, but a - * proxy implementation of the interface that forwards to an actual implementation, if any. - * - * @param serviceInterface given service interface - * @param interface type - * @return returns proxy for the requested ListAction - */ - > T getListActionService(Class serviceInterface); - -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionProviderService.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionProviderService.java deleted file mode 100644 index 577b21ce4a..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/RpcActionProviderService.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -/** - * Provides ability to register Remote Procedure Call (RPC) and Action service implementations. - * The RPCs and Actions are defined in YANG models. - */ -@Beta -public interface RpcActionProviderService { - - /** - * Returns class representing registration of global RPC. - * @param type RPC binding generated interface - * @param implementation RPC binding implementation - * @param service class type - * @param service implementation type - * @return returns class representing a RPC registration - */ - , T extends S> ObjectRegistration registerRpcImplementation(Class type, - T implementation); - - /** - * Returns class representing registration of global RPC for supported paths. - * @param type RPC binding generated interface - * @param implementation RPC binding implementation - * @param paths set of supported paths - * @param service class type - * @param service implementation type - * @return returns class representing a RPC registration - */ - , T extends S> ObjectRegistration registerRpcImplementation(Class type, - T implementation, Set> paths); - - /** - * Returns class representing registration of Action/ListAction. - * @param type Action/ListAction binding generated interface - * @param implementation Action/ListAction binding implementation - * @param datastore {@link LogicalDatastoreType} on which the implementation operates - * @param validNodes Set of nodes this implementation is constrained to, empty if this implementation can handle - * any target node. - * @param service class type - * @param

parent type - * @param service implementation type - * @return returns class representing a Action registration - */ - , T extends S, P extends TreeNode> ObjectRegistration - registerActionImplementation( - Class type, T implementation, LogicalDatastoreType datastore, Set> validNodes); - - default , T extends S> ObjectRegistration - registerActionImplementation(Class type, T implementation, LogicalDatastoreType datastore) { - return registerActionImplementation(type, implementation, datastore, ImmutableSet.of()); - } - - default , T extends S> ObjectRegistration - registerActionImplementation(Class type, T implementation) { - return registerActionImplementation(type, implementation, LogicalDatastoreType.OPERATIONAL, ImmutableSet.of()); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/Transaction.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/Transaction.java deleted file mode 100644 index 0cbd97581a..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/Transaction.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * A common parent for all transactions which operate on a conceptual data tree. - * See derived transaction types for more concrete behavior: - *

    - *
  • {@link ReadTransaction} - Read capabilities, user is able to read data from data tree
  • - *
  • {@link WriteTransaction} - Write capabilities, user is able to propose changes to data tree
  • - *
- * - * Implementation Note: This interface is not intended to be implemented by users of MD-SAL. - */ -public interface Transaction extends Identifiable { - -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChain.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChain.java deleted file mode 100644 index 7c94a9a79a..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChain.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.concepts.Registration; - -/** - * A chain of transactions. Transactions in a chain need to be committed in sequence and each transaction should see - * the effects of previous committed transactions as they occurred. A chain makes no guarantees of atomicity across - * the chained transactions - the transactions are committed as soon as possible in the order that they were committed. - * This behaviour is different from the default AsyncDataBroker, where a transaction is always created from the current - * global state, not taking into account any transactions previously committed by the calling thread. Due to - * the asynchronous nature of transaction submission this can lead to surprising results. If a thread executes - * the following sequence sufficiently quickly: - * - * - * AsyncWriteTransaction t1 = broker.newWriteOnlyTransaction(); - * t1.put(id, data); - * t1.commit(); - * - * AsyncReadTransaction t2 = broker.newReadOnlyTransaction(); - * Optional<?> maybeData = t2.read(id).get(); - * - * it may happen, that it sees maybeData.isPresent() == false, simply because t1 has not completed the processes - * of being applied and t2 is actually allocated from the previous state. This is obviously bad for users who create - * incremental state in the datastore and actually read what they write in subsequent transactions. Using - * a TransactionChain instead of a broker solves this particular problem, and leads to expected behavior: t2 will always - * see the data written in t1 present. - */ -@Beta -public interface TransactionChain extends Registration, TransactionFactory { - /** - * Create a new read only transaction which will continue the chain. - * - *

- * The previous write transaction has to be either SUBMITTED ({@link WriteTransaction#commit commit} was invoked) - * or CANCELLED ({@link #close close} was invoked). - * - *

- * The returned read-only transaction presents an isolated view of the data if the previous write transaction was - * successful - in other words, this read-only transaction will see the state changes made by the previous write - * transaction in the chain. However, state which was introduced by other transactions outside this transaction - * chain after creation of the previous transaction is not visible. - * - * @return New transaction in the chain. - * @throws IllegalStateException if the previous transaction was not SUBMITTED or CANCELLED. - * @throws TransactionChainClosedException if the chain has been closed. - */ - @Override - ReadTransaction newReadOnlyTransaction(); - - /** - * Create a new write-only transaction which will continue the chain. - * - *

- * The previous write transaction has to be either SUBMITTED ({@link WriteTransaction#commit commit} was invoked) - * or CANCELLED ({@link #close close} was invoked) - * - *

- * The returned write-only transaction presents an isolated view of the data if the previous write transaction was - * successful - in other words, this write-only transaction will see the state changes made by the previous write - * transaction in the chain. However, state which was introduced by other transactions outside this transaction - * chain after creation of the previous transaction is not visible - * - *

- * Committing this write-only transaction using {@link WriteTransaction#commit commit} will commit the state - * changes in this transaction to be visible to any subsequent transaction in this chain and also to any transaction - * outside this chain. - * - * @return New transaction in the chain. - * @throws IllegalStateException if the previous transaction was not SUBMITTED or CANCELLED. - * @throws TransactionChainClosedException if the chain has been closed. - */ - @Override - WriteTransaction newWriteOnlyTransaction(); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainClosedException.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainClosedException.java deleted file mode 100644 index eeffac59f4..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainClosedException.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -/** - * Exception thrown when an attempt is made to open a new transaction in a closed chain. - */ -public final class TransactionChainClosedException extends IllegalStateException { - private static final long serialVersionUID = 1L; - - public TransactionChainClosedException(final String message) { - super(message); - } - - public TransactionChainClosedException(final String message, final Throwable cause) { - super(message, cause); - } -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainListener.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainListener.java deleted file mode 100644 index e516213347..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionChainListener.java +++ /dev/null @@ -1,37 +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.mdsal.binding.javav2.api; - -import java.util.EventListener; - -/** - * Listener for transaction chain events. - */ -// FIXME: 4.0.0: remove this in favor of a TransactionChain destiny, available as a FluentFuture from TransactionChain -public interface TransactionChainListener extends EventListener { - /** - * Invoked if when a transaction in the chain fails. All transactions submitted after the failed transaction, in the - * chain, are automatically cancelled by the time this notification is invoked. Open transactions need to be closed - * or cancelled. - * Implementations should invoke chain.close() to close the chain. - * - * @param chain Transaction chain which failed - * @param transaction Transaction which caused the chain to fail - * @param cause The cause of transaction failure - */ - void onTransactionChainFailed(TransactionChain chain, Transaction transaction, Throwable cause); - - /** - * Invoked when a transaction chain is completed. A transaction chain is considered completed when it has been - * closed and all its instructions have completed successfully. - * - * @param chain Transaction chain which completed - */ - void onTransactionChainSuccessful(TransactionChain chain); -} - diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionFactory.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionFactory.java deleted file mode 100644 index 32eaa393d4..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TransactionFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; - -/** - * A factory which allocates new transactions to operate on the data tree. - * - *

- * Note: This interface is not intended to be used directly, but rather via subinterfaces - * which introduces additional semantics to allocated transactions. - *

    - *
  • {@link DataBroker} - *
  • {@link TransactionChain} - *
- * - *

- * All operations on the data tree are performed via one of the transactions: - *

    - *
  • Read-Only - allocated using {@link #newReadOnlyTransaction()} - *
  • Write-Only - allocated using {@link #newWriteOnlyTransaction()} - *
- * - *

- * These transactions provides a stable isolated view of the data tree, which is guaranteed to be - * not affected by other concurrent transactions, until transaction is committed. - * - *

- * For a detailed explanation of how transaction are isolated and how transaction-local changes are - * committed to global data tree, see {@link ReadTransaction}, {@link WriteTransaction} - * and {@link WriteTransaction#commit()}. - * - *

- * It is strongly recommended to use the type of transaction, which provides only the minimal - * capabilities you need. This allows for optimizations at the data broker / data store level. For - * example, implementations may optimize the transaction for reading if they know ahead of time that - * you only need to read data - such as not keeping additional meta-data, which may be required for - * write transactions. - * - *

- * Implementation Note: This interface is not intended to be implemented by users of MD-SAL, - * but only to be consumed by them. - * - * @see DataBroker -*/ -@Beta -public interface TransactionFactory { - /** - * Allocates a new read-only transaction which provides an immutable snapshot of the data tree. The view of data - * tree is an immutable snapshot of current data tree state when transaction was allocated. - * - * @return A new read-only transaction - */ - ReadTransaction newReadOnlyTransaction(); - - /** - * Allocates new write-only transaction based on latest state of data tree. - * - *

- * Preconditions for mutation of data tree are captured from the snapshot of data tree state, when the transaction - * is allocated. If data was changed during transaction in an incompatible way then the commit of this transaction - * will fail. See {@link WriteTransaction#commit()} for more details about conflicting and not-conflicting changes - * and failure scenarios. - * - *

- * Since this transaction does not provide a view of the data it SHOULD BE used only by callers who are exclusive - * writers (exporters of data) to the subtree they modify. This prevents optimistic lock failures as described in - * {@link WriteTransaction#commit()}. - * - *

- * Exclusivity of writers to particular subtree SHOULD BE enforced by external locking mechanism. - * - * @return new write-only transaction - */ - WriteTransaction newWriteOnlyTransaction(); -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModification.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModification.java deleted file mode 100644 index fd531c94f6..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModification.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate; - -/** - * Modified Tree Node. - * - *

- * Represents modification of tree node {@link TreeNode} - * - *

- * @param Type of modified object - * - */ -@Beta -public interface TreeNodeModification extends Identifiable { - - /** - * Represents type of modification which has occured. - * - */ - enum ModificationType { - /** - * Child node (direct or indirect) was modified. - * - */ - SUBTREE_MODIFIED, - /** - * Node was explicitly created / overwritten. - * - */ - WRITE, - /** - * Node was deleted. - * - */ - DELETE, - /** - * This node has appeared because it is implied by one of its children. This type is usually produced when a - * structural container is created to host some leaf entries. It does not have an associated before-image. - * Its semantics is a combination of SUBTREE_MODIFIED and WRITE, depending on which context it is being - * interpreted. - * Users who track the value of the node can treat it as a WRITE. Users transforming a {@link DataTreeCandidate} - * to operations on a {@link org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification} - * should interpret it as a SUBTREE_MODIFIED and examine its children. - * This is needed to correctly deal with concurrent operations on the nodes children, as issuing a write on the - * DataTreeModification could end up removing any leaves which have not been present at the DataTree which - * emitted this event. - */ - APPEARED, - /** - * This node has disappeared because it is no longer implied by any children. This type is usually produced when - * a structural container is removed because it has become empty. It does not have an associated after-image. - * Its semantics is a combination of SUBTREE_MODIFIED and DELETE, depending on which context it is being - * interpreted. - * Users who track the value of the node can treat it as a DELETE, as the container has disappeared. - * Users transforming a {@link DataTreeCandidate} to operations on a - * {@link org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification} should interpret - * it as a SUBTREE_MODIFIED and examine its children. - * This is needed to correctly deal with concurrent operations on the nodes children, as issuing a delete on the - * DataTreeModification would end up removing any leaves which have not been present at the DataTree which - * emitted this event. - */ - DISAPPEARED - } - - @Nonnull - @Override - TreeArgument getIdentifier(); - - /** - * Returns type of modified object. - * - * @return type of modified object. - */ - @Nonnull Class getDataType(); - - /** - * Returns type of modification. - * - * @return type Type of performed modification. - */ - @Nonnull ModificationType getModificationType(); - - /** - * Returns before-state of top level container. Implementations are encouraged, but not required - * to provide this state. - * - * @return State of object before modification. Null if subtree was not present, or the - * implementation cannot provide the state. - */ - @Nullable - T getDataBefore(); - - /** - * Returns after-state of top level container. - * - * @return State of object after modification. Null if subtree is not present. - */ - @Nullable T getDataAfter(); - - /** - * Returns unmodifiable collection of modified direct children. - * - * @return unmodifiable collection of modified direct children. - */ - @Nonnull - Collection> getModifiedChildren(); - - /** - * Returns child list item modification if {@code child} was modified by this modification. - * - * @param childType Type of list item - must be list item with key - * @param type of child class - * @return Modification of {@code child} if {@code child} was modified, null otherwise. - * @throws IllegalArgumentException If supplied {@code childType} class is not valid child according - * to generated model. - */ - > Collection> getModifiedChildren( - @Nonnull Class childType); - - /** - * Returns container child modification if {@code child} was modified by this - * modification. - * - *

- * For accessing all modified list items consider iterating over {@link #getModifiedChildren()}. - * - * @param child Type of child - must be only container - * @param type of child class - * @return Modification of {@code child} if {@code child} was modified, null otherwise. - * @throws IllegalArgumentException If supplied {@code child} class is not valid child according - * to generated model. - */ - @Nullable > TreeNodeModification getModifiedChildContainer( - @Nonnull Class child); - - /** - * Returns augmentation child modification if {@code augmentation} was modified by this - * modification. - * - *

- * For accessing all modified list items consider iterating over {@link #getModifiedChildren()}. - * - * @param augmentation Type of augmentation - must be only container - * @param type of augmentation class - * @return Modification of {@code augmentation} if {@code augmentation} was modified, null otherwise. - * @throws IllegalArgumentException If supplied {@code augmentation} class is not valid augmentation - * according to generated model. - */ - @Nullable & TreeNode> TreeNodeModification getModifiedAugmentation( - @Nonnull Class augmentation); - - - /** - * Returns child list item modification if {@code child} was modified by this modification. - * - * @param listItem Type of list item - must be list item with key - * @param listKey List item key - * @param type of list item class - * @param type of list key - * @return Modification of {@code child} if {@code child} was modified, null otherwise. - * @throws IllegalArgumentException If supplied {@code listItem} class is not valid child according - * to generated model. - */ - & TreeChildNode, K extends IdentifiableItem> - TreeNodeModification getModifiedChildListItem(@Nonnull Class listItem, @Nonnull K listKey); - - /** - * Returns a child modification if a node identified by {@code childArgument} was modified by - * this modification. - * - * @param childArgument Path Argument of child node - * @return Modification of child identified by {@code childArgument} if {@code childArgument} - * was modified, null otherwise. - * @throws IllegalArgumentException If supplied path argument is not valid child according to - * generated model. - * - */ - @Nullable - TreeNodeModification getModifiedChild(TreeArgument childArgument); - -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/WriteTransaction.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/WriteTransaction.java deleted file mode 100644 index cad3ab22c1..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/WriteTransaction.java +++ /dev/null @@ -1,562 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import javax.annotation.CheckReturnValue; -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.CommitInfo; -import org.opendaylight.mdsal.common.api.DataValidationFailedException; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.common.api.OptimisticLockFailedException; -import org.opendaylight.mdsal.common.api.TransactionCommitFailedException; - -/** - * A transaction that provides mutation capabilities on a data tree. - * - *

- * Initial state of write transaction is a stable snapshot of the current data tree. The state is captured when - * the transaction is created and its state and underlying data tree are not affected by other concurrently running - * transactions. - * - *

- * Write transactions are isolated from other concurrent write transactions. All writes are local to the transaction - * and represent only a proposal of state change for the data tree and it is not visible to any other concurrently - * running transaction. - * - *

- * Applications make changes to the local data tree in the transaction by via the put, merge, - * and delete operations. - * - *

Put operation

- * Stores a piece of data at a specified path. This acts as an add / replace operation, which is to say that whole - * subtree will be replaced by the specified data. - * - *

- * Performing the following put operations: - * - *

- * 1) container { list [ a ] }
- * 2) container { list [ b ] }
- * 
- * will result in the following data being present: - * - *
- * container { list [ b ] }
- * 
- *

Merge operation

- * Merges a piece of data with the existing data at a specified path. Any pre-existing data which is not explicitly - * overwritten will be preserved. This means that if you store a container, its child lists will be merged. - * - *

- * Performing the following merge operations: - * - *

- * 1) container { list [ a ] }
- * 2) container { list [ b ] }
- * 
- * will result in the following data being present: - * - *
- * container { list [ a, b ] }
- * 
- * This also means that storing the container will preserve any augmentations which have been attached to it. - * - *

Delete operation

- * Removes a piece of data from a specified path. - * - *

- * After applying changes to the local data tree, applications publish the changes proposed in the transaction - * by calling {@link #commit} on the transaction. This seals the transaction (preventing any further writes using this - * transaction) and commits it to be processed and applied to global conceptual data tree. - * - *

- * The transaction commit may fail due to a concurrent transaction modifying and committing data in an incompatible way. - * See {@link #commit} for more concrete commit failure examples. - * - *

- * Implementation Note: This interface is not intended to be implemented by users of MD-SAL, but only to be - * consumed by them. - */ -@Beta -public interface WriteTransaction extends Transaction { - /** - * Cancels the transaction. Transactions can only be cancelled if it was not yet committed. - * Invoking cancel() on failed or already canceled will have no effect, and transaction is considered cancelled. - * Invoking cancel() on finished transaction (future returned by {@link #commit()} already successfully completed) - * will always fail (return false). - * - * @return false if the task could not be cancelled, typically because it has already completed normally; - * true otherwise - */ - boolean cancel(); - - /** - * Commits this transaction to be asynchronously applied to update the logical data tree. The returned - * {@link FluentFuture} conveys the result of applying the data changes. - * - *

- * This call logically seals the transaction, which prevents the client from further changing the data tree using - * this transaction. Any subsequent calls to put(LogicalDatastoreType, Path, Object), - * merge(LogicalDatastoreType, Path, Object), delete(LogicalDatastoreType, Path) will fail - * with {@link IllegalStateException}. The transaction is marked as committed and enqueued into the data store - * back-end for processing. - * - *

- * Whether or not the commit is successful is determined by versioning of the data tree and validation of registered - * commit participants if the transaction changes the data tree. - * - *

- * The effects of a successful commit of data depends on listeners and commit participants that are registered with - * the data broker. - * - *

Example usage:

- *
-     *  private void doWrite(final int tries) {
-     *      WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
-     *      MyDataObject data = ...;
-     *      InstanceIdentifier<MyDataObject> path = ...;
-     *      writeTx.put(LogicalDatastoreType.OPERATIONAL, path, data);
-     *      Futures.addCallback(writeTx.commit(), new FutureCallback<CommitInfo>() {
-     *          public void onSuccess(CommitInfo result) {
-     *              // succeeded
-     *          }
-     *          public void onFailure(Throwable t) {
-     *              if (t instanceof OptimisticLockFailedException) {
-     *                  if(( tries - 1) > 0 ) {
-     *                      // do retry
-     *                      doWrite(tries - 1);
-     *                  } else {
-     *                      // out of retries
-     *                  }
-     *              } else {
-     *                  // failed due to another type of TransactionCommitFailedException.
-     *              }
-     *          });
-     * }
-     * ...
-     * doWrite(2);
-     * 
- * - *

Failure scenarios

- * - *

- * Transaction may fail because of multiple reasons, such as - *

    - *
  • - * Another transaction finished earlier and modified the same node in a non-compatible way (see below). In this - * case the returned future will fail with an {@link OptimisticLockFailedException}. It is the responsibility - * of the caller to create a new transaction and commit the same modification again in order to update data - * tree. - * - * Warning: In most cases, retrying after an OptimisticLockFailedException will result in a high - * probability of success. However, there are scenarios, albeit unusual, where any number of retries will - * not succeed. Therefore it is strongly recommended to limit the number of retries (2 or 3) to avoid - * an endless loop. - * - *
  • - *
  • Data change introduced by this transaction did not pass validation by commit handlers or data was - * incorrectly structured. Returned future will fail with a {@link DataValidationFailedException}. User - * should not retry to create new transaction with same data, since it probably will fail again. - *
  • - *
- * - *

Change compatibility

- * There are several sets of changes which could be considered incompatible between two transactions which are - * derived from same initial state. Rules for conflict detection applies recursively for each subtree level. - * - *

Change compatibility of leafs, leaf-list items

- * Following table shows state changes and failures between two concurrent transactions, which are based on same - * initial state, Tx 1 completes successfully before Tx 2 is committed. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Initial stateTx 1Tx 2Result
Emptyput(A,1)put(A,2)Tx 2 will fail, state is A=1
Emptyput(A,1)merge(A,2)A=2
Emptymerge(A,1)put(A,2)Tx 2 will fail, state is A=1
Emptymerge(A,1)merge(A,2)A=2
A=0put(A,1)put(A,2)Tx 2 will fail, A=1
A=0put(A,1)merge(A,2)A=2
A=0merge(A,1)put(A,2)Tx 2 will fail, A=1
A=0merge(A,1)merge(A,2)A=2
A=0delete(A)put(A,2)Tx 2 will fail, A does not exists
A=0delete(A)merge(A,2)A=2
- * - *

Change compatibility of subtrees

- * Following table shows state changes and failures between two concurrent transactions, which are based on same - * initial state, Tx 1 completes successfully before Tx 2 is committed. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Initial stateTx 1Tx 2Result
Emptyput(TOP,[])put(TOP,[])Tx 2 will fail, state is TOP=[]
Emptyput(TOP,[])merge(TOP,[])TOP=[]
Emptyput(TOP,[FOO=1])put(TOP,[BAR=1])Tx 2 will fail, state is TOP=[FOO=1]
Emptyput(TOP,[FOO=1])merge(TOP,[BAR=1])TOP=[FOO=1,BAR=1]
Emptymerge(TOP,[FOO=1])put(TOP,[BAR=1])Tx 2 will fail, state is TOP=[FOO=1]
Emptymerge(TOP,[FOO=1])merge(TOP,[BAR=1])TOP=[FOO=1,BAR=1]
TOP=[]put(TOP,[FOO=1])put(TOP,[BAR=1])Tx 2 will fail, state is TOP=[FOO=1]
TOP=[]put(TOP,[FOO=1])merge(TOP,[BAR=1])state is TOP=[FOO=1,BAR=1]
TOP=[]merge(TOP,[FOO=1])put(TOP,[BAR=1])Tx 2 will fail, state is TOP=[FOO=1]
TOP=[]merge(TOP,[FOO=1])merge(TOP,[BAR=1])state is TOP=[FOO=1,BAR=1]
TOP=[]delete(TOP)put(TOP,[BAR=1])Tx 2 will fail, state is empty store
TOP=[]delete(TOP)merge(TOP,[BAR=1])state is TOP=[BAR=1]
TOP=[]put(TOP/FOO,1)put(TOP/BAR,1])state is TOP=[FOO=1,BAR=1]
TOP=[]put(TOP/FOO,1)merge(TOP/BAR,1)state is TOP=[FOO=1,BAR=1]
TOP=[]merge(TOP/FOO,1)put(TOP/BAR,1)state is TOP=[FOO=1,BAR=1]
TOP=[]merge(TOP/FOO,1)merge(TOP/BAR,1)state is TOP=[FOO=1,BAR=1]
TOP=[]delete(TOP)put(TOP/BAR,1)Tx 2 will fail, state is empty store
TOP=[]delete(TOP)merge(TOP/BAR,1]Tx 2 will fail, state is empty store
TOP=[FOO=1]put(TOP/FOO,2)put(TOP/BAR,1)state is TOP=[FOO=2,BAR=1]
TOP=[FOO=1]put(TOP/FOO,2)merge(TOP/BAR,1)state is TOP=[FOO=2,BAR=1]
TOP=[FOO=1]merge(TOP/FOO,2)put(TOP/BAR,1)state is TOP=[FOO=2,BAR=1]
TOP=[FOO=1]merge(TOP/FOO,2)merge(TOP/BAR,1)state is TOP=[FOO=2,BAR=1]
TOP=[FOO=1]delete(TOP/FOO)put(TOP/BAR,1)state is TOP=[BAR=1]
TOP=[FOO=1]delete(TOP/FOO)merge(TOP/BAR,1]state is TOP=[BAR=1]
- * - * - *

Examples of failure scenarios

- * - *

Conflict of two transactions

- * This example illustrates two concurrent transactions, which derived from same initial state - * of data tree and proposes conflicting modifications. - * - *
-     * txA = broker.newWriteTransaction(); // allocates new transaction, data tree is empty
-     * txB = broker.newWriteTransaction(); // allocates new transaction, data tree is empty
-     * txA.put(CONFIGURATION, PATH, A);    // writes to PATH value A
-     * txB.put(CONFIGURATION, PATH, B)     // writes to PATH value B
-     * ListenableFuture futureA = txA.commit(); // transaction A is sealed and committed
-     * ListenebleFuture futureB = txB.commit(); // transaction B is sealed and committed
-     * 
- * Commit of transaction A will be processed asynchronously and data tree will be updated to - * contain value A for PATH. Returned {@link FluentFuture} will - * successfully complete once state is applied to data tree. - * Commit of Transaction B will fail, because previous transaction also modified path in a - * concurrent way. The state introduced by transaction B will not be applied. Returned - * {@link FluentFuture} object will fail with {@link OptimisticLockFailedException} - * exception, which indicates to client that concurrent transaction prevented the committed - * transaction from being applied.
- * - *

- * A successful commit produces implementation-specific {@link CommitInfo} structure, which is used to communicate - * post-condition information to the caller. Such information can contain commit-id, timing information or any - * other information the implementation wishes to share. - * - * @return a FluentFuture containing the result of the commit information. The Future blocks until the commit - * operation is complete. A successful commit returns nothing. On failure, the Future will fail with a - * {@link TransactionCommitFailedException} or an exception derived from TransactionCommitFailedException. - * @throws IllegalStateException if the transaction is already committed or was canceled. - */ - @CheckReturnValue - @NonNull FluentFuture commit(); - - /** - * Stores a piece of data at the specified path. This acts as an add / replace - * operation, which is to say that whole subtree will be replaced by the specified data. - * - *

- * This method does not automatically create missing parent nodes. It is equivalent to invoking - * {@link #put(LogicalDatastoreType, InstanceIdentifier, TreeNode, boolean)} - * with createMissingParents set to false. - * - *

- * If you need to make sure that a parent object exists but you do not want modify - * its pre-existing state by using put, consider using {@link #merge} instead. - * - * @param store - * the logical data store which should be modified - * @param path - * the data object path - * @param data - * the data object to be written to the specified path - * @param data tree type - * @throws IllegalStateException - * if the transaction has already been submitted - */ - void put(LogicalDatastoreType store, InstanceIdentifier path, T data); - - /** - * Stores a piece of data at the specified path. This acts as an add / replace operation, which is to say that whole - * subtree will be replaced by the specified data. - * - *

- * If you need to make sure that a parent object exists but you do not want modify its pre-existing state by using - * put, consider using {@link #merge} instead. - * - *

- * Note: Using createMissingParents with value true, may - * introduce garbage in data store, or recreate nodes, which were deleted by - * previous transaction. - * - * @param store - * the logical data store which should be modified - * @param path - * the data object path - * @param data - * the data object to be written to the specified path - * @param createMissingParents - * if {@link #CREATE_MISSING_PARENTS}, any missing parent nodes will be automatically - * created using a merge operation. - * @param data tree type - * @throws IllegalStateException - * if the transaction has already been submitted - */ - void put(LogicalDatastoreType store, InstanceIdentifier path, T data, - boolean createMissingParents); - - /** - * Merges a piece of data with the existing data at a specified path. Any pre-existing data which is not explicitly - * overwritten will be preserved. This means that if you store a container, its child lists will be merged. - * - *

- * This method does not automatically create missing parent nodes. It is equivalent to invoking - * {@link #merge(LogicalDatastoreType, InstanceIdentifier, TreeNode, boolean)} - * with createMissingParents set to false. - * - *

- * If you require an explicit replace operation, use {@link #put} instead. - * @param store the logical data store which should be modified - * @param path the data object path - * @param data the data object to be merged to the specified path - * @param data tree type - * @throws IllegalStateException if the transaction has already been submitted - */ - void merge(LogicalDatastoreType store, InstanceIdentifier path, T data); - - /** - * Merges a piece of data with the existing data at a specified path. Any pre-existing data which is not explicitly - * overwritten will be preserved. This means that if you store a container, its child lists will be merged. - * - *

- * If you require an explicit replace operation, use {@link #put} instead. - * - * @param store the logical data store which should be modified - * @param path the data object path - * @param data the data object to be merged to the specified path - * @param createMissingParents if {@link #CREATE_MISSING_PARENTS}, any missing parent nodes will be automatically - * created using a merge operation. - * @param data tree type - * @throws IllegalStateException if the transaction has already been submitted - */ - void merge(LogicalDatastoreType store, InstanceIdentifier path, T data, - boolean createMissingParents); - - /** - * Removes a piece of data from specified path. This operation does not fail if the specified path does not exist. - * - * @param store Logical data store which should be modified - * @param path Data object path - * @throws IllegalStateException if the transaction was committed or canceled. - */ - void delete(LogicalDatastoreType store, InstanceIdentifier path); - - /** - * Flag value indicating that missing parents should be created. - */ - boolean CREATE_MISSING_PARENTS = true; - - /** - * Flag value indicating that missing parents should cause an error. - */ - boolean FAIL_ON_MISSING_PARENTS = false; -} diff --git a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/annotation/RoutingContext.java b/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/annotation/RoutingContext.java deleted file mode 100644 index a6f9a51163..0000000000 --- a/binding2/mdsal-binding2-api/src/main/java/org/opendaylight/mdsal/binding/javav2/api/annotation/RoutingContext.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.api.annotation; - -import com.google.common.annotations.Beta; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity; - -@Beta -@Inherited -@Documented -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface RoutingContext { - - Class value(); -} diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifierTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifierTest.java deleted file mode 100644 index 67ad77649d..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeIdentifierTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; - -public class DataTreeIdentifierTest { - - private static final DataTreeIdentifier TEST_IDENTIFIER1 = DataTreeIdentifier.create( - LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(TestTreeNode1.class)); - private static final DataTreeIdentifier TEST_IDENTIFIER2 = DataTreeIdentifier.create( - LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(TestTreeNode2.class)); - - @Test - public void basicTest() throws Exception { - assertEquals(LogicalDatastoreType.OPERATIONAL, TEST_IDENTIFIER1.getDatastoreType()); - assertEquals(InstanceIdentifier.create(TestTreeNode1.class), TEST_IDENTIFIER1.getRootIdentifier()); - } - - @Test - public void containsTest() { - assertTrue("Contains", TEST_IDENTIFIER1.contains(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, - InstanceIdentifier.create(TestTreeNode1.class)))); - assertFalse("Not Contains", TEST_IDENTIFIER1.contains(TEST_IDENTIFIER2)); - } - - @Test - public void hashCodeTest() { - assertEquals("hashCode", TEST_IDENTIFIER1.hashCode(), DataTreeIdentifier.create( - LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(TestTreeNode1.class)).hashCode()); - assertNotEquals("hashCode", TEST_IDENTIFIER1.hashCode(), TEST_IDENTIFIER2.hashCode()); - } - - @Test - public void equalsTest() { - assertTrue("Equals", TEST_IDENTIFIER1.equals(TEST_IDENTIFIER1)); - assertTrue("Equals", TEST_IDENTIFIER1.equals(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, - InstanceIdentifier.create(TestTreeNode1.class)))); - assertFalse("Different", TEST_IDENTIFIER1.equals(DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, - InstanceIdentifier.create(TestTreeNode1.class)))); - assertFalse("Different", TEST_IDENTIFIER1.equals(TEST_IDENTIFIER2)); - assertFalse("Equals null", TEST_IDENTIFIER1.equals(null)); - assertFalse("Different object", TEST_IDENTIFIER1.equals(new Object())); - } - - private static class TestTreeNode1 implements TreeNode { - } - - private static class TestTreeNode2 implements TreeNode { - } -} diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningExceptionTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningExceptionTest.java deleted file mode 100644 index d8a8c9e1cb..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeListeningExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import org.junit.Test; - -public class DataTreeListeningExceptionTest { - - @Test(expected = DataTreeListeningException.class) - public void constructWithCauseTest() throws Exception { - throw new DataTreeListeningException("test", new Throwable()); - } - - @Test(expected = DataTreeListeningException.class) - public void constructTest() throws Exception { - throw new DataTreeListeningException("test"); - } -} diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopExceptionTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopExceptionTest.java deleted file mode 100644 index 179971463e..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeLoopExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import org.junit.Test; - -public class DataTreeLoopExceptionTest { - - @Test(expected = DataTreeLoopException.class) - public void constructWithCauseTest() throws Exception { - throw new DataTreeLoopException("test", new Throwable()); - } - - @Test(expected = DataTreeLoopException.class) - public void constructTest() throws Exception { - throw new DataTreeLoopException("test"); - } -} diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyExceptionTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyExceptionTest.java deleted file mode 100644 index cbe4a14daa..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerBusyExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import org.junit.Test; - -public class DataTreeProducerBusyExceptionTest { - - @Test(expected = DataTreeProducerBusyException.class) - public void constructWithCauseTest() throws Exception { - throw new DataTreeProducerBusyException("test", new Throwable()); - } - - @Test(expected = DataTreeProducerBusyException.class) - public void constructTest() throws Exception { - throw new DataTreeProducerBusyException("test"); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerExceptionTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerExceptionTest.java deleted file mode 100644 index 1c6ef6617d..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/DataTreeProducerExceptionTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import org.junit.Test; - -public class DataTreeProducerExceptionTest { - - @Test(expected = DataTreeProducerException.class) - public void constructWithCauseTest() throws Exception { - throw new DataTreeProducerException("test", new Throwable()); - } - - @Test(expected = DataTreeProducerException.class) - public void constructTest() throws Exception { - throw new DataTreeProducerException("test"); - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedExceptionTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedExceptionTest.java deleted file mode 100644 index 58d971a079..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/NotificationRejectedExceptionTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import org.junit.Test; - -public class NotificationRejectedExceptionTest { - - @Test(expected = NotificationRejectedException.class) - public void constructWithCauseTest() throws Exception { - throw new NotificationRejectedException("test", new Throwable()); - } - - @Test(expected = NotificationRejectedException.class) - public void constructTest() throws Exception { - throw new NotificationRejectedException("test"); - } -} diff --git a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModificationTest.java b/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModificationTest.java deleted file mode 100644 index 0e6c0675df..0000000000 --- a/binding2/mdsal-binding2-api/src/test/java/org/opendaylight/mdsal/binding/javav2/api/TreeNodeModificationTest.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.api; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class TreeNodeModificationTest { - - @Test - public void notificationMethodEnumTest() throws Exception { - assertNotNull(TreeNodeModification.ModificationType.values()); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/pom.xml b/binding2/mdsal-binding2-dom-adapter/pom.xml deleted file mode 100644 index 7f4a16b4cc..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-dom-adapter - 0.16.0-SNAPSHOT - bundle - - - - com.google.guava - guava - - - org.javassist - javassist - - - org.opendaylight.mdsal - mdsal-binding2-api - - - org.opendaylight.mdsal - mdsal-binding2-util - - - org.opendaylight.mdsal - mdsal-dom-broker - test - - - org.opendaylight.mdsal - mdsal-dom-api - - - org.opendaylight.mdsal - mdsal-dom-spi - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - - - org.opendaylight.mdsal - mdsal-binding2-dom-codec - - - org.opendaylight.yangtools - yang-data-impl - - - org.opendaylight.yangtools - yang-model-util - - - org.opendaylight.yangtools - yang-test-util - - - org.osgi - org.osgi.core - - - org.opendaylight.yangtools - yang-parser-impl - test - - - org.opendaylight.mdsal - mdsal-binding2-test-model - - - org.opendaylight.mdsal - mdsal-dom-inmemory-datastore - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - - scm:git:http://git.opendaylight.org/gerrit/mdsal.git - scm:git:ssh://git.opendaylight.org:29418/mdsal.git - HEAD - https://wiki.opendaylight.org/view/MD-SAL:Main - - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/ContextReferenceExtractor.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/ContextReferenceExtractor.java deleted file mode 100644 index a9bc0d65d0..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/ContextReferenceExtractor.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import java.lang.reflect.Method; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.annotation.RoutingContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Tree node reference extractor. - */ -@Beta -public abstract class ContextReferenceExtractor { - - private static final Logger LOG = LoggerFactory.getLogger(ContextReferenceExtractor.class); - private static final String GET_VALUE_NAME = "getValue"; - - private static final ContextReferenceExtractor NULL_EXTRACTOR = new ContextReferenceExtractor() { - - @Nullable - @Override - public InstanceIdentifier extract(final TreeNode obj) { - return null; - } - }; - - private static final LoadingCache, ContextReferenceExtractor> EXTRACTORS = - CacheBuilder.newBuilder().weakKeys().build(new CacheLoader, ContextReferenceExtractor>() { - - @Nonnull - @Override - public ContextReferenceExtractor load(@Nonnull final Class key) throws Exception { - return create(key); - } - - private ContextReferenceExtractor create(final Class key) { - final Method contextGetter = getContextGetter(key); - if (contextGetter == null) { - return NULL_EXTRACTOR; - } - final Class returnType = contextGetter.getReturnType(); - try { - if (InstanceIdentifier.class.isAssignableFrom(returnType)) { - return DirectGetterRouteContextExtractor.create(contextGetter); - } - final Method getValueMethod = findGetValueMethod(returnType); - if (getValueMethod != null) { - return GetValueRouteContextExtractor.create(contextGetter, getValueMethod); - } else { - LOG.warn("Class {} can not be used to determine context, falling back to NULL_EXTRACTOR.", - returnType); - } - } catch (final IllegalAccessException e) { - LOG.warn("Class {} does not conform to Binding Specification. Falling back to NULL_EXTRACTOR", - e); - } - return NULL_EXTRACTOR; - } - - private Method getContextGetter(final Class key) { - for (final Method method : key.getMethods()) { - if (method.getAnnotation(RoutingContext.class) != null) { - return method; - } - } - return null; - } - }); - - /** - * Extract context-reference (Instance Identifier) from Binding TreeNode. - * - * @param input - * - TreeNode from which context reference should be extracted. - * - * @return Instance Identifier representing context reference or null, if tree node does not contain - * context reference. - */ - @Nullable - public abstract InstanceIdentifier extract(TreeNode input); - - /** - * Method for return specific extractor of input object. - * - * @param obj - * - object for get specific extractor - * @return specific extractor - */ - public static ContextReferenceExtractor from(final Class obj) { - return EXTRACTORS.getUnchecked(obj); - } - - private static Method findGetValueMethod(final Class type) { - try { - final Method method = type.getMethod(GET_VALUE_NAME); - if (InstanceIdentifier.class.equals(method.getReturnType())) { - return method; - } - } catch (final NoSuchMethodException e) { - LOG.warn("Value class {} does not comform to Binding Specification.", type, e); - } - return null; - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractor.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractor.java deleted file mode 100644 index 61e2526166..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractor.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor; - -import com.google.common.annotations.Beta; -import com.google.common.base.Throwables; -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 org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -@Beta -final class DirectGetterRouteContextExtractor extends ContextReferenceExtractor { - - private static final Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup(); - - private final MethodHandle handle; - - private DirectGetterRouteContextExtractor(final MethodHandle rawHandle) { - handle = rawHandle.asType(MethodType.methodType(InstanceIdentifier.class, TreeNode.class)); - } - - static ContextReferenceExtractor create(final Method getterMethod) throws IllegalAccessException { - final MethodHandle getterHandle = PUBLIC_LOOKUP.unreflect(getterMethod); - return new DirectGetterRouteContextExtractor(getterHandle); - } - - @SuppressWarnings("checkstyle:IllegalCatch") - @Override - public InstanceIdentifier extract(final TreeNode obj) { - try { - return (InstanceIdentifier) handle.invokeExact(obj); - } catch (final Throwable e) { - Throwables.throwIfUnchecked(e); - throw new RuntimeException(e); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/GetValueRouteContextExtractor.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/GetValueRouteContextExtractor.java deleted file mode 100644 index 1a5ad18cc0..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/GetValueRouteContextExtractor.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor; - -import com.google.common.annotations.Beta; -import com.google.common.base.Throwables; -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 org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -@Beta -final class GetValueRouteContextExtractor extends ContextReferenceExtractor { - - private static final Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup(); - - private final MethodHandle contextHandle; - private final MethodHandle valueHandle; - - private GetValueRouteContextExtractor(final MethodHandle rawContextHandle, final MethodHandle rawValueHandle) { - contextHandle = rawContextHandle.asType(MethodType.methodType(Object.class, TreeNode.class)); - valueHandle = rawValueHandle.asType(MethodType.methodType(InstanceIdentifier.class, Object.class)); - } - - static ContextReferenceExtractor create(final Method contextGetter, final Method getValueMethod) - throws IllegalAccessException { - final MethodHandle rawContextHandle = PUBLIC_LOOKUP.unreflect(contextGetter); - final MethodHandle rawValueHandle = PUBLIC_LOOKUP.unreflect(getValueMethod); - return new GetValueRouteContextExtractor(rawContextHandle, rawValueHandle); - } - - @SuppressWarnings("checkstyle:IllegalCatch") - @Override - public InstanceIdentifier extract(final TreeNode obj) { - try { - final Object ctx = contextHandle.invokeExact(obj); - if (ctx != null) { - return (InstanceIdentifier) valueHandle.invokeExact(ctx); - } - return null; - } catch (final Throwable e) { - Throwables.throwIfUnchecked(e); - throw new RuntimeException(e); - } - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/BindingDOMDataBrokerAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/BindingDOMDataBrokerAdapter.java deleted file mode 100644 index 523642cccd..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/BindingDOMDataBrokerAdapter.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.ImmutableSet; -import java.util.Collection; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeLoopException; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducer; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeService; -import org.opendaylight.mdsal.binding.javav2.api.ReadTransaction; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChain; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChainListener; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree.BindingDOMDataTreeServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction.BindingDOMReadTransactionAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction.BindingDOMTransactionChainAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction.BindingDOMWriteTransactionAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.AbstractForwardedDataBroker; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder.Factory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMDataTreeService; -import org.opendaylight.mdsal.dom.api.DOMService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * The DataBrokerImpl simply defers to the DOMDataBroker for all its operations. All transactions and listener - * registrations are wrapped by the DataBrokerImpl to allow binding aware components to use the DataBroker - * transparently. - * - *

- * Besides this the DataBrokerImpl and it's collaborators also cache data that is already transformed from the - * binding independent to binding aware format - * - */ -@Beta -public class BindingDOMDataBrokerAdapter extends AbstractForwardedDataBroker implements DataBroker, DataTreeService { - - public static final Factory BUILDER_FACTORY = Builder::new; - - private final DataTreeService treeService; - - public BindingDOMDataBrokerAdapter(final DOMDataBroker domDataBroker, final BindingToNormalizedNodeCodec codec) { - super(domDataBroker, codec); - // FIXME: this is an invalid lookup - final DOMDataTreeService domTreeChange = - (DOMDataTreeService) domDataBroker.getExtensions().get(DOMDataTreeService.class); - if (domTreeChange != null) { - treeService = BindingDOMDataTreeServiceAdapter.create(domTreeChange, codec); - } else { - treeService = null; - } - } - - @Override - public ReadTransaction newReadOnlyTransaction() { - return new BindingDOMReadTransactionAdapter(getDelegate().newReadOnlyTransaction(), getCodec()); - } - - @Override - public WriteTransaction newWriteOnlyTransaction() { - return new BindingDOMWriteTransactionAdapter<>(getDelegate().newWriteOnlyTransaction(), getCodec()); - } - - @Override - public TransactionChain createTransactionChain(final TransactionChainListener listener) { - return new BindingDOMTransactionChainAdapter(getDelegate(), getCodec(), listener); - } - - private static class Builder extends BindingDOMAdapterBuilder { - - @Override - public Set> getRequiredDelegates() { - return ImmutableSet.of(DOMDataBroker.class); - } - - @Override - protected DataBroker createInstance(final BindingToNormalizedNodeCodec codec, - final ClassToInstanceMap delegates) { - final DOMDataBroker domDataBroker = delegates.getInstance(DOMDataBroker.class); - return new BindingDOMDataBrokerAdapter(domDataBroker, codec); - } - - } - - @Nonnull - @Override - public ListenerRegistration registerListener(@Nonnull final T listener, - @Nonnull final Collection> subtrees, final boolean allowRxMerges, - @Nonnull final Collection producers) throws DataTreeLoopException { - if (treeService == null) { - throw new UnsupportedOperationException("Underlying data broker does not expose DOMDataTreeChangeService."); - } - return treeService.registerListener(listener, subtrees, allowRxMerges, producers); - } - - @Override - public DataTreeProducer createProducer(final Collection> subtrees) { - return treeService.createProducer(subtrees); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapter.java deleted file mode 100644 index e39cb5430f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapter.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import com.google.common.annotations.Beta; -import java.util.function.BiConsumer; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.CursorAwareWriteTransaction; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeWriteCursor; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.TransactionCommitFailedException; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - -/** - * Allowing cursor to provides write operations(delete, merge, write). - * - * @param - * - {@link DOMDataTreeCursorAwareTransaction} type - */ -@Beta -public class BindingDOMCursorAwareWriteTransactionAdapter - implements CursorAwareWriteTransaction { - - private final T delegate; - private final BindingToNormalizedNodeCodec codec; - - public BindingDOMCursorAwareWriteTransactionAdapter(final T delegate, final BindingToNormalizedNodeCodec codec) { - this.delegate = delegate; - this.codec = codec; - } - - @Nullable - @Override - public

DataTreeWriteCursor createCursor(@Nonnull final DataTreeIdentifier

path) { - final YangInstanceIdentifier yPath = codec.toNormalized(path.getRootIdentifier()); - final DOMDataTreeWriteCursor cursor = - delegate.createCursor(new DOMDataTreeIdentifier(path.getDatastoreType(), yPath)); - return new BindingDOMDataTreeWriteCursorAdapter<>(path, cursor, codec); - } - - @Override - public boolean cancel() { - return delegate.cancel(); - } - - @Override - public void submit(final BiConsumer callback) { - delegate.commit(); - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapter.java deleted file mode 100644 index 1689a4b151..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Collection; -import java.util.stream.Collectors; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeCommitCohort; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeModification; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.modification.LazyDataTreeModification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.PostCanCommitStep; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -/** - * Data tree commit cohort adapter. - * - * @param - * - {@link TreeNode} type - */ -@Beta -public class BindingDOMDataTreeCommitCohortAdapter implements DOMDataTreeCommitCohort { - - private final BindingToNormalizedNodeCodec codec; - private final DataTreeCommitCohort cohort; - - public BindingDOMDataTreeCommitCohortAdapter(final BindingToNormalizedNodeCodec codec, - final DataTreeCommitCohort cohort) { - this.codec = requireNonNull(codec); - this.cohort = requireNonNull(cohort); - } - - @Nonnull - @Override - public FluentFuture canCommit(Object txId, SchemaContext ctx, - Collection candidates) { - final Collection> modifications = candidates.stream().map( - candidate -> LazyDataTreeModification.create(codec, candidate)).collect(Collectors.toList()); - final SettableFuture resultFuture = SettableFuture.create(); - - cohort.canCommit(txId, modifications, (ex, pccs) -> { - if (ex != null) { - resultFuture.setException(ex); - } else { - resultFuture.set(pccs); - } - }); - - return resultFuture; - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortRegistryAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortRegistryAdapter.java deleted file mode 100644 index 7b69055325..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortRegistryAdapter.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeCommitCohort; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeCommitCohortRegistry; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -/** - * Data tree commit cohort registry adapter. - */ -@Beta -public final class BindingDOMDataTreeCommitCohortRegistryAdapter implements DataTreeCommitCohortRegistry { - - private final BindingToNormalizedNodeCodec codec; - private final DOMDataTreeCommitCohortRegistry registry; - - private BindingDOMDataTreeCommitCohortRegistryAdapter(final BindingToNormalizedNodeCodec codec, - final DOMDataTreeCommitCohortRegistry registry) { - this.codec = requireNonNull(codec); - this.registry = requireNonNull(registry); - } - - /** - * Create instance of registry of commit cohort. - * - * @param codec - * - codec for serialize/deserialize - * @param registry - * - dom registry - * @return binding registry - */ - public static DataTreeCommitCohortRegistry from(final BindingToNormalizedNodeCodec codec, - final DOMDataTreeCommitCohortRegistry registry) { - return new BindingDOMDataTreeCommitCohortRegistryAdapter(codec, registry); - } - - @Override - public > ObjectRegistration - registerCommitCohort(final DataTreeIdentifier subtree, final T cohort) { - final BindingDOMDataTreeCommitCohortAdapter adapter = - new BindingDOMDataTreeCommitCohortAdapter<>(codec, cohort); - final DOMDataTreeIdentifier domPath = codec.toDOMDataTreeIdentifier(subtree); - final DOMDataTreeCommitCohortRegistration domReg = registry.registerCommitCohort(domPath, adapter); - return new ObjectRegistration() { - - @Nonnull - @Override - public T getInstance() { - return cohort; - } - - @Override - public void close() { - domReg.close(); - } - }; - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapter.java deleted file mode 100644 index 648579ac8d..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapter.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListeningException; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeModification; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.modification.LazyDataTreeModification; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMDataTreeListener; -import org.opendaylight.mdsal.dom.api.DOMDataTreeListeningException; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate; - -/** - * Data tree listener adapter. - */ -@Beta -public class BindingDOMDataTreeListenerAdapter implements DOMDataTreeListener { - - private final DataTreeListener delegate; - private final BindingToNormalizedNodeCodec codec; - private final LogicalDatastoreType store; - - public BindingDOMDataTreeListenerAdapter(final DataTreeListener delegate, - final BindingToNormalizedNodeCodec codec, final LogicalDatastoreType store) { - this.delegate = requireNonNull(delegate, "delegate"); - this.codec = requireNonNull(codec, "codec"); - this.store = requireNonNull(store, "store"); - } - - @Override - public void onDataTreeChanged(@Nonnull final Collection domChanges, - @Nonnull final Map> domSubtrees) { - - final Collection> changes = toBinding(domChanges); - final Map, TreeNode> subtrees = toBinding(domSubtrees); - - delegate.onDataTreeChanged(changes, subtrees); - } - - private Map, TreeNode> - toBinding(final Map> domSubtrees) { - // FIXME: Introduce lazy translating map - final Map, TreeNode> ret = Maps.newHashMapWithExpectedSize(domSubtrees.size()); - for (final Entry> domEntry : domSubtrees.entrySet()) { - final Entry, TreeNode> bindingEntry = - codec.fromNormalizedNode(domEntry.getKey().getRootIdentifier(), domEntry.getValue()); - ret.put(DataTreeIdentifier.create(store, bindingEntry.getKey()), bindingEntry.getValue()); - } - return ret; - } - - @SuppressWarnings("unchecked") - private Collection> toBinding(final Collection domChanges) { - return Collection.class.cast(LazyDataTreeModification.from(codec, domChanges, store)); - } - - @Override - public void onDataTreeFailed(@Nonnull final Collection causes) { - final List bindingCauses = new ArrayList<>(causes.size()); - for (final DOMDataTreeListeningException cause : causes) { - bindingCauses.add(mapException(cause)); - } - - delegate.onDataTreeFailed(bindingCauses); - } - - private static DataTreeListeningException mapException(final DOMDataTreeListeningException cause) { - // FIXME: Extend logic - return new DataTreeListeningException(cause.getMessage(), cause); - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapter.java deleted file mode 100644 index 2453e12583..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapter.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.CursorAwareWriteTransaction; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducer; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducerException; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException; - -/** - * Producer adapter. - */ -@Beta -public final class BindingDOMDataTreeProducerAdapter implements DataTreeProducer { - - private final DOMDataTreeProducer delegate; - private final BindingToNormalizedNodeCodec codec; - - private BindingDOMDataTreeProducerAdapter(final DOMDataTreeProducer delegate, - final BindingToNormalizedNodeCodec codec) { - this.delegate = requireNonNull(delegate); - this.codec = codec; - } - - /** - * Create instance of producer data tree. - * - * @param domProducer - * - DOM producer - * @param codec - * - codec for serialize/deserialize - * @return instance of producer - */ - public static DataTreeProducer create(final DOMDataTreeProducer domProducer, - final BindingToNormalizedNodeCodec codec) { - return new BindingDOMDataTreeProducerAdapter(domProducer, codec); - } - - @Nonnull - @Override - public CursorAwareWriteTransaction createTransaction(final boolean isolated) { - final DOMDataTreeCursorAwareTransaction domTx = delegate.createTransaction(isolated); - return new BindingDOMCursorAwareWriteTransactionAdapter<>(domTx, codec); - } - - @Nonnull - @Override - public DataTreeProducer createProducer(@Nonnull final Collection> subtrees) { - final Collection domSubtrees = codec.toDOMDataTreeIdentifiers(subtrees); - final DOMDataTreeProducer domChildProducer = delegate.createProducer(domSubtrees); - return BindingDOMDataTreeProducerAdapter.create(domChildProducer, codec); - } - - @Override - public void close() throws DataTreeProducerException { - try { - delegate.close(); - } catch (final DOMDataTreeProducerException e) { - throw new DataTreeProducerException(e.getMessage(), e); - } - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapter.java deleted file mode 100644 index 2918f3d5c1..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeLoopException; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducer; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeService; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer; -import org.opendaylight.mdsal.dom.api.DOMDataTreeService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * Data tree service adapter. - * - */ -@Beta -public final class BindingDOMDataTreeServiceAdapter implements DataTreeService { - - private final DOMDataTreeService delegate; - private final BindingToNormalizedNodeCodec codec; - - private BindingDOMDataTreeServiceAdapter(final DOMDataTreeService delegate, - final BindingToNormalizedNodeCodec codec) { - this.delegate = requireNonNull(delegate, "delegate"); - this.codec = requireNonNull(codec, "codec"); - } - - /** - * Create instance of data tree service adapter. - * - * @param domService - * - data tree service - * @param codec - * - codec foer serialize/deserialize - * @return instance of data tree service adapter - */ - public static BindingDOMDataTreeServiceAdapter create(final DOMDataTreeService domService, - final BindingToNormalizedNodeCodec codec) { - return new BindingDOMDataTreeServiceAdapter(domService, codec); - } - - @Override - public DataTreeProducer createProducer(final Collection> subtrees) { - final Collection domSubtrees = codec.toDOMDataTreeIdentifiers(subtrees); - final DOMDataTreeProducer domChildProducer = delegate.createProducer(domSubtrees); - return BindingDOMDataTreeProducerAdapter.create(domChildProducer, codec); - } - - @Nonnull - @Override - public ListenerRegistration registerListener(@Nonnull final T listener, - @Nonnull final Collection> subtrees, final boolean allowRxMerges, - @Nonnull final Collection producers) throws DataTreeLoopException { - throw new UnsupportedOperationException("Not implemented yet."); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapter.java deleted file mode 100644 index 455e340019..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapter.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import com.google.common.annotations.Beta; -import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Map.Entry; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeWriteCursor; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Data tree write cursor adapter. - * - * @param - * - {@link DOMDataTreeWriteCursor} type - */ -@Beta -public class BindingDOMDataTreeWriteCursorAdapter implements DataTreeWriteCursor { - - private final T delegate; - private final BindingToNormalizedNodeCodec codec; - private final Deque> stack = new ArrayDeque<>(); - - public BindingDOMDataTreeWriteCursorAdapter(final DataTreeIdentifier path, final T delegate, - final BindingToNormalizedNodeCodec codec) { - - this.delegate = delegate; - this.codec = codec; - path.getRootIdentifier().getPathArguments().forEach(stack::push); - } - - private YangInstanceIdentifier.PathArgument convertToNormalized(final TreeArgument child) { - stack.push(child); - final InstanceIdentifier iid = InstanceIdentifier.create(stack); - final YangInstanceIdentifier ret = codec.toNormalized(iid); - stack.pop(); - return ret.getLastPathArgument(); - } - - private

Entry> - convertToNormalized(final TreeArgument child, final P data) { - stack.push(child); - final InstanceIdentifier iid = InstanceIdentifier.create(stack); - final Entry> entry = - codec.toNormalizedNode(new SimpleEntry<>(iid, data)); - stack.pop(); - return entry; - } - - @Override - public void delete(final TreeArgument child) { - delegate.delete(convertToNormalized(child)); - } - - @Override - public void merge(final TreeArgument child, final U data) { - final Entry> entry = convertToNormalized(child, data); - delegate.merge(entry.getKey().getLastPathArgument(), entry.getValue()); - } - - @Override - public

void write(final TreeArgument

child, final P data) { - final Entry> entry = convertToNormalized(child, data); - delegate.write(entry.getKey().getLastPathArgument(), entry.getValue()); - } - - @Override - public void enter(@Nonnull final TreeArgument child) { - stack.push(child); - } - - @Override - public void enter(@Nonnull final TreeArgument... path) { - for (final TreeArgument pathArgument : path) { - enter(pathArgument); - } - } - - @Override - public void enter(@Nonnull final Iterable> path) { - path.forEach(this::enter); - } - - @Override - public void exit() { - stack.pop(); - } - - @Override - public void exit(final int depth) { - for (int i = 0; i < depth; i++) { - exit(); - } - } - - @Override - public void close() { - delegate.close(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapter.java deleted file mode 100644 index f0f4963a67..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapter.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import com.google.common.annotations.Beta; -import java.util.Optional; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.MountPointListener; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMMountPointListener; -import org.opendaylight.mdsal.dom.api.DOMMountPointService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException; - -/** - * Mount point listener adapter. - * - * @param - * - {@link MountPointListener} type - */ -@Beta -public final class BindingDOMMountPointListenerAdapter - implements ListenerRegistration, DOMMountPointListener { - - private final T listener; - private final ListenerRegistration registration; - private final BindingToNormalizedNodeCodec codec; - - public BindingDOMMountPointListenerAdapter(final T listener, final BindingToNormalizedNodeCodec codec, - final DOMMountPointService mountService) { - this.listener = listener; - this.codec = codec; - this.registration = mountService.registerProvisionListener(this); - } - - @Nonnull - @Override - public T getInstance() { - return listener; - } - - @Override - public void close() { - registration.close(); - } - - @Override - public void onMountPointCreated(final YangInstanceIdentifier path) { - try { - final InstanceIdentifier bindingPath = toBinding(path); - listener.onMountPointCreated(bindingPath); - } catch (final DeserializationException e) { - BindingDOMMountPointServiceAdapter.LOG.error("Unable to translate mountPoint path {}." + " Omitting event.", - path, e); - } - } - - private InstanceIdentifier toBinding(final YangInstanceIdentifier path) - throws DeserializationException { - final Optional> instanceIdentifierOptional = codec.toBinding(path); - if (instanceIdentifierOptional.isPresent()) { - return instanceIdentifierOptional.get(); - } else { - throw new DeserializationException("Deserialization unsuccessful, " + instanceIdentifierOptional); - } - } - - @Override - public void onMountPointRemoved(final YangInstanceIdentifier path) { - try { - final InstanceIdentifier bindingPath = toBinding(path); - listener.onMountPointRemoved(bindingPath); - } catch (final DeserializationException e) { - BindingDOMMountPointServiceAdapter.LOG.error("Unable to translate mountPoint path {}." + " Omitting event.", - path, e); - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapter.java deleted file mode 100644 index 860c494a22..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import java.util.Optional; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.MountPoint; -import org.opendaylight.mdsal.binding.javav2.api.MountPointListener; -import org.opendaylight.mdsal.binding.javav2.api.MountPointService; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.dom.api.DOMMountPoint; -import org.opendaylight.mdsal.dom.api.DOMMountPointService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Mount point service adapter. - */ -@Beta -public class BindingDOMMountPointServiceAdapter implements MountPointService { - - public static final Logger LOG = LoggerFactory.getLogger(BindingDOMMountPointServiceAdapter.class); - - private final BindingToNormalizedNodeCodec codec; - private final DOMMountPointService mountService; - private final LoadingCache bindingMountpoints = - CacheBuilder.newBuilder().weakKeys().build(new CacheLoader() { - - @Nonnull - @Override - public BindingMountPointAdapter load(@Nonnull final DOMMountPoint key) throws Exception { - return new BindingMountPointAdapter(codec, key); - } - }); - - public BindingDOMMountPointServiceAdapter(final DOMMountPointService mountService, - final BindingToNormalizedNodeCodec codec) { - this.codec = codec; - this.mountService = mountService; - } - - @Override - public Optional getMountPoint(final InstanceIdentifier mountPoint) { - - final YangInstanceIdentifier domPath = codec.toYangInstanceIdentifierBlocking(mountPoint); - final Optional domMount = mountService.getMountPoint(domPath); - if (domMount.isPresent()) { - return Optional.ofNullable(bindingMountpoints.getUnchecked(domMount.get())); - } - return Optional.empty(); - } - - @Override - public ListenerRegistration registerListener(final InstanceIdentifier path, - final T listener) { - return new BindingDOMMountPointListenerAdapter<>(listener, codec, mountService); - } - -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapter.java deleted file mode 100644 index 9ea00710a0..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.LoadingCache; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.BindingService; -import org.opendaylight.mdsal.binding.javav2.api.MountPoint; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.loader.BindingDOMAdapterLoader; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.dom.api.DOMMountPoint; -import org.opendaylight.mdsal.dom.api.DOMService; - -/** - * Binding mount point adapter. - */ -@Beta -public class BindingMountPointAdapter implements MountPoint { - - private final InstanceIdentifier identifier; - private LoadingCache, Optional> services; - - public BindingMountPointAdapter(final BindingToNormalizedNodeCodec codec, final DOMMountPoint domMountPoint) { - identifier = codec.getCodecRegistry().fromYangInstanceIdentifier(domMountPoint.getIdentifier()); - services = CacheBuilder.newBuilder().build(new BindingDOMAdapterLoader(codec) { - - @Nullable - @Override - protected DOMService getDelegate(final Class reqDeleg) { - return domMountPoint.getService(reqDeleg).orElse(null); - } - }); - } - - @Nonnull - @Override - public InstanceIdentifier getIdentifier() { - return identifier; - } - - @Override - public Optional getService(final Class service) { - final Optional potential = services.getUnchecked(service); - if (potential.isPresent()) { - return Optional.of(service.cast(potential.get())); - } - return Optional.empty(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationListenerAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationListenerAdapter.java deleted file mode 100644 index b16c236e54..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationListenerAdapter.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMap; -import com.google.common.reflect.TypeToken; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.dom.codec.serialized.LazySerializedDOMNotification; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener; -import org.opendaylight.mdsal.dom.api.DOMNotification; -import org.opendaylight.mdsal.dom.api.DOMNotificationListener; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -/** - * Notification listener adapter. - */ -@Beta -public class BindingDOMNotificationListenerAdapter implements DOMNotificationListener { - - private final BindingNormalizedNodeSerializer codec; - private final NotificationListener delegate; - private final Map invokers; - - public BindingDOMNotificationListenerAdapter(final BindingNormalizedNodeSerializer codec, - final NotificationListener delegate) { - this.codec = codec; - this.delegate = delegate; - this.invokers = createInvokerMapFor(delegate.getClass()); - } - - @Override - public void onNotification(@Nonnull final DOMNotification notification) { - final Notification baNotification = deserialize(notification); - final QName notificationQName = notification.getType().getLastComponent(); - getInvoker(notification.getType()).invokeNotification(delegate, notificationQName, - (Instantiable) baNotification); - } - - private Notification deserialize(final DOMNotification notification) { - if (notification instanceof LazySerializedDOMNotification) { - return ((LazySerializedDOMNotification) notification).getBindingData(); - } - return codec.fromNormalizedNodeNotification(notification.getType(), notification.getBody()); - } - - private NotificationListenerInvoker getInvoker(final SchemaPath type) { - return invokers.get(type); - } - - /** - * Get supported notifications. - * - * @return supported notifications - */ - public Set getSupportedNotifications() { - return invokers.keySet(); - } - - /** - * Create map of all notification listeners. - * - * @param implClz - * - class type of {@link NotificationListener} - * @return map of notification listeners - */ - private static Map - createInvokerMapFor(final Class implClz) { - final Map builder = new HashMap<>(); - for (final TypeToken ifaceToken : TypeToken.of(implClz).getTypes().interfaces()) { - final Class iface = ifaceToken.getRawType(); - if (NotificationListener.class.isAssignableFrom(iface) && BindingReflections.isBindingClass(iface)) { - @SuppressWarnings("unchecked") - final Class listenerType = - (Class) iface; - final NotificationListenerInvoker invoker = NotificationListenerInvoker.from(listenerType); - for (final SchemaPath path : getNotificationTypes(listenerType)) { - builder.put(path, invoker); - } - } - } - return ImmutableMap.copyOf(builder); - } - - private static Set getNotificationTypes(final Class type) { - // TODO: Investigate possibility and performance impact if we cache this or expose - // it from NotificationListenerInvoker - final Set ret = new HashSet<>(); - for (final Method method : type.getMethods()) { - if (BindingReflections.isNotificationCallback(method)) { - final Class notification = method.getParameterTypes()[0]; - final QName name = BindingReflections.findQName(notification); - ret.add(SchemaPath.create(true, name)); - } - } - return ret; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationPublishServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationPublishServiceAdapter.java deleted file mode 100644 index 19b760d772..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationPublishServiceAdapter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.opendaylight.mdsal.binding.javav2.api.NotificationPublishService; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder.Factory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.serialized.LazySerializedDOMNotification; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.dom.api.DOMNotification; -import org.opendaylight.mdsal.dom.api.DOMNotificationPublishService; -import org.opendaylight.mdsal.dom.api.DOMService; - -/** - * Adapter for notification publisher service. - */ -@Beta -public class BindingDOMNotificationPublishServiceAdapter implements NotificationPublishService, AutoCloseable { - - public static final Factory BUILDER_FACTORY = Builder::new; - - private final BindingToNormalizedNodeCodec codecRegistry; - private final DOMNotificationPublishService domPublishService; - - public BindingDOMNotificationPublishServiceAdapter(final BindingToNormalizedNodeCodec codec, - final DOMNotificationPublishService domPublishService) { - this.codecRegistry = codec; - this.domPublishService = domPublishService; - } - - public BindingToNormalizedNodeCodec getCodecRegistry() { - return codecRegistry; - } - - public DOMNotificationPublishService getDomPublishService() { - return domPublishService; - } - - @Override - public void putNotification(final Notification notification) throws InterruptedException { - domPublishService.putNotification(toDomNotification(notification)); - } - - @Override - public ListenableFuture offerNotification(final Notification notification) { - final ListenableFuture offerResult = domPublishService.offerNotification(toDomNotification(notification)); - return DOMNotificationPublishService.REJECTED.equals(offerResult) ? NotificationPublishService.REJECTED - : offerResult; - } - - @Override - public ListenableFuture offerNotification(final Notification notification, final int timeout, - final TimeUnit unit) throws InterruptedException { - final ListenableFuture offerResult = - domPublishService.offerNotification(toDomNotification(notification), timeout, unit); - return DOMNotificationPublishService.REJECTED.equals(offerResult) ? NotificationPublishService.REJECTED - : offerResult; - } - - private DOMNotification toDomNotification(final Notification notification) { - return LazySerializedDOMNotification.create(codecRegistry, notification); - } - - @Override - public void close() throws Exception { - // NOOP - } - - private static class Builder extends BindingDOMAdapterBuilder { - - @Override - public Set> getRequiredDelegates() { - return ImmutableSet.of(DOMNotificationPublishService.class); - } - - @Override - protected NotificationPublishService createInstance(final BindingToNormalizedNodeCodec codec, - final ClassToInstanceMap delegates) { - final DOMNotificationPublishService domPublish = delegates.getInstance(DOMNotificationPublishService.class); - return new BindingDOMNotificationPublishServiceAdapter(codec, domPublish); - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationServiceAdapter.java deleted file mode 100644 index 5a8c6a87d8..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/BindingDOMNotificationServiceAdapter.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.api.NotificationService; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder.Factory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener; -import org.opendaylight.mdsal.dom.api.DOMNotificationService; -import org.opendaylight.mdsal.dom.api.DOMService; -import org.opendaylight.yangtools.concepts.AbstractListenerRegistration; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * Notification service adapter. - */ -@Beta -public class BindingDOMNotificationServiceAdapter implements NotificationService, AutoCloseable { - - public static final Factory BUILDER_FACTORY = Builder::new; - - private final BindingNormalizedNodeSerializer codec; - private final DOMNotificationService domNotifService; - - public BindingDOMNotificationServiceAdapter(final BindingNormalizedNodeSerializer codec, - final DOMNotificationService domNotifService) { - this.codec = codec; - this.domNotifService = domNotifService; - } - - @Override - public ListenerRegistration registerNotificationListener(final T listener) { - final BindingDOMNotificationListenerAdapter domListener = - new BindingDOMNotificationListenerAdapter(codec, listener); - final ListenerRegistration domRegistration = - domNotifService.registerNotificationListener(domListener, domListener.getSupportedNotifications()); - return new ListenerRegistrationImpl<>(listener, domRegistration); - } - - @Override - public void close() throws Exception { - // NOOP - } - - private static class ListenerRegistrationImpl - extends AbstractListenerRegistration { - private final ListenerRegistration listenerRegistration; - - ListenerRegistrationImpl(final T listener, final ListenerRegistration listenerRegistration) { - super(listener); - this.listenerRegistration = listenerRegistration; - } - - @Override - protected void removeRegistration() { - listenerRegistration.close(); - } - } - - private static class Builder extends BindingDOMAdapterBuilder { - - @Override - protected NotificationService createInstance(final BindingToNormalizedNodeCodec codec, - final ClassToInstanceMap delegates) { - final DOMNotificationService domNotification = delegates.getInstance(DOMNotificationService.class); - return new BindingDOMNotificationServiceAdapter(codec.getCodecRegistry(), domNotification); - } - - @Override - public Set> getRequiredDelegates() { - return ImmutableSet.of(DOMNotificationService.class); - } - } - - /** - * Get DOM notification service. - * - * @return DOM notification service - */ - public DOMNotificationService getDomService() { - return domNotifService; - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/NotificationListenerInvoker.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/NotificationListenerInvoker.java deleted file mode 100644 index 6db4e816d6..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/notification/NotificationListenerInvoker.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener; -import org.opendaylight.yangtools.yang.common.QName; - -/** - * Provides single method invocation of notification callbacks on supplied instance. - * - *

- * Notification Listener invoker provides common invocation interface for any subtype of - * {@link NotificationListener}. via {@link #invokeNotification(NotificationListener, QName, Instantiable)} - * method. - */ -@Beta -public final class NotificationListenerInvoker { - - private static final Lookup LOOKUP = MethodHandles.publicLookup(); - - private static final LoadingCache, NotificationListenerInvoker> INVOKERS = - CacheBuilder.newBuilder().weakKeys() - .build(new CacheLoader, NotificationListenerInvoker>() { - - private NotificationListenerInvoker - createInvoker(final Class key) { - return new NotificationListenerInvoker(createInvokerMap(key)); - } - - private Map - createInvokerMap(final Class key) { - final Builder ret = ImmutableMap.builder(); - for (final Method method : key.getMethods()) { - if (BindingReflections.isNotificationCallback(method)) { - - final Class notification = method.getParameterTypes()[0]; - final QName name = BindingReflections.findQName(notification); - MethodHandle handle; - try { - handle = LOOKUP.unreflect(method).asType(MethodType.methodType(void.class, - NotificationListener.class, Instantiable.class)); - ret.put(name, handle); - } catch (final IllegalAccessException e) { - throw new IllegalStateException("Can not access public method.", e); - } - } - - } - return ret.build(); - } - - @Override - public NotificationListenerInvoker load(final Class key) - throws Exception { - return createInvoker(key); - } - - }); - - private final Map methodInvokers; - - public NotificationListenerInvoker(final Map map) { - this.methodInvokers = map; - } - - /** - * Creates Notification service invoker for specified type. - * - * @param type - * - NotificationListener interface, which was generated from model. - * @return Cached instance of {@link NotificationListenerInvoker} for supplied notification type. - * - */ - public static NotificationListenerInvoker from(final Class type) { - Preconditions.checkArgument(type.isInterface()); - Preconditions.checkArgument(BindingReflections.isBindingClass(type)); - return INVOKERS.getUnchecked(type); - } - - /** - * Invokes supplied Notification on provided implementation of NotificationListener. - * - * @param impl - * - implementation on which notification callback should be invoked. - * @param notificationName - * - name of notification to be invoked. - * @param input - * - input data for notification. - * - */ - @SuppressWarnings("checkstyle:IllegalCatch") - public void invokeNotification(@Nonnull final NotificationListener impl, @Nonnull final QName notificationName, - @Nullable final Instantiable input) { - requireNonNull(impl, "implementation must be supplied"); - final MethodHandle invoker = methodInvokers.get(notificationName); - Preconditions.checkArgument(invoker != null, "Supplied notification is not valid for implementation %s", impl); - try { - invoker.invokeExact(impl, input); - } catch (final Throwable e) { - Throwables.throwIfUnchecked(e); - throw new RuntimeException(e); - } - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/ActionServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/ActionServiceAdapter.java deleted file mode 100644 index 426be662c7..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/ActionServiceAdapter.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.MoreExecutors; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.serialized.LazySerializedContainerNode; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMActionResult; -import org.opendaylight.mdsal.dom.api.DOMActionService; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -@Beta -class ActionServiceAdapter implements InvocationHandler { - - private final Class> type; - private final BindingToNormalizedNodeCodec codec; - private final DOMActionService delegate; - private final Action proxy; - private final SchemaPath path; - - ActionServiceAdapter(final Class> type, - final BindingToNormalizedNodeCodec codec, final DOMActionService domService) { - this.type = requireNonNull(type); - this.codec = requireNonNull(codec); - this.delegate = requireNonNull(domService); - this.path = getCodec().getActionPath(type); - proxy = (Action) Proxy.newProxyInstance(type.getClassLoader(), - new Class[] { type }, this); - } - - public BindingToNormalizedNodeCodec getCodec() { - return codec; - } - - public DOMActionService getDelegate() { - return delegate; - } - - Action getProxy() { - return proxy; - } - - public Class> getType() { - return type; - } - - public SchemaPath getPath() { - return path; - } - - @Override - @SuppressWarnings("checkstyle:hiddenField") - public Object invoke(final Object proxy, final Method method, final Object[] args) { - - switch (method.getName()) { - case "equals": - if (args.length == 1) { - return proxy == args[0]; - } - break; - case "hashCode": - if (args.length == 0) { - return System.identityHashCode(proxy); - } - break; - case "toString": - if (args.length == 0) { - return type.getName() + "$Adapter{delegate=" + getDelegate() + "}"; - } - break; - case "invoke": - if (args.length == 3) { - final Input input = (Input) requireNonNull(args[0]); - final InstanceIdentifier path = (InstanceIdentifier) requireNonNull(args[1]); - final RpcCallback callback = (RpcCallback) requireNonNull(args[2]); - - final FluentFuture future = getDelegate().invokeAction(getPath(), - new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, getCodec().toNormalized(path)), - (ContainerNode) LazySerializedContainerNode.create(getPath(), (TreeNode) input, - getCodec().getCodecRegistry())); - //FIXME:this part is ugly, how to bridge FluentFuture and RpcCallback better? - // Invocation returned a future we know about -- return that future instead - if (future instanceof LazyDOMActionResultFuture) { - ListenableFuture> bindingFuture = - ((LazyDOMActionResultFuture) future).getBindingFuture(); - Futures.addCallback(bindingFuture, new FutureCallback>() { - - @Override - public void onSuccess(final RpcResult result) { - if (result.isSuccessful()) { - callback.onSuccess((Output) result.getResult()); - } else { - //FIXME: It's not suitable to do this way here. It's better for - // 'onFailure' to accept Collection as input. - result.getErrors().forEach(e -> callback.onFailure(e.getCause())); - } - } - - @Override - public void onFailure(final Throwable throwable) { - callback.onFailure(throwable); - } - }, MoreExecutors.directExecutor()); - } else { - Futures.addCallback(future, new FutureCallback() { - - @Override - public void onSuccess(final DOMActionResult result) { - if (result.getErrors().isEmpty()) { - callback.onSuccess((Output) getCodec().fromNormalizedNodeOperationData(getPath(), - result.getOutput().get())); - } else { - result.getErrors().forEach(e -> callback.onFailure(e.getCause())); - } - } - - @Override - public void onFailure(final Throwable throwable) { - callback.onFailure(throwable); - } - }, MoreExecutors.directExecutor()); - } - } - return 0; - default: - break; - } - - throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported."); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationProviderServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationProviderServiceAdapter.java deleted file mode 100644 index f80087271e..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationProviderServiceAdapter.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.SettableFuture; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.RpcActionProviderService; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation.BindingDOMOperationProviderServiceAdapter.AbstractImplAdapter.ActionAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation.BindingDOMOperationProviderServiceAdapter.AbstractImplAdapter.RpcAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.registration.BindingDOMOperationAdapterRegistration; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.serialized.LazySerializedContainerNode; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Operation; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMActionImplementation; -import org.opendaylight.mdsal.dom.api.DOMActionInstance; -import org.opendaylight.mdsal.dom.api.DOMActionProviderService; -import org.opendaylight.mdsal.dom.api.DOMActionResult; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier; -import org.opendaylight.mdsal.dom.api.DOMRpcImplementation; -import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration; -import org.opendaylight.mdsal.dom.api.DOMRpcProviderService; -import org.opendaylight.mdsal.dom.api.DOMRpcResult; -import org.opendaylight.yangtools.concepts.ObjectRegistration; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -/** - * Operation service provider adapter. - */ -@Beta -public class BindingDOMOperationProviderServiceAdapter implements RpcActionProviderService { - - private static final Set GLOBAL = ImmutableSet.of(YangInstanceIdentifier.builder().build()); - private final BindingToNormalizedNodeCodec codec; - private final DOMRpcProviderService domRpcRegistry; - private final DOMActionProviderService domActionRegistry; - - public BindingDOMOperationProviderServiceAdapter(final DOMRpcProviderService domRpcRegistry, - final DOMActionProviderService domActionRegistry, final BindingToNormalizedNodeCodec codec) { - this.codec = codec; - this.domRpcRegistry = domRpcRegistry; - this.domActionRegistry = domActionRegistry; - } - - @Override - public , T extends S> ObjectRegistration registerRpcImplementation(final Class type, - final T implementation) { - return register(type, implementation, GLOBAL); - } - - @Override - public , T extends S> ObjectRegistration registerRpcImplementation(final Class type, - final T implementation, final Set> paths) { - return register(type, implementation, toYangInstanceIdentifiers(paths)); - } - - private , T extends S> ObjectRegistration register(final Class type, - final T implementation, final Collection rpcContextPaths) { - final SchemaPath path = codec.getRpcPath(type); - final Set domRpcs = createDomRpcIdentifiers(path, rpcContextPaths); - final DOMRpcImplementationRegistration domReg = domRpcRegistry.registerRpcImplementation( - new RpcAdapter(codec.getCodecRegistry(), type, implementation), domRpcs); - return new BindingDOMOperationAdapterRegistration<>(implementation, domReg); - } - - private static Set createDomRpcIdentifiers(final SchemaPath rpc, - final Collection paths) { - final Set ret = new HashSet<>(); - for (final YangInstanceIdentifier path : paths) { - ret.add(DOMRpcIdentifier.create(rpc, path)); - } - return ret; - } - - private Collection toYangInstanceIdentifiers(final Set> identifiers) { - final Collection ret = new ArrayList<>(identifiers.size()); - for (final InstanceIdentifier binding : identifiers) { - ret.add(codec.toYangInstanceIdentifierCached(binding)); - } - return ret; - } - - @Override - public , T extends S, P extends TreeNode> ObjectRegistration - registerActionImplementation(final Class type, final T implementation, - final LogicalDatastoreType datastore, final Set> validNodes) { - final SchemaPath path = codec.getActionPath(type); - final ObjectRegistration domReg = domActionRegistry.registerActionImplementation( - new ActionAdapter(codec.getCodecRegistry(), type, implementation), - DOMActionInstance.of(path, codec.toDOMDataTreeIdentifiers(validNodes))); - return new BindingDOMOperationAdapterRegistration<>(implementation, domReg); - } - - public abstract static class AbstractImplAdapter { - protected final BindingNormalizedNodeCodecRegistry codec; - protected final D delegate; - private final QName inputQname; - - AbstractImplAdapter(final BindingNormalizedNodeCodecRegistry codec, final Class clazz, - final D delegate) { - this.codec = requireNonNull(codec); - this.delegate = requireNonNull(delegate); - inputQname = QName.create(BindingReflections.getQNameModule(clazz), "input").intern(); - } - - TreeNode deserialize(final SchemaPath path, final NormalizedNode input) { - if (input instanceof LazySerializedContainerNode) { - return ((LazySerializedContainerNode) input).bindingData(); - } - final SchemaPath inputSchemaPath = path.createChild(inputQname); - return codec.fromNormalizedNodeOperationData(inputSchemaPath, (ContainerNode) input); - } - - public static final class RpcAdapter extends AbstractImplAdapter implements DOMRpcImplementation { - - RpcAdapter(final BindingNormalizedNodeCodecRegistry codec, final Class clazz, - final Rpc delegate) { - super(codec, clazz, delegate); - } - - @SuppressWarnings("unchecked") - @Nonnull - @Override - public FluentFuture invokeRpc(@Nonnull final DOMRpcIdentifier rpc, - @Nullable final NormalizedNode input) { - final TreeNode bindingInput = input != null ? deserialize(rpc.getType(), input) : null; - final SettableFuture> bindingResult = SettableFuture.create(); - CompletableFuture.runAsync(() -> delegate.invoke((Input) bindingInput, - new RpcCallback>() { - @Override - public void onSuccess(final Output output) { - bindingResult.set(RpcResultBuilder.success(output).build()); - } - - @Override - public void onFailure(final Throwable error) { - bindingResult.set(RpcResultBuilder.failed().withError(ErrorType.APPLICATION, - error.getMessage(), error).build()); - } - }) - ); - return LazyDOMRpcResultFuture.create(codec,bindingResult); - } - } - - public static final class ActionAdapter extends AbstractImplAdapter - implements DOMActionImplementation { - - ActionAdapter(final BindingNormalizedNodeCodecRegistry codec, final Class clazz, - final Action delegate) { - super(codec, clazz, delegate); - } - - @Override - @SuppressWarnings("unchecked") - @Nonnull - public FluentFuture invokeAction(final SchemaPath type, - final DOMDataTreeIdentifier path, final ContainerNode input) { - final TreeNode bindingInput = input != null ? deserialize(type, input) : null; - final SettableFuture> bindingResult = SettableFuture.create(); - CompletableFuture.runAsync(() -> delegate.invoke((Input) bindingInput, - codec.fromYangInstanceIdentifier(path.getRootIdentifier()), - new RpcCallback>() { - @Override - public void onSuccess(final Output output) { - bindingResult.set(RpcResultBuilder.success(output).build()); - } - - @Override - public void onFailure(final Throwable error) { - bindingResult.set(RpcResultBuilder.failed().withError(ErrorType.APPLICATION, - error.getMessage(), error).build()); - } - }) - ); - return LazyDOMActionResultFuture.create(codec, bindingResult); - } - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationServiceAdapter.java deleted file mode 100644 index 80c2843f82..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationServiceAdapter.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.ClassToInstanceMap; -import com.google.common.collect.ImmutableSet; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.RpcActionConsumerRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder.Factory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.ListAction; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMActionService; -import org.opendaylight.mdsal.dom.api.DOMRpcService; -import org.opendaylight.mdsal.dom.api.DOMService; - -/** - * Adapter for operation service. - */ -@Beta -public class BindingDOMOperationServiceAdapter implements RpcActionConsumerRegistry { - - public static final Factory BUILDER_FACTORY = Builder::new; - - private final DOMRpcService domRpcService; - private final DOMActionService domActionService; - private final BindingToNormalizedNodeCodec codec; - private final LoadingCache>, RpcServiceAdapter> rpcProxies = CacheBuilder.newBuilder() - .weakKeys().build(new CacheLoader>, RpcServiceAdapter>() { - @Nonnull - @Override - public RpcServiceAdapter load(@Nonnull final Class> key) { - Preconditions.checkArgument(BindingReflections.isBindingClass(key)); - Preconditions.checkArgument(key.isInterface(), - "Supplied Operation service type must be interface."); - if (Rpc.class.isAssignableFrom(key)) { - return new RpcServiceAdapter(key, codec, domRpcService); - } - - throw new UnsupportedOperationException(); - } - }); - - private final LoadingCache>, ActionServiceAdapter> - actionProxies = CacheBuilder.newBuilder().weakKeys().build( - new CacheLoader>, ActionServiceAdapter>() { - @Nonnull - @Override - public ActionServiceAdapter load(@Nonnull - final Class> key) { - Preconditions.checkArgument(BindingReflections.isBindingClass(key)); - Preconditions.checkArgument(key.isInterface(), - "Supplied Operation service type must be interface."); - if (Action.class.isAssignableFrom(key)) { - return new ActionServiceAdapter(key, codec, domActionService); - } - - throw new UnsupportedOperationException(); - } - }); - - public BindingDOMOperationServiceAdapter(final DOMRpcService domRpcService, final DOMActionService domActionService, - final BindingToNormalizedNodeCodec codec) { - this.domRpcService = requireNonNull(domRpcService); - this.domActionService = requireNonNull(domActionService); - this.codec = requireNonNull(codec); - } - - @SuppressWarnings("unchecked") - @Override - public > T getRpcService(final Class rpc) { - return (T) rpcProxies.getUnchecked(requireNonNull(rpc)).getProxy(); - } - - private static final class Builder extends BindingDOMAdapterBuilder { - - @Override - protected RpcActionConsumerRegistry createInstance(final BindingToNormalizedNodeCodec codec, - final ClassToInstanceMap delegates) { - final DOMRpcService domRpcService = delegates.getInstance(DOMRpcService.class); - final DOMActionService domActionService = delegates.getInstance(DOMActionService.class); - return new BindingDOMOperationServiceAdapter(domRpcService, domActionService, codec); - } - - @Override - public Set> getRequiredDelegates() { - return ImmutableSet.of(DOMRpcService.class, DOMActionService.class); - } - } - - @SuppressWarnings("unchecked") - @Override - public > T getActionService(final Class serviceInterface) { - return (T) actionProxies.getUnchecked(requireNonNull(serviceInterface)).getProxy(); - } - - @Override - public > T getListActionService(final Class serviceInterface) { - return getActionService(serviceInterface); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMActionResultFuture.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMActionResultFuture.java deleted file mode 100644 index 24c880ec5f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMActionResultFuture.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.AbstractFuture; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMActionException; -import org.opendaylight.mdsal.dom.api.DOMActionNotAvailableException; -import org.opendaylight.mdsal.dom.api.DOMActionResult; -import org.opendaylight.mdsal.dom.spi.SimpleDOMActionResult; -import org.opendaylight.yangtools.util.concurrent.ExceptionMapper; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.common.RpcResult; - -/** - * DOM operation result from Binding. - */ -@Beta -final class LazyDOMActionResultFuture extends AbstractFuture { - private static final ExceptionMapper DOM_ACTION_EX_MAPPER = - new ExceptionMapper("action", DOMActionException.class) { - @Override - protected DOMActionException newWithCause(String message, Throwable cause) { - return cause instanceof DOMActionException ? (DOMActionException)cause - : new DOMActionNotAvailableException("Action failed", cause); - } - }; - - private final ListenableFuture> bindingFuture; - private final BindingNormalizedNodeCodecRegistry codec; - private volatile DOMActionResult result; - - private LazyDOMActionResultFuture(final ListenableFuture> delegate, - final BindingNormalizedNodeCodecRegistry codec) { - this.bindingFuture = requireNonNull(delegate, "delegate"); - this.codec = requireNonNull(codec, "codec"); - } - - static FluentFuture create(final BindingNormalizedNodeCodecRegistry codec, - final ListenableFuture> bindingResult) { - return new LazyDOMActionResultFuture(bindingResult, codec); - } - - ListenableFuture> getBindingFuture() { - return bindingFuture; - } - - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - return bindingFuture.cancel(mayInterruptIfRunning); - } - - @Override - public void addListener(@Nonnull final Runnable listener, @Nonnull final Executor executor) { - bindingFuture.addListener(listener, executor); - } - - @Override - public DOMActionResult get() throws InterruptedException, ExecutionException { - if (result != null) { - return result; - } - - try { - return transformIfNecessary(bindingFuture.get()); - } catch (ExecutionException e) { - throw new ExecutionException(e.getMessage(), DOM_ACTION_EX_MAPPER.apply(e)); - } - } - - @Override - public DOMActionResult get(@Nonnull final long timeout, final TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - if (result != null) { - return result; - } - - try { - return transformIfNecessary(bindingFuture.get(timeout, unit)); - } catch (ExecutionException e) { - throw new ExecutionException(e.getMessage(), DOM_ACTION_EX_MAPPER.apply(e)); - } - } - - @Override - public boolean isCancelled() { - return bindingFuture.isCancelled(); - } - - @Override - public boolean isDone() { - return bindingFuture.isDone(); - } - - private synchronized DOMActionResult transformIfNecessary(final RpcResult input) { - if (result == null) { - result = transform(input); - } - return result; - } - - private DOMActionResult transform(final RpcResult input) { - if (input.isSuccessful()) { - final Object inputData = input.getResult(); - if (inputData instanceof DataContainer) { - return new SimpleDOMActionResult(codec.toNormalizedNodeOperationData((TreeNode) inputData), - ImmutableList.of()); - } else { - return new SimpleDOMActionResult(ImmutableList.of()); - } - } - return new SimpleDOMActionResult(input.getErrors()); - } - -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMRpcResultFuture.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMRpcResultFuture.java deleted file mode 100644 index a37279c24f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/LazyDOMRpcResultFuture.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.AbstractFuture; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMRpcException; -import org.opendaylight.mdsal.dom.api.DOMRpcResult; -import org.opendaylight.mdsal.dom.api.DefaultDOMRpcException; -import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult; -import org.opendaylight.yangtools.util.concurrent.ExceptionMapper; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * DOM operation result from Binding. - */ -@Beta -final class LazyDOMRpcResultFuture extends AbstractFuture { - private static final ExceptionMapper DOM_RPC_EX_MAPPER = - new ExceptionMapper("rpc", DOMRpcException.class) { - @Override - protected DOMRpcException newWithCause(String message, Throwable cause) { - return cause instanceof DOMRpcException ? (DOMRpcException)cause - : new DefaultDOMRpcException("RPC failed", cause); - } - }; - - private final ListenableFuture> bindingFuture; - private final BindingNormalizedNodeCodecRegistry codec; - private volatile DOMRpcResult result; - - private LazyDOMRpcResultFuture(final ListenableFuture> delegate, - final BindingNormalizedNodeCodecRegistry codec) { - this.bindingFuture = requireNonNull(delegate, "delegate"); - this.codec = requireNonNull(codec, "codec"); - } - - static FluentFuture create(final BindingNormalizedNodeCodecRegistry codec, - final ListenableFuture> bindingResult) { - return new LazyDOMRpcResultFuture(bindingResult, codec); - } - - ListenableFuture> getBindingFuture() { - return bindingFuture; - } - - @Override - public boolean cancel(final boolean mayInterruptIfRunning) { - return bindingFuture.cancel(mayInterruptIfRunning); - } - - @Override - public void addListener(@Nonnull final Runnable listener, @Nonnull final Executor executor) { - bindingFuture.addListener(listener, executor); - } - - @Override - public DOMRpcResult get() throws InterruptedException, ExecutionException { - if (result != null) { - return result; - } - - try { - return transformIfNecessary(bindingFuture.get()); - } catch (ExecutionException e) { - throw new ExecutionException(e.getMessage(), DOM_RPC_EX_MAPPER.apply(e)); - } - } - - @Override - public DOMRpcResult get(@Nonnull final long timeout, final TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - if (result != null) { - return result; - } - - try { - return transformIfNecessary(bindingFuture.get(timeout, unit)); - } catch (ExecutionException e) { - throw new ExecutionException(e.getMessage(), DOM_RPC_EX_MAPPER.apply(e)); - } - } - - @Override - public boolean isCancelled() { - return bindingFuture.isCancelled(); - } - - @Override - public boolean isDone() { - return bindingFuture.isDone(); - } - - private synchronized DOMRpcResult transformIfNecessary(final RpcResult input) { - if (result == null) { - result = transform(input); - } - return result; - } - - private DOMRpcResult transform(final RpcResult input) { - if (input.isSuccessful()) { - final Object inputData = input.getResult(); - if (inputData instanceof DataContainer) { - return new DefaultDOMRpcResult(codec.toNormalizedNodeOperationData((TreeNode) inputData)); - } else { - return new DefaultDOMRpcResult((NormalizedNode) null); - } - } - return new DefaultDOMRpcResult(input.getErrors()); - } - -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/RpcServiceAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/RpcServiceAdapter.java deleted file mode 100644 index 25d6b21089..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/RpcServiceAdapter.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.MoreExecutors; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Collection; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor.ContextReferenceExtractor; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.serialized.LazySerializedContainerNode; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMRpcResult; -import org.opendaylight.mdsal.dom.api.DOMRpcService; -import org.opendaylight.mdsal.dom.spi.RpcRoutingStrategy; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; -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.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; -import org.opendaylight.yangtools.yang.model.api.RpcDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -@Beta -class RpcServiceAdapter implements InvocationHandler { - - private final RpcInvocationStrategy strategy; - private final Class> type; - private final BindingToNormalizedNodeCodec codec; - private final DOMRpcService delegate; - private final Rpc proxy; - - RpcServiceAdapter(final Class> type, final BindingToNormalizedNodeCodec codec, - final DOMRpcService domService) { - this.type = requireNonNull(type); - this.codec = requireNonNull(codec); - this.delegate = requireNonNull(domService); - strategy = createStrategy(type); - proxy = (Rpc) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, this); - } - - private RpcInvocationStrategy createStrategy(final Class> rpcInterface) { - final RpcDefinition rpc = codec.getRpcDefinition(rpcInterface); - final RpcRoutingStrategy domStrategy = RpcRoutingStrategy.from(rpc); - if (domStrategy.isContextBasedRouted()) { - try { - return new RoutedStrategy(rpc.getPath(), - rpcInterface.getMethod("invoke", Input.class, RpcCallback.class), domStrategy.getLeaf()); - } catch (final NoSuchMethodException e) { - throw new IllegalStateException("Can not find 'invoke' method", e); - } - } - return new NonRoutedStrategy(rpc.getPath()); - } - - Rpc getProxy() { - return proxy; - } - - @Override - @SuppressWarnings("checkstyle:hiddenField") - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - switch (method.getName()) { - case "toString": - return type.getName() + "$Adapter{delegate=" + delegate.toString() + "}"; - case "hashCode": - return System.identityHashCode(proxy); - case "equals": - return proxy == args[0]; - case "invoke": - if (args.length == 2) { - final Input input = (Input) requireNonNull(args[0]); - final RpcCallback callback = (RpcCallback) requireNonNull(args[1]); - ListenableFuture> future = strategy.invoke((TreeNode) input); - Futures.addCallback(future, new FutureCallback>() { - - @Override - public void onSuccess(final RpcResult result) { - if (result.getErrors().isEmpty()) { - callback.onSuccess((Output) result.getResult()); - } else { - result.getErrors().forEach(e -> callback.onFailure(e.getCause())); - } - } - - @Override - public void onFailure(final Throwable throwable) { - callback.onFailure(throwable); - } - }, MoreExecutors.directExecutor()); - } - return 0; - default: - break; - } - - throw new UnsupportedOperationException("Method " + method.toString() + "is unsupported."); - } - - private abstract class RpcInvocationStrategy { - - private final SchemaPath rpcName; - - protected RpcInvocationStrategy(final SchemaPath path) { - rpcName = path; - } - - final ListenableFuture> invoke(final TreeNode input) { - return invoke0(rpcName, serialize(input)); - } - - abstract NormalizedNode serialize(TreeNode input); - - final ListenableFuture> invokeEmpty() { - return invoke0(rpcName, null); - } - - final SchemaPath getRpcName() { - return rpcName; - } - - private ListenableFuture> invoke0(final SchemaPath schemaPath, final NormalizedNode input) { - final ListenableFuture listenInPoolThread = - JdkFutureAdapters.listenInPoolThread(delegate.invokeRpc(schemaPath, input)); - if (listenInPoolThread instanceof LazyDOMRpcResultFuture) { - return ((LazyDOMRpcResultFuture) listenInPoolThread).getBindingFuture(); - } - - return transformFuture(schemaPath, listenInPoolThread, codec.getCodecFactory()); - } - - private ListenableFuture> transformFuture(final SchemaPath rpc, - final ListenableFuture domFuture, final BindingNormalizedNodeCodecRegistry resultCodec) { - return Futures.transform(domFuture, input -> { - final NormalizedNode domData = input.getResult(); - final TreeNode bindingResult; - if (domData != null) { - final SchemaPath rpcOutput = rpc.createChild(QName.create(rpc.getLastComponent(), "output")); - bindingResult = resultCodec.fromNormalizedNodeOperationData(rpcOutput, (ContainerNode) domData); - } else { - bindingResult = null; - } - - // DOMRpcResult does not have a notion of success, hence we have to reverse-engineer it by looking - // at reported errors and checking whether they are just warnings. - final Collection errors = input.getErrors(); - return RpcResult.class.cast(RpcResultBuilder.status(errors.stream() - .noneMatch(error -> error.getSeverity() == ErrorSeverity.ERROR)) - .withResult(bindingResult).withRpcErrors(errors).build()); - }, MoreExecutors.directExecutor()); - } - } - - private final class NonRoutedStrategy extends RpcInvocationStrategy { - - protected NonRoutedStrategy(final SchemaPath path) { - super(path); - } - - @Override - NormalizedNode serialize(final TreeNode input) { - return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry()); - } - - } - - private final class RoutedStrategy extends RpcInvocationStrategy { - - private final ContextReferenceExtractor refExtractor; - private final NodeIdentifier contextName; - - protected RoutedStrategy(final SchemaPath path, final Method rpcMethod, final QName leafName) { - super(path); - final Optional>> maybeInputType = - BindingReflections.resolveOperationInputClass(rpcMethod); - Preconditions.checkState(maybeInputType.isPresent(), "RPC method %s has no input", rpcMethod.getName()); - final Class> inputType = maybeInputType.get(); - refExtractor = ContextReferenceExtractor.from(inputType); - this.contextName = new NodeIdentifier(leafName); - } - - @SuppressWarnings("rawtypes") - @Override - NormalizedNode serialize(final TreeNode input) { - final InstanceIdentifier bindingII = refExtractor.extract(input); - if (bindingII != null) { - final YangInstanceIdentifier yangII = codec.toYangInstanceIdentifierCached(bindingII); - final LeafNode contextRef = ImmutableNodes.leafNode(contextName, yangII); - return LazySerializedContainerNode.withContextRef(getRpcName(), input, contextRef, - codec.getCodecRegistry()); - } - return LazySerializedContainerNode.create(getRpcName(), input, codec.getCodecRegistry()); - } - - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMReadTransactionAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMReadTransactionAdapter.java deleted file mode 100644 index 92872d9a34..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMReadTransactionAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction; - -import com.google.common.annotations.Beta; -import java.util.function.BiConsumer; -import org.opendaylight.mdsal.binding.javav2.api.ReadTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.AbstractForwardedTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.common.api.ReadFailedException; -import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction; - -/** - * Read transaction adapter. - */ -@Beta -public class BindingDOMReadTransactionAdapter extends AbstractForwardedTransaction - implements ReadTransaction { - - public BindingDOMReadTransactionAdapter(final DOMDataTreeReadTransaction delegate, - final BindingToNormalizedNodeCodec codec) { - super(delegate, codec); - } - - @Override - public void read(final LogicalDatastoreType store, final InstanceIdentifier path, - final BiConsumer callback) { - doRead(getDelegate(), store, path); - } - - @Override - public void close() { - getDelegate().close(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMTransactionChainAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMTransactionChainAdapter.java deleted file mode 100644 index 3dcfe8278e..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMTransactionChainAdapter.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction; - -import static com.google.common.base.Preconditions.checkState; -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.MoreExecutors; -import java.util.function.Supplier; -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.api.ReadTransaction; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChain; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChainClosedException; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChainListener; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.common.api.CommitInfo; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction; -import org.opendaylight.mdsal.dom.api.DOMTransactionChain; -import org.opendaylight.mdsal.dom.api.DOMTransactionChainClosedException; -import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener; -import org.opendaylight.yangtools.concepts.Delegator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Transaction chain adapter. - */ -@Beta -public final class BindingDOMTransactionChainAdapter implements TransactionChain, Delegator { - - private static final Logger LOG = LoggerFactory.getLogger(BindingDOMTransactionChainAdapter.class); - - private final DOMTransactionChain delegate; - private final BindingToNormalizedNodeCodec codec; - private final TransactionChainListener bindingListener; - - public BindingDOMTransactionChainAdapter(final DOMDataBroker chainFactory, final BindingToNormalizedNodeCodec codec, - final TransactionChainListener listener) { - requireNonNull(chainFactory, "DOM Transaction chain factory must not be null"); - this.bindingListener = listener; - this.delegate = chainFactory.createTransactionChain(new DelegateChainListener()); - this.codec = codec; - } - - @Override - public DOMTransactionChain getDelegate() { - return delegate; - } - - @Override - public ReadTransaction newReadOnlyTransaction() { - return new BindingDOMReadTransactionAdapter(createTransaction(delegate::newReadOnlyTransaction), codec); - } - - @Override - public WriteTransaction newWriteOnlyTransaction() { - final DOMDataTreeWriteTransaction delegateTx = createTransaction(delegate::newWriteOnlyTransaction); - return new BindingDOMWriteTransactionAdapter(delegateTx, codec) { - - @Override - public @NonNull FluentFuture commit() { - return listenForFailure(this, super.commit()); - } - - }; - } - - private > F listenForFailure(final WriteTransaction tx, final F future) { - future.addCallback(new FutureCallback() { - @Override - public void onFailure(final Throwable throwable) { - failTransactionChain(tx, throwable); - } - - @Override - public void onSuccess(final T result) { - // Intentionally NOOP - } - }, MoreExecutors.directExecutor()); - - return future; - } - - private void failTransactionChain(final WriteTransaction tx, final Throwable throwable) { - /* - * We assume correct state change for underlying transaction - * - * chain, so we are not changing any of our internal state to mark that we failed. - */ - this.bindingListener.onTransactionChainFailed(this, tx, throwable); - } - - @Override - public void close() { - delegate.close(); - } - - private static T createTransaction(final Supplier supplier) { - try { - return supplier.get(); - } catch (DOMTransactionChainClosedException e) { - throw new TransactionChainClosedException("Transaction chain already closed", e); - } - } - - private final class DelegateChainListener implements DOMTransactionChainListener { - @Override - public void onTransactionChainFailed(final DOMTransactionChain chain, - final DOMDataTreeTransaction transaction, final Throwable cause) { - checkState(delegate.equals(chain), "Listener for %s was invoked for incorrect chain %s.", delegate, chain); - /* - * Intentionally NOOP, callback for failure, since we are also listening on each transaction - * future for failure, in order to have reference to Binding Transaction (which was seen by client - * of this transaction chain), instead of DOM transaction which is known only to this chain, - * binding transaction implementation and underlying transaction chain. - * - */ - LOG.debug("Transaction chain {} failed. Failed DOM Transaction {}", this, transaction, cause); - } - - @Override - public void onTransactionChainSuccessful(final DOMTransactionChain chain) { - checkState(delegate.equals(chain), "Listener for %s was invoked for incorrect chain %s.", delegate, chain); - bindingListener.onTransactionChainSuccessful(BindingDOMTransactionChainAdapter.this); - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMWriteTransactionAdapter.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMWriteTransactionAdapter.java deleted file mode 100644 index df2b96c096..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/transaction/BindingDOMWriteTransactionAdapter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.AbstractWriteTransaction; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.CommitInfo; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction; - -/** - * Write transaction adapter. - * - * @param - * - {@link DOMDataTreeWriteTransaction} type - */ -@Beta -public class BindingDOMWriteTransactionAdapter - extends AbstractWriteTransaction - implements WriteTransaction { - - public BindingDOMWriteTransactionAdapter(final T delegateTx, final BindingToNormalizedNodeCodec codec) { - super(delegateTx, codec); - } - - @Override - public void put(final LogicalDatastoreType store, final InstanceIdentifier path, - final U data) { - put(store, path, data, false); - } - - @Override - public void merge(final LogicalDatastoreType store, final InstanceIdentifier path, - final U data) { - merge(store, path, data, false); - } - - @Override - public void delete(final LogicalDatastoreType store, final InstanceIdentifier path) { - doDelete(store, path); - } - - @Override - public @NonNull FluentFuture commit() { - return doCommit(); - } - - @Override - public boolean cancel() { - return doCancel(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDOMOperationAdapterRegistration.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDOMOperationAdapterRegistration.java deleted file mode 100644 index 1f6f202358..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDOMOperationAdapterRegistration.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.registration; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.Operation; -import org.opendaylight.yangtools.concepts.AbstractObjectRegistration; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -/** - * Registration of Binding - DOM Operation adapter. - * - * @param - * - {@link Operation} type - */ -@Beta -public class BindingDOMOperationAdapterRegistration extends AbstractObjectRegistration { - - private final ObjectRegistration reg; - - public BindingDOMOperationAdapterRegistration(final T instance, final ObjectRegistration reg) { - super(instance); - this.reg = reg; - } - - @Override - protected void removeRegistration() { - reg.close(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDataTreeListenerRegistration.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDataTreeListenerRegistration.java deleted file mode 100644 index 41ed4b4f78..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/registration/BindingDataTreeListenerRegistration.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.registration; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.yangtools.concepts.AbstractListenerRegistration; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * Registration of data tree listener. - * - * @param - * - {@link DataTreeListener} type - */ -@Beta -public class BindingDataTreeListenerRegistration - extends AbstractListenerRegistration { - - private final ListenerRegistration domReg; - - public BindingDataTreeListenerRegistration(final L listener, final ListenerRegistration domReg) { - super(listener); - this.domReg = requireNonNull(domReg); - } - - @Override - protected void removeRegistration() { - domReg.close(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedDataBroker.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedDataBroker.java deleted file mode 100644 index df461cc36b..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedDataBroker.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi; - -import com.google.common.annotations.Beta; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.yangtools.concepts.Delegator; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This abstract class forwards DOM Data Broker and provides de-serialization of DOM data to Binding data. - */ -@Beta -public abstract class AbstractForwardedDataBroker implements Delegator, AutoCloseable { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractForwardedDataBroker.class); - - // The Broker to whom we do all forwarding - private final DOMDataBroker domDataBroker; - - private final BindingToNormalizedNodeCodec codec; - - protected AbstractForwardedDataBroker(final DOMDataBroker domDataBroker, final BindingToNormalizedNodeCodec codec) { - this.domDataBroker = domDataBroker; - this.codec = codec; - } - - protected BindingToNormalizedNodeCodec getCodec() { - return codec; - } - - @Override - public DOMDataBroker getDelegate() { - return domDataBroker; - } - - protected Map, TreeNode> toBinding( - final InstanceIdentifier path, - final Map> normalized) { - final Map, TreeNode> newMap = new HashMap<>(); - - for (final Map.Entry> entry : normalized.entrySet()) { - try { - final Optional, TreeNode>> potential = - getCodec().toBinding(entry); - if (potential.isPresent()) { - final Entry, TreeNode> binding = potential.get(); - newMap.put(binding.getKey(), binding.getValue()); - } - } catch (final DeserializationException e) { - LOG.warn("Failed to transform {}, omitting it", entry, e); - } - } - return newMap; - } - - protected Set> toBinding(final InstanceIdentifier path, - final Set normalized) { - final Set> hashSet = new HashSet<>(); - for (final YangInstanceIdentifier normalizedPath : normalized) { - try { - final Optional> potential = - getCodec().toBinding(normalizedPath); - if (potential.isPresent()) { - final InstanceIdentifier binding = potential.get(); - hashSet.add(binding); - } else if (normalizedPath - .getLastPathArgument() instanceof YangInstanceIdentifier.AugmentationIdentifier) { - hashSet.add(path); - } - } catch (final DeserializationException e) { - LOG.warn("Failed to transform {}, omitting it", normalizedPath, e); - } - } - return hashSet; - } - - @SuppressWarnings("unchecked") - protected Optional toBindingData(final InstanceIdentifier path, final NormalizedNode data) { - if (path.isWildcarded()) { - return Optional.empty(); - } - return (Optional) getCodec().deserializeFunction(path) - .apply(Optional.of(data)); - } - - @Override - public void close() { - // Intentional NOOP - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedTransaction.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedTransaction.java deleted file mode 100644 index ce0c955bb9..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractForwardedTransaction.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.FluentFuture; -import com.google.common.util.concurrent.MoreExecutors; -import java.util.Optional; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction; -import org.opendaylight.yangtools.concepts.Delegator; -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * Abstract class for forwards transaction and codec for serialize/deserialize DOM and Binding data. - * - * @param type of asynchronous transaction - */ -@Beta -public abstract class AbstractForwardedTransaction - implements Delegator, Identifiable { - - private final T delegate; - private final BindingToNormalizedNodeCodec codec; - - public AbstractForwardedTransaction(final T delegateTx, final BindingToNormalizedNodeCodec codec) { - this.delegate = requireNonNull(delegateTx, "Delegate must not be null"); - this.codec = requireNonNull(codec, "Codec must not be null"); - } - - @Nonnull - @Override - public final Object getIdentifier() { - return delegate.getIdentifier(); - } - - @Override - public final T getDelegate() { - return delegate; - } - - @SuppressWarnings("unchecked") - protected final S getDelegateChecked(final Class txType) { - checkState(txType.isInstance(delegate)); - return (S) delegate; - } - - protected final BindingToNormalizedNodeCodec getCodec() { - return codec; - } - - protected final FluentFuture> doRead( - final DOMDataTreeReadTransaction readTx, final LogicalDatastoreType store, - final InstanceIdentifier path) { - checkArgument(!path.isWildcarded(), "Invalid read of wildcarded path %s", path); - - return readTx.read(store, codec.toYangInstanceIdentifierBlocking(path)) - .transform(codec.deserializeFunction(path)::apply, MoreExecutors.directExecutor()); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractWriteTransaction.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractWriteTransaction.java deleted file mode 100644 index b94d821df1..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/AbstractWriteTransaction.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.FluentFuture; -import java.util.Map.Entry; -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.CommitInfo; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Abstract Base Transaction for transactions which are backed by {@link DOMDataTreeWriteTransaction}. - */ -@Beta -public abstract class AbstractWriteTransaction - extends AbstractForwardedTransaction { - - protected AbstractWriteTransaction(final T delegate, final BindingToNormalizedNodeCodec codec) { - super(delegate, codec); - } - - /** - * Put Binding data to specific datastore via - * {@link DOMDataTreeWriteTransaction#put(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}. - * - * @param store - * - specific {@link LogicalDatastoreType} - * @param path - * - path to data - * @param data - * - data to be written to specific path - * @param createParents - * - option to create parent of data to be write - */ - public final void put(final LogicalDatastoreType store, final InstanceIdentifier path, - final U data, final boolean createParents) { - Preconditions.checkArgument(!path.isWildcarded(), "Cannot put data into wildcarded path %s", path); - - final Entry> normalized = getCodec().toNormalizedNode(path, data); - if (createParents) { - ensureParentsByMerge(store, normalized.getKey(), path); - } else { - ensureListParentIfNeeded(store, path, normalized); - } - - getDelegate().put(store, normalized.getKey(), normalized.getValue()); - } - - /** - * Merge Binding data with existing data on specific path via - * {@link DOMDataTreeWriteTransaction#merge(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}. - * - * @param store - * - specific {@link LogicalDatastoreType} - * @param path - * - path to data - * @param data - * - data to be merged - * @param createParents - * - option to create parent of data to be merged - */ - public final void merge(final LogicalDatastoreType store, final InstanceIdentifier path, - final U data, final boolean createParents) { - Preconditions.checkArgument(!path.isWildcarded(), "Cannot merge data into wildcarded path %s", path); - - final Entry> normalized = getCodec().toNormalizedNode(path, data); - if (createParents) { - ensureParentsByMerge(store, normalized.getKey(), path); - } else { - ensureListParentIfNeeded(store, path, normalized); - } - - getDelegate().merge(store, normalized.getKey(), normalized.getValue()); - } - - /** - * Ensures list parent if item is list, otherwise noop. - * - *

- * One of properties of binding specification is that it is impossible to represent list as a whole and - * thus it is impossible to write empty variation of MapNode without creating parent node, with empty - * list. - * - *

- * This actually makes writes such as - * - *

-     * put("Nodes", new NodesBuilder().build());
-     * put("Nodes/Node[key]", new NodeBuilder().setKey("key").build());
-     * 
- * - *

- * To result in three DOM operations: - * - *

-     * put("/nodes", domNodes);
-     * merge("/nodes/node", domNodeList);
-     * put("/nodes/node/node[key]", domNode);
-     * 
- * - *

- * In order to allow that to be inserted if necessary, if we know item is list item, we will try to merge - * empty MapNode or OrderedNodeMap to ensure list exists. - * - * @param store - * - Data Store type - * @param path - * - Path to data (Binding Aware) - * @param normalized - * - Normalized version of data to be written - */ - private void ensureListParentIfNeeded(final LogicalDatastoreType store, final InstanceIdentifier path, - final Entry> normalized) { - if (IdentifiableItem.class.isAssignableFrom(path.getTargetType())) { - final YangInstanceIdentifier parentMapPath = normalized.getKey().getParent(); - Preconditions.checkArgument(parentMapPath != null, "Map path %s does not have a parent", path); - - final NormalizedNode emptyParent = getCodec().getDefaultNodeFor(parentMapPath); - getDelegate().merge(store, parentMapPath, emptyParent); - } - } - - /** - * Subclasses of this class are required to implement creation of parent nodes based on behavior of their - * underlying transaction. - * - * @param store - * - an instance of LogicalDatastoreType - * @param domPath - * - an instance of YangInstanceIdentifier - * @param path - * - an instance of InstanceIdentifier - */ - protected final void ensureParentsByMerge(final LogicalDatastoreType store, final YangInstanceIdentifier domPath, - final InstanceIdentifier path) { - final YangInstanceIdentifier parentPath = domPath.getParent(); - if (parentPath != null) { - final NormalizedNode parentNode = getCodec().instanceIdentifierToNode(parentPath); - getDelegate().merge(store, YangInstanceIdentifier.create(parentNode.getIdentifier()), parentNode); - } - } - - protected final void doDelete(final LogicalDatastoreType store, final InstanceIdentifier path) { - Preconditions.checkArgument(!path.isWildcarded(), "Cannot delete wildcarded path %s", path); - - final YangInstanceIdentifier normalized = getCodec().toYangInstanceIdentifierBlocking(path); - getDelegate().delete(store, normalized); - } - - protected final @NonNull FluentFuture doCommit() { - return getDelegate().commit(); - } - - protected final boolean doCancel() { - return getDelegate().cancel(); - } -} - diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilder.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilder.java deleted file mode 100644 index af86fe1128..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilder.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.ImmutableClassToInstanceMap; -import com.google.common.collect.MutableClassToInstanceMap; -import java.util.Set; -import org.opendaylight.yangtools.concepts.Builder; - -/** - * Class for building instances of delegates of specific type. - * - * @param - * - builded specific object type - * @param - * - delegates type - */ -@Beta -public abstract class AdapterBuilder implements Builder { - - private final ClassToInstanceMap delegates = MutableClassToInstanceMap.create(); - - protected abstract T createInstance(ClassToInstanceMap immutableDelegates); - - /** - * Get required delegates. - * - * @return set of delegates - */ - public abstract Set> getRequiredDelegates(); - - /** - * Add delegate to set of delegates. - * - * @param type - * - type of delegate - * @param impl - * - implementation of delegate - */ - public final void addDelegate(final Class type, final D impl) { - delegates.put(type, impl); - } - - @Override - public final T build() { - checkAllRequiredServices(); - return createInstance(ImmutableClassToInstanceMap.copyOf(delegates)); - } - - private void checkAllRequiredServices() { - for (final Class type : getRequiredDelegates()) { - Preconditions.checkState(delegates.get(type) != null, "Requires service %s is not defined.", type); - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/BindingDOMAdapterBuilder.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/BindingDOMAdapterBuilder.java deleted file mode 100644 index b7dace6bf9..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/BindingDOMAdapterBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ClassToInstanceMap; -import org.opendaylight.mdsal.binding.javav2.api.BindingService; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMService; - -/** - * Binding DOM adapter builder instance. - * - * @param - * - Binding Service type - */ -@Beta -public abstract class BindingDOMAdapterBuilder extends AdapterBuilder { - - private BindingToNormalizedNodeCodec codec; - - protected abstract T createInstance(BindingToNormalizedNodeCodec myCodec, ClassToInstanceMap delegates); - - @Override - protected final T createInstance(final ClassToInstanceMap delegates) { - Preconditions.checkState(codec != null); - return createInstance(codec, delegates); - } - - /** - * Set codec for builder. - * - * @param codec - * - binding normalized node codec - */ - public void setCodec(final BindingToNormalizedNodeCodec codec) { - this.codec = codec; - } - - /** - * Factory for creating of new builder. - * - * @param - * - Binding Service type - */ - public interface Factory { - - /** - * Prepare new builder for service. - * - * @return adapter builder - */ - BindingDOMAdapterBuilder newBuilder(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/AdapterLoader.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/AdapterLoader.java deleted file mode 100644 index b50ebe45d1..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/AdapterLoader.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.loader; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheLoader; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.AdapterBuilder; - -/** - * Class for loading specific delegate type. - * - * @param - * - built specific object type - * @param - * - delegates type - */ -@Beta -public abstract class AdapterLoader extends CacheLoader, Optional> { - - @Nullable - protected abstract D getDelegate(Class reqDeleg); - - @Nonnull - protected abstract AdapterBuilder createBuilder(Class key); - - @Nonnull - @Override - public Optional load(@Nonnull final Class key) { - - final AdapterBuilder builder = createBuilder(key); - for (final Class reqDeleg : builder.getRequiredDelegates()) { - final D deleg = getDelegate(reqDeleg); - if (deleg != null) { - builder.addDelegate(reqDeleg, deleg); - } else { - return Optional.empty(); - } - } - return Optional.of(builder.build()); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoader.java b/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoader.java deleted file mode 100644 index fa2742586d..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoader.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.loader; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import java.util.Map; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.BindingService; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.api.NotificationPublishService; -import org.opendaylight.mdsal.binding.javav2.api.NotificationService; -import org.opendaylight.mdsal.binding.javav2.api.RpcActionConsumerRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.BindingDOMDataBrokerAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationPublishServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation.BindingDOMOperationServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.AdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder.BindingDOMAdapterBuilder.Factory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMService; - -/** - * Loader for factory of services. - */ -@Beta -public abstract class BindingDOMAdapterLoader extends AdapterLoader { - - @SuppressWarnings("checkstyle:GenericWhitespace") - private static final Map, BindingDOMAdapterBuilder.Factory> FACTORIES = - ImmutableMap., BindingDOMAdapterBuilder.Factory> builder() - .put(DataBroker.class, BindingDOMDataBrokerAdapter.BUILDER_FACTORY) - .put(NotificationPublishService.class, BindingDOMNotificationPublishServiceAdapter.BUILDER_FACTORY) - .put(NotificationService.class, BindingDOMNotificationServiceAdapter.BUILDER_FACTORY) - .put(RpcActionConsumerRegistry.class, BindingDOMOperationServiceAdapter.BUILDER_FACTORY) - .build(); - - private final BindingToNormalizedNodeCodec codec; - - public BindingDOMAdapterLoader(final BindingToNormalizedNodeCodec codec) { - this.codec = codec; - } - - @Nonnull - @Override - protected final AdapterBuilder - createBuilder(final Class key) { - final Factory factory = FACTORIES.get(key); - Preconditions.checkArgument(factory != null, "Unsupported service type %s", key); - final BindingDOMAdapterBuilder builder = factory.newBuilder(); - builder.setCodec(codec); - return builder; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractorTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractorTest.java deleted file mode 100644 index 9de72f9d2a..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/extractor/DirectGetterRouteContextExtractorTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -import java.lang.reflect.Method; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -public class DirectGetterRouteContextExtractorTest { - - private static final InstanceIdentifier INSTANCE_IDENTIFIER = InstanceIdentifier.create(TreeNode.class); - private static final String EXCEPTION_TEXT = "testException"; - - @Test - public void basicTest() throws Exception { - final Method testMthd = this.getClass().getDeclaredMethod("testMethod", TreeNode.class); - testMthd.setAccessible(true); - final ContextReferenceExtractor referenceExtractor = DirectGetterRouteContextExtractor.create(testMthd); - assertEquals(testMethod(mock(TreeNode.class)), referenceExtractor.extract(mock(TreeNode.class))); - - try { - referenceExtractor.extract(null); - fail("Expected exception"); - } catch (NullPointerException e) { - assertTrue(e.getMessage().equals(EXCEPTION_TEXT)); - } - } - - private static InstanceIdentifier testMethod(TreeNode data) { - if (data == null) { - throw new NullPointerException(EXCEPTION_TEXT); - } - return INSTANCE_IDENTIFIER; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapterTest.java deleted file mode 100644 index cca2391e5f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMCursorAwareWriteTransactionAdapterTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.function.BiConsumer; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeWriteCursor; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - -public class BindingDOMCursorAwareWriteTransactionAdapterTest { - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void basicTest() throws Exception { - final DOMDataTreeCursorAwareTransaction delegate = mock(DOMDataTreeCursorAwareTransaction.class); - final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = - new BindingToNormalizedNodeCodec( - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), - registry); - final YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.EMPTY; - doReturn(yangInstanceIdentifier).when(registry).toYangInstanceIdentifier(any()); - - final BindingDOMCursorAwareWriteTransactionAdapter adapter = - new BindingDOMCursorAwareWriteTransactionAdapter<>(delegate, codec); - - final DataTreeIdentifier dti = - DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(TreeNode.class)); - - final DOMDataTreeWriteCursor dtwc = mock(DOMDataTreeWriteCursor.class); - doReturn(dtwc).when(delegate) - .createCursor(new DOMDataTreeIdentifier(dti.getDatastoreType(), yangInstanceIdentifier)); - final DataTreeWriteCursor cursor = adapter.createCursor(dti); - assertNotNull(cursor); - - doReturn(null).when(delegate).commit(); - final BiConsumer callback = mock(BiConsumer.class); - adapter.submit(callback); - verify(delegate).commit(); - - doReturn(true).when(delegate).cancel(); - assertTrue(adapter.cancel()); - verify(delegate).cancel(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapterTest.java deleted file mode 100644 index 3a8cce1f89..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeCommitCohortAdapterTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import java.util.Arrays; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeCommitCohort; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.modification.LazyDataTreeModification; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.yangtools.yang.common.QName; -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.tree.DataTreeCandidateNode; - -public class BindingDOMDataTreeCommitCohortAdapterTest { - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void canCommitTest() throws Exception { - final DataTreeCommitCohort cohort = mock(DataTreeCommitCohort.class); - final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = - new BindingToNormalizedNodeCodec( - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), - registry); - - final BindingDOMDataTreeCommitCohortAdapter adapter = - new BindingDOMDataTreeCommitCohortAdapter<>(codec, cohort); - assertNotNull(adapter); - - final DOMDataTreeCandidate domDataTreeCandidate = mock(DOMDataTreeCandidate.class); - final DOMDataTreeIdentifier domDataTreeIdentifier = - new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY); - doReturn(InstanceIdentifier.create(TreeNode.class)).when(registry).fromYangInstanceIdentifier(any()); - final BindingTreeCodec bindingCodecTree = mock(BindingTreeCodec.class); - final BindingTreeNodeCodec bindingCodecTreeNode = mock(BindingTreeNodeCodec.class); - doReturn(bindingCodecTreeNode).when(bindingCodecTree).getSubtreeCodec(any(InstanceIdentifier.class)); - doReturn(bindingCodecTree).when(registry).getCodecContext(); - doReturn(domDataTreeIdentifier).when(domDataTreeCandidate).getRootPath(); - final DataTreeCandidateNode dataTreeCandidateNode = mock(DataTreeCandidateNode.class); - final NodeIdentifier codeIdentifier = NodeIdentifier.create(QName.create("test", "2017-06-15", "ltest")); - doReturn(codeIdentifier).when(dataTreeCandidateNode) - .getIdentifier(); - doReturn(mock(TreeArgument.class)).when(bindingCodecTreeNode).deserializePathArgument(codeIdentifier); - doReturn(dataTreeCandidateNode).when(domDataTreeCandidate).getRootNode(); - assertNotNull(LazyDataTreeModification.create(codec, domDataTreeCandidate)); - - doNothing().when(cohort).canCommit(any(), any(), any()); - adapter.canCommit(new Object(), null, Arrays.asList(domDataTreeCandidate)); - verify(cohort).canCommit(any(), any(), any()); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapterTest.java deleted file mode 100644 index fb83cd16a9..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeListenerAdapterTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingBrokerTestFactory; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingTestContext; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeListeningException; - -public class BindingDOMDataTreeListenerAdapterTest { - - private BindingDOMDataTreeListenerAdapter bindingDOMDataTreeListenerAdapter; - - @Mock - private DataTreeListener delegate; - - @Before - public void setUp() throws Exception { - initMocks(this); - final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); - testFactory.setExecutor(MoreExecutors.newDirectExecutorService()); - final BindingTestContext testContext = testFactory.getTestContext(); - testContext.start(); - - bindingDOMDataTreeListenerAdapter = - new BindingDOMDataTreeListenerAdapter(delegate, testContext.getCodec(), LogicalDatastoreType.OPERATIONAL); - } - - @Test - public void onDataTreeChanged() throws Exception { - bindingDOMDataTreeListenerAdapter.onDataTreeChanged(ImmutableSet.of(), ImmutableMap.of()); - verify(delegate).onDataTreeChanged(any(), any()); - } - - @Test - public void onDataTreeFailedTest() throws Exception { - bindingDOMDataTreeListenerAdapter.onDataTreeFailed(ImmutableSet.of(new DOMDataTreeListeningException("test"))); - verify(delegate).onDataTreeFailed(any()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapterTest.java deleted file mode 100644 index 821bac65ec..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeProducerAdapterTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducerException; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingBrokerTestFactory; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingTestContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCursorAwareTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerBusyException; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducerException; - -public class BindingDOMDataTreeProducerAdapterTest { - - private BindingDOMDataTreeProducerAdapter bindingDOMDataTreeProducerAdapter; - private BindingToNormalizedNodeCodec codec; - - @Mock - private DOMDataTreeProducer delegate; - - @Before - public void setUp() throws Exception { - initMocks(this); - final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); - testFactory.setExecutor(MoreExecutors.newDirectExecutorService()); - final BindingTestContext testContext = testFactory.getTestContext(); - testContext.start(); - codec = testContext.getCodec(); - bindingDOMDataTreeProducerAdapter = - (BindingDOMDataTreeProducerAdapter) BindingDOMDataTreeProducerAdapter.create(delegate, codec); - } - - @Test - public void createTransactionTest() throws Exception { - doReturn(mock(DOMDataTreeCursorAwareTransaction.class)).when(delegate).createTransaction(true); - assertNotNull(bindingDOMDataTreeProducerAdapter.createTransaction(true)); - verify(delegate).createTransaction(true); - } - - @Test - public void createTest() throws Exception { - assertNotNull(BindingDOMDataTreeProducerAdapter.create(delegate, codec)); - } - - @Test - public void createProducerTest() throws Exception { - doReturn(mock(DOMDataTreeProducer.class)).when(delegate).createProducer(any()); - assertNotNull(bindingDOMDataTreeProducerAdapter.createProducer(ImmutableSet.of())); - verify(delegate).createProducer(any()); - } - - @Test - public void closeTest() throws Exception { - reset(delegate); - bindingDOMDataTreeProducerAdapter.close(); - verify(delegate).close(); - } - - @Test(expected = DataTreeProducerException.class) - public void closeTestWithException1() throws Exception { - doThrow(new DOMDataTreeProducerBusyException("test")).when(delegate).close(); - bindingDOMDataTreeProducerAdapter.close(); - } - - @Test(expected = DataTreeProducerException.class) - public void closeTestWithException2() throws Exception { - doThrow(new DOMDataTreeProducerException("test")).when(delegate).close(); - bindingDOMDataTreeProducerAdapter.close(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapterTest.java deleted file mode 100644 index 45dc5fbbbb..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeServiceAdapterTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingBrokerTestFactory; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingTestContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMDataTreeProducer; -import org.opendaylight.mdsal.dom.api.DOMDataTreeService; - -public class BindingDOMDataTreeServiceAdapterTest { - - private BindingDOMDataTreeServiceAdapter bindingDOMDataTreeServiceAdapter; - private BindingToNormalizedNodeCodec codec; - - @Mock - private DOMDataTreeService delegate; - - @Before - public void setUp() throws Exception { - initMocks(this); - final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); - testFactory.setExecutor(MoreExecutors.newDirectExecutorService()); - final BindingTestContext testContext = testFactory.getTestContext(); - testContext.start(); - codec = testContext.getCodec(); - bindingDOMDataTreeServiceAdapter = BindingDOMDataTreeServiceAdapter.create(delegate, codec); - } - - @Test - public void createProducerTest() throws Exception { - doReturn(mock(DOMDataTreeProducer.class)).when(delegate).createProducer(any()); - assertNotNull(bindingDOMDataTreeServiceAdapter.createProducer(ImmutableSet.of())); - verify(delegate).createProducer(any()); - } - - @Test(expected = UnsupportedOperationException.class) - public void registerListenerTest() throws Exception { - bindingDOMDataTreeServiceAdapter.registerListener(mock(DataTreeListener.class), ImmutableSet.of(), false, - ImmutableSet.of()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapterTest.java deleted file mode 100644 index c1e38c293f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/data/tree/BindingDOMDataTreeWriteCursorAdapterTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.tree; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import com.google.common.collect.ImmutableList; -import java.lang.reflect.Field; -import java.util.AbstractMap.SimpleEntry; -import java.util.Deque; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteCursor; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -public class BindingDOMDataTreeWriteCursorAdapterTest { - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Test - public void basicTest() throws Exception { - final DataTreeIdentifier identifier = - DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, - InstanceIdentifier.create(TreeNode.class)); - final DOMDataTreeWriteCursor delegate = mock(DOMDataTreeWriteCursor.class); - final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = - new BindingToNormalizedNodeCodec( - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), - registry); - final BindingDOMDataTreeWriteCursorAdapter adapter = - new BindingDOMDataTreeWriteCursorAdapter<>(identifier, delegate, codec); - - final TreeArgument pathArgument = new Item<>(TreeNode.class); - final TreeNode data = mock(TreeNode.class); - - adapter.enter(pathArgument, pathArgument); - adapter.enter(ImmutableList.of(pathArgument)); - - doNothing().when(delegate).write(any(), any()); - doNothing().when(delegate).merge(any(), any()); - doNothing().when(delegate).delete(any()); - doReturn(YangInstanceIdentifier.EMPTY).when(registry).toYangInstanceIdentifier(any()); - doNothing().when(delegate).close(); - final NormalizedNode normalizedNode = mock(NormalizedNode.class); - - doReturn(new SimpleEntry>(YangInstanceIdentifier.EMPTY, - normalizedNode)).when(registry).toNormalizedNode(any(), any()); - adapter.write(pathArgument, data); - verify(delegate).write(any(), any()); - - adapter.merge(pathArgument, data); - verify(delegate).merge(any(), any()); - - adapter.delete(pathArgument); - verify(delegate).delete(any()); - - final Field stackField = BindingDOMDataTreeWriteCursorAdapter.class.getDeclaredField("stack"); - stackField.setAccessible(true); - final Deque stack = (Deque) stackField.get(adapter); - assertTrue(stack.contains(pathArgument)); - - adapter.exit(stack.size()); - assertFalse(stack.contains(pathArgument)); - - adapter.close(); - verify(delegate).close(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapterTest.java deleted file mode 100644 index 30033b84e9..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointListenerAdapterTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.util.concurrent.MoreExecutors; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.MountPointListener; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingBrokerTestFactory; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingTestContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.dom.api.DOMMountPointService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - -public class BindingDOMMountPointListenerAdapterTest { - - private BindingDOMMountPointListenerAdapter bindingDOMMountPointListenerAdapter; - private BindingToNormalizedNodeCodec codec; - - @Mock private MountPointListener listener; - @Mock private DOMMountPointService mountPointService; - @Mock private ListenerRegistration listenerRegistration; - - @Before - public void setUp() throws Exception { - initMocks(this); - final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); - testFactory.setExecutor(MoreExecutors.newDirectExecutorService()); - final BindingTestContext testContext = testFactory.getTestContext(); - testContext.start(); - codec = testContext.getCodec(); - doReturn(listenerRegistration).when(mountPointService).registerProvisionListener(any()); - bindingDOMMountPointListenerAdapter = - new BindingDOMMountPointListenerAdapter<>(listener, codec, mountPointService); - } - - @Test - public void basicTest() throws Exception { - assertEquals(listener, bindingDOMMountPointListenerAdapter.getInstance()); - bindingDOMMountPointListenerAdapter.close(); - verify(listenerRegistration).close(); - } - - @Test - public void onMountPointCreatedWithExceptionTest() throws Exception { - reset(listener); - bindingDOMMountPointListenerAdapter.onMountPointCreated(YangInstanceIdentifier.EMPTY); - verifyZeroInteractions(listener); - } - - @Test - public void onMountPointRemovedWithExceptionTest() throws Exception { - reset(listener); - bindingDOMMountPointListenerAdapter.onMountPointRemoved(YangInstanceIdentifier.EMPTY); - verifyZeroInteractions(listener); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapterTest.java deleted file mode 100644 index 97f9c31379..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingDOMMountPointServiceAdapterTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import java.util.Optional; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.MountPointListener; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMMountPoint; -import org.opendaylight.mdsal.dom.api.DOMMountPointService; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - -public class BindingDOMMountPointServiceAdapterTest { - - @Test - public void basicTest() throws Exception { - final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = - new BindingToNormalizedNodeCodec((GeneratedClassLoadingStrategy) - GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), registry); - doReturn(YangInstanceIdentifier.EMPTY).when(registry).toYangInstanceIdentifier(any()); - final DOMMountPointService mountPointService = mock(DOMMountPointService.class); - - final BindingDOMMountPointServiceAdapter adapter = - new BindingDOMMountPointServiceAdapter(mountPointService, codec); - - doReturn(Optional.empty()).when(mountPointService).getMountPoint(any()); - assertFalse(adapter.getMountPoint(InstanceIdentifier.create(TreeNode.class)).isPresent()); - - doReturn(Optional.of(mock(DOMMountPoint.class))).when(mountPointService).getMountPoint(any()); - assertTrue(adapter.getMountPoint(InstanceIdentifier.create(TreeNode.class)).isPresent()); - - assertNotNull(adapter.registerListener(InstanceIdentifier.create(TreeNode.class), - mock(MountPointListener.class))); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapterTest.java deleted file mode 100644 index 6a87080a11..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/mountpoint/BindingMountPointAdapterTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint; - -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.dom.api.DOMMountPoint; - -public class BindingMountPointAdapterTest { - - @Test - public void basicTest() throws Exception { - final GeneratedClassLoadingStrategy loading = (GeneratedClassLoadingStrategy) getTCCLClassLoadingStrategy(); - final BindingNormalizedNodeCodecRegistry codecRegistry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = new BindingToNormalizedNodeCodec(loading, codecRegistry); - final DOMMountPoint domMountPoint = mock(DOMMountPoint.class); - final BindingMountPointAdapter bindingMountPointAdapter = new BindingMountPointAdapter(codec, domMountPoint); - assertNull(bindingMountPointAdapter.getIdentifier()); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationAdapterTest.java deleted file mode 100644 index f6490fe45c..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/impl/operation/BindingDOMOperationAdapterTest.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.common.collect.ImmutableSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingBrokerTestFactory; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.test.BindingTestContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMActionNotAvailableException; -import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.TestOperationServiceInContAction; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.TestOperationServiceMyRpcRpc; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.data.MyCont; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.data.my_cont.in_cont.InContInput; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.data.my_cont.in_cont.InContOutput; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.data.my_rpc.MyRpcInput; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.data.my_rpc.MyRpcOutput; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.dto.my_cont.in_cont.InContInputBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.dto.my_cont.in_cont.InContOutputBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.dto.my_rpc.MyRpcInputBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.test.operation.rev170621.dto.my_rpc.MyRpcOutputBuilder; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - - -public class BindingDOMOperationAdapterTest { - private static final MyRpcOutput RPC_OUTPUT = new MyRpcOutputBuilder().setRpcOutputLeaf("rpc_output_leaf").build(); - private static final InContOutput ACTION_OUTPUT = - new InContOutputBuilder().setOutputLeaf("action_output_leaf").build(); - private BindingDOMOperationProviderServiceAdapter adapter; - private BindingDOMOperationServiceAdapter serviceAdapter; - - @Before - public void setUp() throws Exception { - final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory(); - testFactory.setExecutor(Executors.newCachedThreadPool()); - - final BindingTestContext testContext = testFactory.getTestContext(); - testContext.start(); - - this.adapter = new BindingDOMOperationProviderServiceAdapter(testContext.getDomRpcRegistry(), - testContext.getDomActionRegistry(), testContext.getCodec()); - - this.serviceAdapter = new BindingDOMOperationServiceAdapter(testContext.getDomRpcInvoker(), - testContext.getDomActionService(), testContext.getCodec()); - } - - @Test - public void actionTest() throws Exception { - final CountDownLatch invokeLatch = new CountDownLatch(1); - final ObjectRegistration registration = adapter.registerActionImplementation( - TestOperationServiceInContAction.class, new TestActionImpl(), LogicalDatastoreType.OPERATIONAL, - ImmutableSet.of( - DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(MyCont.class)))); - assertNotNull(registration); - - final TestOperationServiceInContAction action = - serviceAdapter.getActionService(TestOperationServiceInContAction.class); - assertNotNull(action); - - action.invoke(new InContInputBuilder().setInputLeaf("in").build(), - InstanceIdentifier.create(MyCont.class), - new RpcCallback() { - @Override - public void onSuccess(InContOutput output) { - assertEquals(ACTION_OUTPUT, output); - invokeLatch.countDown(); - } - - @Override - public void onFailure(Throwable cause) { - assertNotNull(cause); - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - @Test - public void actionFailedTest() throws Exception { - - final CountDownLatch invokeLatch = new CountDownLatch(1); - - final ObjectRegistration registration = adapter.registerActionImplementation( - TestOperationServiceInContAction.class, new TestActionFailedImpl(), LogicalDatastoreType.OPERATIONAL, - ImmutableSet.of(DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, - InstanceIdentifier.create(MyCont.class)))); - assertNotNull(registration); - - final TestOperationServiceInContAction action = - serviceAdapter.getActionService(TestOperationServiceInContAction.class); - assertNotNull(action); - - action.invoke(new InContInputBuilder().setInputLeaf("in").build(), - InstanceIdentifier.create(MyCont.class), - new RpcCallback() { - @Override - public void onSuccess(InContOutput output) { - - } - - @Override - public void onFailure(Throwable cause) { - assertTrue(cause instanceof RuntimeException); - assertEquals(cause.getMessage(), "TestActionFailedImpl invoke failed."); - invokeLatch.countDown(); - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - @Test - public void actionNotAvaliableTest() throws Exception { - - final CountDownLatch invokeLatch = new CountDownLatch(1); - - final TestOperationServiceInContAction action = - serviceAdapter.getActionService(TestOperationServiceInContAction.class); - assertNotNull(action); - - action.invoke(new InContInputBuilder().setInputLeaf("in").build(), - InstanceIdentifier.create(MyCont.class), - new RpcCallback() { - @Override - public void onSuccess(InContOutput output) { - - } - - @Override - public void onFailure(Throwable cause) { - assertTrue(cause instanceof DOMActionNotAvailableException); - invokeLatch.countDown(); - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - @Test - public void rpcTest() throws Exception { - final CountDownLatch invokeLatch = new CountDownLatch(1); - - assertNotNull(adapter.registerRpcImplementation(TestOperationServiceMyRpcRpc.class, - new TestRpcImpl())); - final TestOperationServiceMyRpcRpc rpc = - serviceAdapter.getRpcService(TestOperationServiceMyRpcRpc.class); - assertNotNull(rpc); - - rpc.invoke(new MyRpcInputBuilder().setRpcInputLeaf("123").build(), - new RpcCallback() { - @Override - public void onSuccess(MyRpcOutput output) { - assertEquals(RPC_OUTPUT, output); - invokeLatch.countDown(); - } - - @Override - public void onFailure(Throwable cause) { - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - @Test - public void rpcFailedTest() throws Exception { - - final CountDownLatch invokeLatch = new CountDownLatch(1); - - assertNotNull(adapter.registerRpcImplementation(TestOperationServiceMyRpcRpc.class, - new TestRpcFailedImpl())); - final TestOperationServiceMyRpcRpc rpc = - serviceAdapter.getRpcService(TestOperationServiceMyRpcRpc.class); - assertNotNull(rpc); - - rpc.invoke(new MyRpcInputBuilder().setRpcInputLeaf("123").build(), - new RpcCallback() { - @Override - public void onSuccess(MyRpcOutput output) { - - } - - @Override - public void onFailure(Throwable cause) { - assertTrue(cause instanceof RuntimeException); - assertEquals(cause.getMessage(), "TestRpcFailedImpl invoke failed."); - invokeLatch.countDown(); - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - @Test - public void rpcNotAvaliableTest() throws Exception { - final CountDownLatch invokeLatch = new CountDownLatch(1); - - final TestOperationServiceMyRpcRpc rpc = - serviceAdapter.getRpcService(TestOperationServiceMyRpcRpc.class); - assertNotNull(rpc); - - rpc.invoke(new MyRpcInputBuilder().setRpcInputLeaf("123").build(), - new RpcCallback() { - @Override - public void onSuccess(MyRpcOutput output) { - - } - - @Override - public void onFailure(Throwable cause) { - assertTrue(cause instanceof DOMRpcImplementationNotAvailableException); - invokeLatch.countDown(); - } - }); - assertEquals("Invoke complete", true, invokeLatch.await(5, TimeUnit.SECONDS)); - } - - private class TestRpcImpl implements TestOperationServiceMyRpcRpc { - - @Override - public void invoke(MyRpcInput input, RpcCallback callback) { - callback.onSuccess(RPC_OUTPUT); - } - } - - private class TestRpcFailedImpl implements TestOperationServiceMyRpcRpc { - - @Override - public void invoke(MyRpcInput input, RpcCallback callback) { - callback.onFailure(new RuntimeException("TestRpcFailedImpl invoke failed.")); - } - } - - private class TestActionImpl implements TestOperationServiceInContAction { - - @Override - public void invoke(InContInput input, InstanceIdentifier ii, RpcCallback callback) { - callback.onSuccess(ACTION_OUTPUT); - } - } - - private class TestActionFailedImpl implements TestOperationServiceInContAction { - - @Override - public void invoke(InContInput input, InstanceIdentifier ii, RpcCallback callback) { - callback.onFailure(new RuntimeException("TestActionFailedImpl invoke failed.")); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilderTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilderTest.java deleted file mode 100644 index f61d92d5f4..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/builder/AdapterBuilderTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.builder; - -import static org.junit.Assert.assertTrue; - -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.MutableClassToInstanceMap; -import java.util.Map; -import java.util.Set; -import org.junit.Test; - -public class AdapterBuilderTest extends AdapterBuilder { - - private static final ClassToInstanceMap DELEGATES = MutableClassToInstanceMap.create(); - - @Test - public void buildTest() throws Exception { - this.addDelegate(String.class, "test"); - DELEGATES.putAll((Map) this.build()); - assertTrue(DELEGATES.containsValue("test")); - this.addDelegate(Object.class, "test2"); - DELEGATES.putAll((Map) this.build()); - assertTrue(DELEGATES.containsValue("test")); - assertTrue(DELEGATES.get(Object.class).equals("test2")); - } - - @Override - public Set getRequiredDelegates() { - return DELEGATES.keySet(); - } - - @Override - protected Object createInstance(ClassToInstanceMap delegates) { - return delegates; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoaderTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoaderTest.java deleted file mode 100644 index e9beef1133..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/spi/loader/BindingDOMAdapterLoaderTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.loader; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.collect.ImmutableClassToInstanceMap; -import javax.annotation.Nullable; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.BindingDOMDataBrokerAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMService; - -public class BindingDOMAdapterLoaderTest { - - @Mock - private DOMDataBroker domService; - - @Mock - private BindingNormalizedNodeCodecRegistry mockCodecRegistry; - - private BindingDOMAdapterLoader bindingDOMAdapterLoader; - private BindingDOMDataBrokerAdapter bindingDOMDataBrokerAdapter; - - @Before - public void setUp() throws Exception { - initMocks(this); - doReturn(ImmutableClassToInstanceMap.of()).when(domService).getExtensions(); - - bindingDOMAdapterLoader = new BindingDOMAdapterLoader( - new BindingToNormalizedNodeCodec((GeneratedClassLoadingStrategy) - GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), mockCodecRegistry)) { - @Nullable - @Override - protected DOMService getDelegate(Class reqDeleg) { - return domService; - } - }; - } - - @Test - public void createBuilderTest() throws Exception { - assertTrue(bindingDOMAdapterLoader.load(DataBroker.class).get() instanceof BindingDOMDataBrokerAdapter); - domService = null; - assertFalse(bindingDOMAdapterLoader.load(DataBroker.class).isPresent()); - } - - @Test - public void createChainTest() throws Exception { - bindingDOMDataBrokerAdapter - = (BindingDOMDataBrokerAdapter) bindingDOMAdapterLoader.load(DataBroker.class).get(); - assertNotNull(bindingDOMDataBrokerAdapter.createTransactionChain(null)); - } - - @Test(expected = UnsupportedOperationException.class) - public void registerWithException() throws Exception { - bindingDOMDataBrokerAdapter - = (BindingDOMDataBrokerAdapter) bindingDOMAdapterLoader.load(DataBroker.class).get(); - bindingDOMDataBrokerAdapter.registerListener(null,null, false, null); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractDataBrokerTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractDataBrokerTest.java deleted file mode 100644 index 21b4657649..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractDataBrokerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public class AbstractDataBrokerTest extends AbstractSchemaAwareTest { - - private DataBrokerTestCustomizer testCustomizer; - private DataBroker dataBroker; - private DOMDataBroker domBroker; - - @Override - protected void setupWithSchema(final SchemaContext context) { - testCustomizer = createDataBrokerTestCustomizer(); - dataBroker = testCustomizer.createDataBroker(); - domBroker = testCustomizer.createDOMDataBroker(); - testCustomizer.updateSchema(context); - setupWithDataBroker(dataBroker); - } - - protected void setupWithDataBroker(final DataBroker broker) { - // Intentionally left No-op, subclasses may customize it - } - - protected DataBrokerTestCustomizer createDataBrokerTestCustomizer() { - return new DataBrokerTestCustomizer(); - } - - public DataBroker getDataBroker() { - return dataBroker; - } - - public DOMDataBroker getDomBroker() { - return domBroker; - } - - protected static final void assertCommit(final ListenableFuture commit) { - try { - commit.get(500, TimeUnit.MILLISECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - throw new IllegalStateException(e); - } - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractSchemaAwareTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractSchemaAwareTest.java deleted file mode 100644 index 814b75f2ce..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/AbstractSchemaAwareTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import com.google.common.annotations.Beta; -import org.junit.Before; -import org.opendaylight.mdsal.binding.javav2.runtime.context.ModuleInfoBackedContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public abstract class AbstractSchemaAwareTest { - - private Iterable moduleInfos; - private SchemaContext schemaContext; - - protected Iterable getModuleInfos() throws Exception { - return BindingReflections.loadModuleInfos(); - } - - @Before - public final void setup() throws Exception { - moduleInfos = getModuleInfos(); - final ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create(); - moduleContext.addModuleInfos(moduleInfos); - schemaContext = moduleContext.tryToCreateSchemaContext().get(); - setupWithSchema(schemaContext); - } - - /** - * Setups test with Schema context. - * - * @param context - * schema context - */ - protected abstract void setupWithSchema(SchemaContext context); -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BasicLeafValueTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BasicLeafValueTest.java deleted file mode 100644 index bea6d4f5cd..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BasicLeafValueTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import java.util.concurrent.ExecutionException; -import org.junit.Ignore; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.gen.javav2.urn.test.rev170627.data.MyCont; -import org.opendaylight.mdsal.gen.javav2.urn.test.rev170627.dto.MyContBuilder; - -public class BasicLeafValueTest extends AbstractDataBrokerTest { - - private static final InstanceIdentifier MY_CONT_NODE_PATH - = InstanceIdentifier.create(MyCont.class); - - @Ignore - @Test - public void testMyContLeafNode() throws InterruptedException, ExecutionException { - final WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - final MyContBuilder hello = new MyContBuilder().setMyLeaf("hello"); - writeTx.put(LogicalDatastoreType.OPERATIONAL, MY_CONT_NODE_PATH, hello.build()); - writeTx.commit().get(); - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingBrokerTestFactory.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingBrokerTestFactory.java deleted file mode 100644 index dac15569da..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingBrokerTestFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import java.util.concurrent.ExecutorService; -import javassist.ClassPool; - -@Beta -public class BindingBrokerTestFactory { - - private static final ClassPool CLASS_POOL = ClassPool.getDefault(); - private boolean startWithParsedSchema = true; - private ExecutorService executor; - private ClassPool classPool; - - public boolean isStartWithParsedSchema() { - return startWithParsedSchema; - } - - public void setStartWithParsedSchema(final boolean startWithParsedSchema) { - this.startWithParsedSchema = startWithParsedSchema; - } - - public ExecutorService getExecutor() { - return executor; - } - - public void setExecutor(final ExecutorService executor) { - this.executor = executor; - } - - public BindingTestContext getTestContext() { - Preconditions.checkState(executor != null, "Executor is not set."); - final ListeningExecutorService listenableExecutor = MoreExecutors.listeningDecorator(executor); - return new BindingTestContext(listenableExecutor, getClassPool(), startWithParsedSchema); - } - - public ClassPool getClassPool() { - if (classPool == null) { - return CLASS_POOL; - } - - return classPool; - } - - public void setClassPool(final ClassPool classPool) { - this.classPool = classPool; - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingTestContext.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingTestContext.java deleted file mode 100644 index 5c69781ce0..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/BindingTestContext.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import javassist.ClassPool; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.api.MountPointService; -import org.opendaylight.mdsal.binding.javav2.api.NotificationPublishService; -import org.opendaylight.mdsal.binding.javav2.api.NotificationService; -import org.opendaylight.mdsal.binding.javav2.api.RpcActionConsumerRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.BindingDOMDataBrokerAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.mountpoint.BindingDOMMountPointServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationPublishServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation.BindingDOMOperationProviderServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.operation.BindingDOMOperationServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api.TreeNodeSerializerGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.runtime.context.ModuleInfoBackedContext; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMActionProviderService; -import org.opendaylight.mdsal.dom.api.DOMActionService; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMMountPointService; -import org.opendaylight.mdsal.dom.api.DOMNotificationPublishService; -import org.opendaylight.mdsal.dom.api.DOMNotificationService; -import org.opendaylight.mdsal.dom.api.DOMRpcProviderService; -import org.opendaylight.mdsal.dom.api.DOMRpcService; -import org.opendaylight.mdsal.dom.broker.DOMMountPointServiceImpl; -import org.opendaylight.mdsal.dom.broker.DOMNotificationRouter; -import org.opendaylight.mdsal.dom.broker.DOMRpcRouter; -import org.opendaylight.mdsal.dom.broker.SerializedDOMDataBroker; -import org.opendaylight.mdsal.dom.spi.store.DOMStore; -import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public class BindingTestContext implements AutoCloseable { - - private final MockSchemaService mockSchemaService = new MockSchemaService(); - private final ListeningExecutorService executor; - private final ClassPool classPool; - private final boolean startWithSchema; - - private DOMMountPointService biMountImpl; - private BindingToNormalizedNodeCodec codec; - private ImmutableMap newDatastores; - private DOMDataBroker newDOMDataBroker; - private DataBroker dataBroker; - private RpcActionConsumerRegistry baConsumerRpc; - private BindingDOMOperationProviderServiceAdapter baProviderRpc; - private DOMRpcRouter domRouter; - private NotificationPublishService publishService; - private NotificationService listenService; - private DOMNotificationPublishService domPublishService; - private DOMNotificationService domListenService; - - public DOMDataBroker getDomAsyncDataBroker() { - return newDOMDataBroker; - } - - public BindingToNormalizedNodeCodec getCodec() { - return codec; - } - - protected BindingTestContext(final ListeningExecutorService executor, final ClassPool classPool, - final boolean startWithSchema) { - this.executor = executor; - this.classPool = classPool; - this.startWithSchema = startWithSchema; - } - - public void startDomDataBroker() { - } - - public void startNewDataBroker() { - checkState(executor != null, "Executor needs to be set"); - checkState(newDOMDataBroker != null, "DOM Data Broker must be set"); - dataBroker = new BindingDOMDataBrokerAdapter(newDOMDataBroker, codec); - } - - public void startNewDomDataBroker() { - checkState(executor != null, "Executor needs to be set"); - final InMemoryDOMDataStore operStore = - new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService()); - final InMemoryDOMDataStore configStore = - new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService()); - newDatastores = - ImmutableMap.builder().put(LogicalDatastoreType.OPERATIONAL, operStore) - .put(LogicalDatastoreType.CONFIGURATION, configStore).build(); - - newDOMDataBroker = new SerializedDOMDataBroker(newDatastores, executor); - - mockSchemaService.registerSchemaContextListener(configStore); - mockSchemaService.registerSchemaContextListener(operStore); - } - - public void startBindingDataBroker() { - - } - - public void startBindingBroker() { - checkState(executor != null, "Executor needs to be set"); - - baConsumerRpc = new BindingDOMOperationServiceAdapter(getDomRpcInvoker(), getDomActionService(), codec); - baProviderRpc = new BindingDOMOperationProviderServiceAdapter(getDomRpcRegistry(), getDomActionRegistry(), - codec); - final MountPointService mountService = new BindingDOMMountPointServiceAdapter(biMountImpl, codec); - } - - public void startForwarding() { - - } - - public void startBindingToDomMappingService() { - checkState(classPool != null, "ClassPool needs to be present"); - - final TreeNodeSerializerGenerator generator = - StreamWriterGenerator.create(JavassistUtils.forClassPool(classPool)); - final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator); - final GeneratedClassLoadingStrategy loading = - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(); - codec = new BindingToNormalizedNodeCodec(loading, codecRegistry); - mockSchemaService.registerSchemaContextListener(codec); - } - - private void updateYangSchema(final ImmutableSet moduleInfos) { - mockSchemaService.changeSchema(getContext(moduleInfos)); - } - - private static SchemaContext getContext(final ImmutableSet moduleInfos) { - final ModuleInfoBackedContext ctx = ModuleInfoBackedContext.create(); - ctx.addModuleInfos(moduleInfos); - return ctx.tryToCreateSchemaContext().get(); - } - - public SchemaContext getContext() { - return mockSchemaService.getSchemaContext(); - } - - public void start() { - startNewDomDataBroker(); - - startDomBroker(); - startDomMountPoint(); - startBindingToDomMappingService(); - startNewDataBroker(); - startBindingNotificationBroker(); - startBindingBroker(); - - startForwarding(); - if (startWithSchema) { - loadYangSchemaFromClasspath(); - } - } - - private void startDomMountPoint() { - biMountImpl = new DOMMountPointServiceImpl(); - } - - private void startDomBroker() { - checkState(executor != null); - domRouter = new DOMRpcRouter(); - mockSchemaService.registerSchemaContextListener(domRouter); - } - - public void startBindingNotificationBroker() { - checkState(executor != null); - final DOMNotificationRouter router = DOMNotificationRouter.create(16); - domPublishService = router; - domListenService = router; - publishService = new BindingDOMNotificationPublishServiceAdapter(codec, domPublishService); - listenService = new BindingDOMNotificationServiceAdapter(codec, domListenService); - - } - - public void loadYangSchemaFromClasspath() { - final ImmutableSet moduleInfos = BindingReflections.loadModuleInfos(); - updateYangSchema(moduleInfos); - } - - public DOMRpcProviderService getDomRpcRegistry() { - return domRouter.getRpcProviderService(); - } - - public DOMActionProviderService getDomActionRegistry() { - return domRouter.getActionProviderService(); - } - - public DOMRpcService getDomRpcInvoker() { - return domRouter.getRpcService(); - } - - public DOMActionService getDomActionService() { - return domRouter.getActionService(); - } - - @Override - public void close() throws Exception { - - } - - public DOMMountPointService getDomMountProviderService() { - return biMountImpl; - } - - public DataBroker getDataBroker() { - return dataBroker; - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/DataBrokerTestCustomizer.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/DataBrokerTestCustomizer.java deleted file mode 100644 index 509bc86a0b..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/DataBrokerTestCustomizer.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMap; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import javassist.ClassPool; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.api.NotificationPublishService; -import org.opendaylight.mdsal.binding.javav2.api.NotificationService; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.BindingDOMDataBrokerAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationPublishServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.notification.BindingDOMNotificationServiceAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api.TreeNodeSerializerGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMSchemaService; -import org.opendaylight.mdsal.dom.broker.DOMNotificationRouter; -import org.opendaylight.mdsal.dom.broker.SerializedDOMDataBroker; -import org.opendaylight.mdsal.dom.spi.store.DOMStore; -import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public class DataBrokerTestCustomizer { - - private DOMDataBroker domDataBroker; - private final DOMNotificationRouter domNotificationRouter; - private final MockSchemaService schemaService; - private ImmutableMap datastores; - private final BindingToNormalizedNodeCodec bindingToNormalized; - - public ImmutableMap createDatastores() { - return ImmutableMap.builder() - .put(LogicalDatastoreType.OPERATIONAL, createOperationalDatastore()) - .put(LogicalDatastoreType.CONFIGURATION, createConfigurationDatastore()).build(); - } - - public DataBrokerTestCustomizer() { - schemaService = new MockSchemaService(); - final ClassPool pool = ClassPool.getDefault(); - final TreeNodeSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool)); - final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator); - final GeneratedClassLoadingStrategy loading = - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(); - bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry); - schemaService.registerSchemaContextListener(bindingToNormalized); - domNotificationRouter = DOMNotificationRouter.create(16); - } - - public DOMStore createConfigurationDatastore() { - final InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService()); - schemaService.registerSchemaContextListener(store); - return store; - } - - public DOMStore createOperationalDatastore() { - final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService()); - schemaService.registerSchemaContextListener(store); - return store; - } - - public DOMDataBroker createDOMDataBroker() { - return new SerializedDOMDataBroker(getDatastores(), getCommitCoordinatorExecutor()); - } - - public NotificationService createNotificationService() { - return new BindingDOMNotificationServiceAdapter(bindingToNormalized.getCodecRegistry(), domNotificationRouter); - } - - public NotificationPublishService createNotificationPublishService() { - return new BindingDOMNotificationPublishServiceAdapter(bindingToNormalized, domNotificationRouter); - } - - public ListeningExecutorService getCommitCoordinatorExecutor() { - return MoreExecutors.newDirectExecutorService(); - } - - public DataBroker createDataBroker() { - return new BindingDOMDataBrokerAdapter(getDOMDataBroker(), bindingToNormalized); - } - - public BindingToNormalizedNodeCodec getBindingToNormalized() { - return bindingToNormalized; - } - - public DOMSchemaService getSchemaService() { - return schemaService; - } - - private DOMDataBroker getDOMDataBroker() { - if (domDataBroker == null) { - domDataBroker = createDOMDataBroker(); - } - return domDataBroker; - } - - private synchronized ImmutableMap getDatastores() { - if (datastores == null) { - datastores = createDatastores(); - } - return datastores; - } - - public void updateSchema(final SchemaContext ctx) { - schemaService.changeSchema(ctx); - } - - public DOMNotificationRouter getDomNotificationRouter() { - return domNotificationRouter; - } -} diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/MockSchemaService.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/MockSchemaService.java deleted file mode 100644 index 2b65bfa4c3..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/test/MockSchemaService.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.test; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.ImmutableClassToInstanceMap; -import org.opendaylight.mdsal.dom.api.DOMSchemaService; -import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.util.ListenerRegistry; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; -import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; - -@Beta -public final class MockSchemaService implements DOMSchemaService, SchemaContextProvider { - - private SchemaContext schemaContext; - - ListenerRegistry listeners = ListenerRegistry.create(); - - @Override - public synchronized SchemaContext getGlobalContext() { - return schemaContext; - } - - @Override - public synchronized SchemaContext getSessionContext() { - return schemaContext; - } - - @Override - public ListenerRegistration - registerSchemaContextListener(final SchemaContextListener listener) { - return listeners.register(listener); - } - - @Override - public synchronized SchemaContext getSchemaContext() { - return schemaContext; - } - - @Override - public ClassToInstanceMap getExtensions() { - return ImmutableClassToInstanceMap.of(); - } - - public synchronized void changeSchema(final SchemaContext newContext) { - schemaContext = newContext; - for (final ListenerRegistration listener : listeners) { - listener.getInstance().onGlobalContextUpdated(schemaContext); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/transaction/BindingDOMTransactionChainAdapterTest.java b/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/transaction/BindingDOMTransactionChainAdapterTest.java deleted file mode 100644 index 950819769f..0000000000 --- a/binding2/mdsal-binding2-dom-adapter/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/adapter/transaction/BindingDOMTransactionChainAdapterTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.adapter.transaction; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -import com.google.common.collect.ImmutableClassToInstanceMap; -import javax.annotation.Nullable; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.data.BindingDOMDataBrokerAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.impl.transaction.BindingDOMTransactionChainAdapter; -import org.opendaylight.mdsal.binding.javav2.dom.adapter.spi.loader.BindingDOMAdapterLoader; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.dom.api.DOMDataBroker; -import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction; -import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction; -import org.opendaylight.mdsal.dom.api.DOMService; -import org.opendaylight.mdsal.dom.api.DOMTransactionChain; - -public class BindingDOMTransactionChainAdapterTest { - - @Mock - private DOMDataBroker domService; - - @Mock - private DOMTransactionChain transactionChain; - - @Mock - private BindingNormalizedNodeCodecRegistry mockCodecRegistry; - - private BindingDOMTransactionChainAdapter bindingDOMTransactionChainAdapter; - - @Before - public void setUp() throws Exception { - initMocks(this); - doReturn(transactionChain).when(domService).createTransactionChain(any()); - doReturn(ImmutableClassToInstanceMap.of()).when(domService).getExtensions(); - BindingDOMAdapterLoader bindingDOMAdapterLoader = new BindingDOMAdapterLoader( - new BindingToNormalizedNodeCodec((GeneratedClassLoadingStrategy) - GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), mockCodecRegistry)) { - @Nullable - @Override - protected DOMService getDelegate(final Class reqDeleg) { - return domService; - } - }; - - BindingDOMDataBrokerAdapter bindingDOMDataBrokerAdapter = - (BindingDOMDataBrokerAdapter) bindingDOMAdapterLoader.load(DataBroker.class).get(); - bindingDOMTransactionChainAdapter = - (BindingDOMTransactionChainAdapter) bindingDOMDataBrokerAdapter.createTransactionChain(null); - assertNotNull(bindingDOMTransactionChainAdapter.getDelegate()); - doNothing().when(transactionChain).close(); - bindingDOMTransactionChainAdapter.close(); - verify(transactionChain).close(); - } - - @Test - public void readTransactionTest() throws Exception { - doReturn(mock(DOMDataTreeReadTransaction.class)).when(transactionChain).newReadOnlyTransaction(); - assertNotNull(bindingDOMTransactionChainAdapter.newReadOnlyTransaction()); - } - - @Test - public void writeTransactionTest() throws Exception { - doReturn(mock(DOMDataTreeWriteTransaction.class)).when(transactionChain).newWriteOnlyTransaction(); - assertNotNull(bindingDOMTransactionChainAdapter.newWriteOnlyTransaction()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/pom.xml b/binding2/mdsal-binding2-dom-codec/pom.xml deleted file mode 100644 index ecc55baefc..0000000000 --- a/binding2/mdsal-binding2-dom-codec/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-dom-codec - 0.16.0-SNAPSHOT - bundle - - - - org.javassist - javassist - - - org.opendaylight.mdsal - mdsal-binding2-api - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - - - org.opendaylight.mdsal - mdsal-binding2-runtime - - - org.opendaylight.yangtools - yang-data-impl - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - - - org.opendaylight.mdsal - mdsal-binding2-test-model - test - - - org.opendaylight.mdsal - mdsal-dom-api - - - org.apache.commons - commons-lang3 - - - com.google.guava - guava - - - org.opendaylight.yangtools - mockito-configuration - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.groupId}.${project.artifactId} - - org.opendaylight.mdsal.binding2.dom.codec.*, - org.opendaylight.yangtools.binding.data.codec.*, - org.opendaylight.yangtools.binding.data.codec.gen.impl.*, - org.opendaylight.yangtools.binding.data.codec.impl.*, - ;-split-package:=error - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/AugmentationReader.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/AugmentationReader.java deleted file mode 100644 index 4fc0bd3562..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/AugmentationReader.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api; - -import com.google.common.annotations.Beta; -import java.lang.reflect.InvocationHandler; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; - -/** - * Interface which should be implemented by proxy {@link InvocationHandler} to - * obtain augmentations from proxy implementations of {@link Augmentable} - * object. - * - *

- * If implemented proxy does not implement this interface, its augmentations are - * not properly serialized / deserialized. - */ -@Beta -public interface AugmentationReader { - - /** - * Get augmentations. - * - * @param obj - * - object implemented this interface - * @return augmentations - */ - Map>, Augmentation> getAugmentations(Object obj); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCachingCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCachingCodec.java deleted file mode 100644 index 60aa0dc1cc..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCachingCodec.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * 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 - * - Binding representation of data - */ -@Beta -public interface BindingNormalizedNodeCachingCodec - extends BindingNormalizedNodeCodec, 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 - void close(); -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCodec.java deleted file mode 100644 index b8c7e75143..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingNormalizedNodeCodec.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Codec providing serialization and deserializiation between Binding and - * NormalizedNode representation of data. - * - * - * @param - * - Binding representation of data - */ -@Beta -public interface BindingNormalizedNodeCodec { - - /** - * 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); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeCodec.java deleted file mode 100644 index 226fec66a6..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeCodec.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api; - -import com.google.common.annotations.Beta; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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 concrete set of YANG models, represented - * by SchemaContext and provides access to subtree specific serialization - * context. - */ -@Beta -public interface BindingTreeCodec { - - /** - * Get specific subtree serialization context by Binding path. - * - * @param path - * - {@link InstanceIdentifier} path - * @param data type - * @return subtree codec - */ - @Nullable - BindingTreeNodeCodec getSubtreeCodec(InstanceIdentifier path); - - /** - * Get specific subtree serialization context by DOM path. - * - * @param path - * - {@link YangInstanceIdentifier} path - * @return subtree codec - */ - @Nullable - BindingTreeNodeCodec getSubtreeCodec(YangInstanceIdentifier path); - - /** - * Get specific subtree serialization context by {@link SchemaPath} path. - * - * @param path - * - {@link SchemaPath} path - * @return specific subtree codec - */ - @Nullable - BindingTreeNodeCodec getSubtreeCodec(SchemaPath path); - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeNodeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeNodeCodec.java deleted file mode 100644 index 19e88915de..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/BindingTreeNodeCodec.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableCollection; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; - -/** - * Specific subtree codec to model subtree between Java Binding and DOM. - * - * @param - * - Binding representation of data - */ -@Beta -public interface BindingTreeNodeCodec extends BindingNormalizedNodeCodec { - - /** - * Returns binding class of interface which represents API of current schema - * node. - * - * @return interface which defines API of binding representation of data. - */ - @Nonnull - Class 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 - * @param data type - * @return context of child - * @throws IllegalArgumentException - * - if supplied child class is not valid in specified context - */ - @Nonnull - BindingTreeNodeCodec streamChild(@Nonnull 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). - * - * This method differs from {@link #streamChild(Class)}, that is less - * stricter for interfaces representing augmentation and cases, that may - * return {@link BindingTreeNodeCodec} even if augmentation interface - * containing same data was supplied and does not represent augmentation of - * this node. - * - * @param childClass - * - child class by Binding Stream navigation - * @param data type - * @return context of child or Optional.empty if supplied is not applicable - * in context - */ - Optional> possibleStreamChild(@Nonnull Class 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 - BindingTreeNodeCodec 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 - BindingTreeNodeCodec bindingPathArgumentChild(@Nonnull TreeArgument arg, - @Nullable List 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 which uses cache for serialization / deserialization - */ - @Nonnull - BindingNormalizedNodeCachingCodec - createCachingCodec(@Nonnull ImmutableCollection> cacheSpecifier); - - /** - * Writes data representing object to supplied stream. - * - * @param data - * - representing object - * @param writer - * - supplied stream - */ - void writeAsNormalizedNode(T data, NormalizedNodeStreamWriter writer); - - /** - * Serializes path argument for current node. - * - * @param arg - * - Binding Path Argument, may be null if Binding Instance - * Identifier does not have representation for current node (e.g. - * choice or case) - * @return Yang Path Argument, may be null if Yang Instance Identifier does - * not have representation for current node (e.g. case). - * @throws IllegalArgumentException - * - if supplied {@code arg} is not valid. - */ - @Nullable - YangInstanceIdentifier.PathArgument serializePathArgument(@Nullable TreeArgument arg); - - /** - * Deserializes path argument for current node. - * - * @param arg - * - Yang Path Argument, may be null if Yang Instance Identifier - * does not have representation for current node (e.g. case) - * @return Binding Path Argument, may be null if Binding Instance Identifier - * does not have representation for current node (e.g. choice or - * case) - * @throws IllegalArgumentException - * - if supplied {@code arg} is not valid. - */ - @Nullable - TreeArgument deserializePathArgument(@Nullable YangInstanceIdentifier.PathArgument arg); - - /** - * Return schema of node codec context. - * - * @return {@link Object} as schema of specific node context - */ - @Nonnull - Object getSchema(); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingNormalizedNodeWriterFactory.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingNormalizedNodeWriterFactory.java deleted file mode 100644 index 440750c279..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingNormalizedNodeWriterFactory.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory; - -import java.util.Map.Entry; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; - -/** - * Factory for {@link BindingStreamEventWriter}, which provides stream writers - * which translates data and delegates calls to - * {@link NormalizedNodeStreamWriter}. - * - */ -public interface BindingNormalizedNodeWriterFactory { - - /** - * Creates a {@link BindingStreamEventWriter} for data tree path which will - * translate to NormalizedNode model and invoke proper events on supplied - * {@link NormalizedNodeStreamWriter}. - * - *

- * Also provides translation of supplied Instance Identifier to - * {@link YangInstanceIdentifier} so client code, does not need to translate - * that separately. - * - *

- * If {@link YangInstanceIdentifier} is not needed, please use - * {@link #newWriter(InstanceIdentifier, NormalizedNodeStreamWriter)} method - * to conserve resources. - * - * @param path - * - Binding Path in conceptual data tree, for which writer - * should be instantiated - * @param domWriter - * - 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 newWriterAndIdentifier( - @Nonnull InstanceIdentifier path, @Nonnull NormalizedNodeStreamWriter domWriter); - - /** - * Creates a {@link BindingStreamEventWriter} for data tree path which will - * translate to NormalizedNode model and invoke proper events on supplied - * {@link NormalizedNodeStreamWriter}. - * - *

- * This variation does not provide YANG instance identifier and is useful - * for use-cases, where {@link InstanceIdentifier} translation is done in - * other way, or YANG instance identifier is unnecessary (e.g. - * notifications, operations). - * - * @param path - * - Binding Path in conceptual data tree, for which writer - * should be instantiated - * @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, - @Nonnull NormalizedNodeStreamWriter domWriter); - - /** - * Creates a {@link BindingStreamEventWriter} for operation data which will - * translate to NormalizedNode model and invoke proper events on supplied - * {@link NormalizedNodeStreamWriter}. - * - * @param operationInputOrOutput - * - binding class representing operation (RPC, Action) input or - * output, for which writer should be instantiated - * @param domWriter - * - stream writer on which events will be invoked - * @return {@link BindingStreamEventWriter} which will write to supplied - * {@link NormalizedNodeStreamWriter} - */ - @Nonnull - BindingStreamEventWriter newOperationWriter(@Nonnull Class> operationInputOrOutput, - @Nonnull NormalizedNodeStreamWriter domWriter); - - /** - * Creates a {@link BindingStreamEventWriter} for notification which will - * translate to NormalizedNode model and invoke proper events on supplied - * {@link NormalizedNodeStreamWriter}. - * - * @param notification - * - binding class representing notification, for which writer - * should be instantiated - * @param domWriter - * - stream writer on which events will be invoked - * @return {@link BindingStreamEventWriter} which will write to supplied - * {@link NormalizedNodeStreamWriter} - */ - @Nonnull - BindingStreamEventWriter newNotificationWriter(@Nonnull Class> notification, - @Nonnull NormalizedNodeStreamWriter domWriter); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingTreeCodecFactory.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingTreeCodecFactory.java deleted file mode 100644 index 3f0e47ca07..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/factory/BindingTreeCodecFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public interface BindingTreeCodecFactory { - - /** - * 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 - */ - BindingTreeCodec create(BindingRuntimeContext context); - - /** - * Creates Binding Codec Tree for schema context according to binding - * classes. - * - * @param schemaContext - * - schema 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 - */ - BindingTreeCodec create(SchemaContext schemaContext, Class... bindingClasses); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/serializer/BindingNormalizedNodeSerializer.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/serializer/BindingNormalizedNodeSerializer.java deleted file mode 100644 index 6a81ed81d7..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/api/serializer/BindingNormalizedNodeSerializer.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer; - -import java.util.Map.Entry; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -/** - * Serialization service, which provides two-way serialization between Java - * Binding Data representation and NormalizedNode representation. - */ -public interface BindingNormalizedNodeSerializer { - - /** - * Translates supplied YANG Instance Identifier into Binding instance - * identifier. - * - * @param dom - * - YANG Instance Identifier - * @return Binding Instance Identifier, or null if the instance identifier - * is not representable - */ - @Nullable - InstanceIdentifier fromYangInstanceIdentifier(@Nonnull YangInstanceIdentifier dom); - - /** - * Translates supplied YANG Instance Identifier and NormalizedNode into - * Binding data. - * - * @param path - * - Binding Instance Identifier - * @param data - * - NormalizedNode representing data - * @return DOM Instance Identifier - */ - @Nullable - Entry, TreeNode> fromNormalizedNode(@Nonnull YangInstanceIdentifier path, - NormalizedNode data); - - /** - * Translates supplied Binding Instance Identifier into NormalizedNode - * instance identifier. - * - * @param binding - * - Binding Instance Identifier - * @return DOM Instance Identifier - * @throws IllegalArgumentException - * - if supplied Instance Identifier is not valid - */ - @Nullable - YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull InstanceIdentifier binding); - - /** - * Translates supplied Binding Instance Identifier and data into - * NormalizedNode representation. - * - * @param path - * - Binding Instance Identifier pointing to data - * @param data - * - representing Data Tree - * @param data type - * @return NormalizedNode representation - * @throws IllegalArgumentException - * - if supplied Instance Identifier is not valid. - */ - @Nullable - Entry> - toNormalizedNode(InstanceIdentifier path, T data); - - /** - * Translates supplied NormalizedNode Notification into Binding data. - * - * @param path - * - Schema Path of Notification, schema path is absolute, and - * consists of Notification QName - * @param data - * - NormalizedNode representing data - * @return Binding representation of Notification - */ - @Nullable - Notification fromNormalizedNodeNotification(@Nonnull SchemaPath path, @Nonnull ContainerNode data); - - /** - * Translates supplied Binding Notification or output into NormalizedNode - * notification. - * - * @param data - * NormalizedNode representing notification data - * @return NormalizedNode representation of notification - */ - @Nonnull - ContainerNode toNormalizedNodeNotification(@Nonnull Notification data); - - /** - * Translates supplied NormalizedNode operation (RPC, Action) input or - * output into Binding data. - * - * @param path - * - schema path of operation data, schema path consists of - * rpc/action QName and input/output QName. - * @param data - * - NormalizedNode representing data - * @return Binding representation of operation data - */ - @Nullable - TreeNode fromNormalizedNodeOperationData(@Nonnull SchemaPath path, @Nonnull ContainerNode data); - - /** - * Translates supplied Binding operation (RPC, Action) input or output into - * NormalizedNode data. - * - * @param data - * - NormalizedNode representing rpc/action data - * @return NormalizedNode representation of operation data - */ - @Nonnull - ContainerNode toNormalizedNodeOperationData(@Nonnull TreeNode data); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/api/TreeNodeSerializerGenerator.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/api/TreeNodeSerializerGenerator.java deleted file mode 100644 index 1456c3ec91..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/api/TreeNodeSerializerGenerator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; - -/** - * Public interface exposed from generator implementation. - */ -@Beta -public interface TreeNodeSerializerGenerator { - - /** - * Get a serializer for a particular type. - * - * @param type - class of type - * @return serializer instance - */ - TreeNodeSerializerImplementation getSerializer(Class type); - - /** - * Notify the generator that the runtime context has been updated. - * - * @param runtime - new runtime context - */ - void onBindingRuntimeContextUpdated(BindingRuntimeContext runtime); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StaticBindingProperty.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StaticBindingProperty.java deleted file mode 100644 index 62754501b8..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StaticBindingProperty.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; - -/** - * Definition of static property for Binding objects. - * - *

- * This definition consists of - *

    - *
  • name - property name
  • - *
  • type - Java type for property
  • - *
  • value - value to which property should be initialized
  • - *
- */ -@Beta -public class StaticBindingProperty { - - private final String name; - private final Class type; - private final Object value; - - public StaticBindingProperty(final String name, final Class type, final Object value) { - this.name = requireNonNull(name); - this.type = requireNonNull(type); - this.value = requireNonNull(value); - } - - public String getName() { - return this.name; - } - - public Class getType() { - return this.type; - } - - public Object getValue() { - return this.value; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + this.name.hashCode(); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final StaticBindingProperty other = (StaticBindingProperty) obj; - if (!this.name.equals(other.name)) { - return false; - } - return true; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StreamWriterGenerator.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StreamWriterGenerator.java deleted file mode 100644 index b84a26e74d..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/StreamWriterGenerator.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api.TreeNodeSerializerGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractStreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source.AbstractAugmentSerializerSource; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source.AbstractAugmentableDataNodeContainerEmitterSource; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source.AbstractTreeNodeSerializerSource; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.AugmentableDispatchSerializer; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.ChoiceDispatchSerializer; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; - -/** - * Concrete implementation of {@link AbstractStreamWriterGenerator} which in - * runtime generates classes implementing - * {@link TreeNodeSerializerImplementation} interface and are used to serialize - * Binding {@link TreeNode}. - * - *

- * Actual implementation of codecs is done via static methods, which allows for - * static wiring of codecs. Choice codec and Augmentable codecs are static - * properties of parent codec and stateless implementations are used ( - * {@link ChoiceDispatchSerializer}, {@link AugmentableDispatchSerializer}, - * which uses registry to dispatch to concrete item codec. - */ -@Beta -public final class StreamWriterGenerator extends AbstractStreamWriterGenerator { - - private static final String UNKNOWN_SIZE = BindingStreamEventWriter.class.getName() + ".UNKNOWN_SIZE"; - - private StreamWriterGenerator(final JavassistUtils utils, final Void ignore) { - super(utils); - } - - /** - * Create a new instance backed by a specific {@link JavassistUtils} - * instance. - * - * @param utils - * JavassistUtils instance to use - * @return A new generator - */ - public static TreeNodeSerializerGenerator create(final JavassistUtils utils) { - return new StreamWriterGenerator(utils, null); - } - - @Override - protected AbstractTreeNodeSerializerSource generateContainerSerializer(final GeneratedType type, - final ContainerSchemaNode node) { - - return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) { - @Override - public CharSequence emitStartEvent() { - return startContainerNode(classReference(type), UNKNOWN_SIZE); - } - }; - } - - @Override - protected AbstractTreeNodeSerializerSource generateNotificationSerializer(final GeneratedType type, - final NotificationDefinition node) { - - return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) { - @Override - public CharSequence emitStartEvent() { - return startContainerNode(classReference(type), UNKNOWN_SIZE); - } - }; - } - - @Override - protected AbstractTreeNodeSerializerSource generateCaseSerializer(final GeneratedType type, - final CaseSchemaNode node) { - return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) { - @Override - public CharSequence emitStartEvent() { - return startCaseNode(classReference(type), UNKNOWN_SIZE); - } - }; - } - - @Override - protected AbstractTreeNodeSerializerSource generateUnkeyedListEntrySerializer(final GeneratedType type, - final ListSchemaNode node) { - return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) { - - @Override - public CharSequence emitStartEvent() { - return startUnkeyedListItem(UNKNOWN_SIZE); - } - }; - } - - @Override - protected AbstractTreeNodeSerializerSource generateAugmentSerializer(final GeneratedType type, - final Collection augmentationSchemas) { - return new AbstractAugmentSerializerSource(this, type, augmentationSchemas) { - - @Override - public CharSequence emitStartEvent() { - return startAugmentationNode(classReference(type)); - } - }; - } - - @Override - protected AbstractTreeNodeSerializerSource generateMapEntrySerializer(final GeneratedType type, - final ListSchemaNode node) { - return new AbstractAugmentableDataNodeContainerEmitterSource(this, type, node) { - @Override - public CharSequence emitStartEvent() { - StringBuilder sb = new StringBuilder() - .append('(') - .append(IdentifiableItem.class.getName()) - .append(") ") - .append(invoke(INPUT, "treeIdentifier")); - return startMapEntryNode(sb.toString(), UNKNOWN_SIZE); - } - }; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/TreeNodeSerializerPrototype.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/TreeNodeSerializerPrototype.java deleted file mode 100644 index 9c135d8560..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/impl/TreeNodeSerializerPrototype.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl; - -import com.google.common.annotations.Beta; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; - -/** - * Prototype of a TreeNodeSerializerImplementation. This is a template class, which the stream writer - * generator uses to instantiate {@link TreeNodeSerializerImplementation} on a per-type basis. During that - * time, the {@link #serialize(TreeNodeSerializerRegistry, TreeNode, BindingStreamEventWriter)} method will be - * replaced by the real implementation. - */ -@Beta -public final class TreeNodeSerializerPrototype implements TreeNodeSerializerImplementation { - - private static final TreeNodeSerializerPrototype INSTANCE = new TreeNodeSerializerPrototype(); - - private TreeNodeSerializerPrototype() { - // Intentionally hidden, subclasses can replace it - } - - /** - * Return the shared serializer instance. - * - * @return Global singleton instance. - */ - public static TreeNodeSerializerPrototype getInstance() { - return INSTANCE; - } - - @Override - public void serialize(final TreeNodeSerializerRegistry reg, final TreeNode obj, - final BindingStreamEventWriter stream) throws IOException { - throw new UnsupportedOperationException("Prototype body, this code should never be invoked."); - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractGenerator.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractGenerator.java deleted file mode 100644 index 34cb4d06fd..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractGenerator.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator; - -import com.google.common.annotations.Beta; - -/** - * Base class for sharing the loading capability. - */ -@Beta -public abstract class AbstractGenerator { - - /** - * Ensure that the serializer class for specified class is loaded and return - * its name. - * - * @param cls - * - data tree class - * @return serializer class name - */ - public abstract String loadSerializerFor(Class cls); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractStreamWriterGenerator.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractStreamWriterGenerator.java deleted file mode 100644 index 4715f6d640..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/generator/AbstractStreamWriterGenerator.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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 java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.util.Collection; -import java.util.Map.Entry; -import javassist.CannotCompileException; -import javassist.CtClass; -import javassist.CtField; -import javassist.CtMethod; -import javassist.Modifier; -import javassist.NotFoundException; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api.TreeNodeSerializerGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StaticBindingProperty; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.TreeNodeSerializerPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source.AbstractTreeNodeSerializerSource; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.AugmentableDispatchSerializer; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.util.ClassLoaderUtils; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public abstract class AbstractStreamWriterGenerator extends AbstractGenerator implements TreeNodeSerializerGenerator { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractStreamWriterGenerator.class); - - public static final String SERIALIZE_METHOD_NAME = "serialize"; - public static final AugmentableDispatchSerializer AUGMENTABLE = new AugmentableDispatchSerializer(); - private static final Field FIELD_MODIFIERS; - - private final LoadingCache, TreeNodeSerializerImplementation> implementations; - private final CtClass[] serializeArguments; - private final JavassistUtils javassist; - - private BindingRuntimeContext context; - - static { - /* - * Cache reflection access to field modifiers field. We need this to set - * fix the static declared fields to final once we initialize them. If - * we cannot get access, that's fine, too. - */ - Field field = null; - try { - field = Field.class.getDeclaredField("modifiers"); - field.setAccessible(true); - } catch (NoSuchFieldException | SecurityException e) { - LOG.warn("Could not get Field modifiers field, serializers run at decreased efficiency", e); - } - - FIELD_MODIFIERS = field; - } - - protected AbstractStreamWriterGenerator(final JavassistUtils utils) { - this.javassist = requireNonNull(utils, "JavassistUtils instance is required."); - this.serializeArguments = new CtClass[] { javassist.asCtClass(TreeNodeSerializerRegistry.class), - javassist.asCtClass(TreeNode.class), javassist.asCtClass(BindingStreamEventWriter.class), }; - javassist.appendClassLoaderIfMissing(TreeNodeSerializerPrototype.class.getClassLoader()); - this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader()); - } - - @Override - public final TreeNodeSerializerImplementation getSerializer(final Class type) { - return implementations.getUnchecked(type); - } - - @Override - public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) { - this.context = runtime; - } - - @Override - public final String loadSerializerFor(final Class cls) { - return implementations.getUnchecked(cls).getClass().getName(); - } - - private final class SerializerImplementationLoader extends CacheLoader, TreeNodeSerializerImplementation> { - - private static final String GETINSTANCE_METHOD_NAME = "getInstance"; - private static final String SERIALIZER_SUFFIX = "$StreamWriter"; - - private String getSerializerName(final Class type) { - return type.getName() + SERIALIZER_SUFFIX; - } - - @Override - @SuppressWarnings("unchecked") - public TreeNodeSerializerImplementation load(@Nonnull final Class type) throws Exception { - Preconditions.checkArgument(BindingReflections.isBindingClass(type)); - Preconditions.checkArgument(Instantiable.class.isAssignableFrom(type), - "Instantiable is not assingnable from %s from classloader %s.", type, type.getClassLoader()); - - final String serializerName = getSerializerName(type); - - Class cls; - try { - cls = (Class) ClassLoaderUtils - .loadClass(type.getClassLoader(), serializerName); - } catch (final ClassNotFoundException e) { - cls = generateSerializer(type, serializerName); - } - - final TreeNodeSerializerImplementation obj = - (TreeNodeSerializerImplementation) cls.getDeclaredMethod(GETINSTANCE_METHOD_NAME).invoke(null); - LOG.debug("Loaded serializer {} for class {}", obj, type); - return obj; - } - - private Class generateSerializer(final Class type, - final String serializerName) - throws CannotCompileException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException { - final AbstractTreeNodeSerializerSource source = generateEmitterSource(type, serializerName); - final CtClass poolClass = generateEmitter0(type, source, serializerName); - final Class cls = - poolClass.toClass(type.getClassLoader(), type.getProtectionDomain()) - .asSubclass(TreeNodeSerializerImplementation.class); - - /* - * Due to OSGi class loader rules we cannot initialize the fields - * during construction, as the initializer expressions do not see - * our implementation classes. This should be almost as good as - * that, as we are resetting the fields to final before ever leaking - * the class. - */ - for (final StaticBindingProperty constant : source.getStaticConstants()) { - final Field field = cls.getDeclaredField(constant.getName()); - field.setAccessible(true); - field.set(null, constant.getValue()); - - if (FIELD_MODIFIERS != null) { - FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL); - } - } - - return cls; - } - } - - private AbstractTreeNodeSerializerSource generateEmitterSource(final Class type, final String serializerName) { - Types.typeForClass(type); - javassist.appendClassLoaderIfMissing(type.getClassLoader()); - - if (Augmentation.class.isAssignableFrom(type)) { - final Entry> entry = context.getAugmentationDefinition(type); - return generateAugmentSerializer(((GeneratedTypeBuilder) entry.getKey()).toInstance(), entry.getValue()); - } - - final Entry typeWithSchema = context.getTypeWithSchema(type); - final GeneratedType generatedType = typeWithSchema.getKey(); - final Object schema = typeWithSchema.getValue(); - - final AbstractTreeNodeSerializerSource source; - if (schema instanceof ContainerSchemaNode) { - source = generateContainerSerializer(generatedType, (ContainerSchemaNode) schema); - } else if (schema instanceof ListSchemaNode) { - final ListSchemaNode casted = (ListSchemaNode) schema; - if (casted.getKeyDefinition().isEmpty()) { - source = generateUnkeyedListEntrySerializer(generatedType, casted); - } else { - source = generateMapEntrySerializer(generatedType, casted); - } - } else if (schema instanceof CaseSchemaNode) { - source = generateCaseSerializer(generatedType, (CaseSchemaNode) schema); - } else if (schema instanceof NotificationDefinition) { - source = generateNotificationSerializer(generatedType, (NotificationDefinition) schema); - } else { - throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported"); - } - return source; - } - - private CtClass generateEmitter0(final Class type, final AbstractTreeNodeSerializerSource source, - final String serializerName) { - final CtClass product; - - /* - * getSerializerBody() has side effects, such as loading classes and - * codecs, it should be run in model class loader in order to correctly - * reference load child classes. - * - * Furthermore the fact that getSerializedBody() can trigger other code - * generation to happen, we need to take care of this before calling - * instantiatePrototype(), as that will call our customizer with the - * lock held, hence any code generation will end up being blocked on the - * javassist lock. - */ - final String body = ClassLoaderUtils.getWithClassLoader(type.getClassLoader(), - source.getSerializerBody()::toString); - - try { - product = javassist.instantiatePrototype(TreeNodeSerializerPrototype.class.getName(), serializerName, - cls -> { - // Generate any static fields - for (final StaticBindingProperty def : source.getStaticConstants()) { - final CtField field = new CtField(javassist.asCtClass(def.getType()), def.getName(), cls); - field.setModifiers(Modifier.PRIVATE + Modifier.STATIC); - cls.addField(field); - } - - // Replace serialize() -- may reference static fields - final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments); - serializeTo.setBody(body); - - // The prototype is not visible, so we need to take care - // of that - cls.setModifiers(Modifier.setPublic(cls.getModifiers())); - }); - } catch (final NotFoundException e) { - LOG.error("Failed to instatiate serializer {}", source, e); - throw new LinkageError("Unexpected instantation problem: serializer prototype not found", e); - } - return product; - } - - /** - * Generates serializer source code for supplied container node, which will - * read supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of container - * @param node - schema of container - * @return source for container node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateContainerSerializer(GeneratedType type, - ContainerSchemaNode node); - - /** - * Generates serializer source for supplied case node, which will read - * supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of case - * @param node - schema of case - * @return source for case node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateCaseSerializer(GeneratedType type, CaseSchemaNode node); - - /** - * Generates serializer source for supplied list node, which will read - * supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of list - * @param node - schema of list - * @return source for list node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateMapEntrySerializer(GeneratedType type, - ListSchemaNode node); - - /** - * Generates serializer source for supplied list node, which will read - * supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of list - * @param node - schema of list - * @return source for list node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateUnkeyedListEntrySerializer(GeneratedType type, - ListSchemaNode node); - - /** - * Generates serializer source for supplied augmentation node, which will - * read supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of augmentation - * @param schemas - schemas of augmentation - * @return source for augmentation node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateAugmentSerializer(GeneratedType type, - Collection schemas); - - /** - * Generates serializer source for notification node, which will read - * supplied binding type and invoke proper methods on supplied - * {@link BindingStreamEventWriter}. - * - *

- * Implementation is required to recursively invoke events for all reachable - * binding objects. - * - * @param type - binding type of notification - * @param node - schema of notification - * @return source for notification node writer - */ - protected abstract AbstractTreeNodeSerializerSource generateNotificationSerializer(GeneratedType type, - NotificationDefinition node); - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentSerializerSource.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentSerializerSource.java deleted file mode 100644 index 525f72da0a..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentSerializerSource.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.ArrayList; -import java.util.Collection; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public abstract class AbstractAugmentSerializerSource extends AbstractDataNodeContainerSerializerSource { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractAugmentSerializerSource.class); - private final Collection augmentationSchemas; - - public AbstractAugmentSerializerSource(final AbstractGenerator generator, final GeneratedType type, - final Collection augmentationSchemas) { - // Note: passing first augmentation schema node just to avoid exceptions from super class. - super(generator, type, augmentationSchemas.stream().findFirst().get()); - this.augmentationSchemas = requireNonNull(augmentationSchemas); - } - - /** - * Override {@link AbstractDataNodeContainerSerializerSource#getChildNodes()} to get all children nodes - * of same target augmentation schema nodes. - */ - @Override - protected Collection getChildNodes() { - Collection childNodes = new ArrayList<>(); - for (AugmentationSchemaNode schema : this.augmentationSchemas) { - childNodes.addAll(schema.getChildNodes()); - } - return childNodes; - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentableDataNodeContainerEmitterSource.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentableDataNodeContainerEmitterSource.java deleted file mode 100644 index d58725c9c9..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractAugmentableDataNodeContainerEmitterSource.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractStreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; - -@Beta -public abstract class AbstractAugmentableDataNodeContainerEmitterSource - extends AbstractDataNodeContainerSerializerSource { - - private static final String AUGMENTABLE_SERIALIZER = "AUGMENTABLE_SERIALIZER"; - - public AbstractAugmentableDataNodeContainerEmitterSource(final AbstractStreamWriterGenerator generator, - final GeneratedType type, final DataNodeContainer node) { - super(generator, type, node); - /* - * Eventhough intuition says the serializer could reference the - * generator directly, that is not true in OSGi environment -- so we - * need to resolve the reference first and inject it as a static - * constant. - */ - staticConstant(AUGMENTABLE_SERIALIZER, TreeNodeSerializerImplementation.class, - StreamWriterGenerator.AUGMENTABLE); - } - - @Override - protected void emitAfterBody(final StringBuilder builder) { - builder.append(statement(invoke(AUGMENTABLE_SERIALIZER, "serialize", REGISTRY, INPUT, STREAM))); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractDataNodeContainerSerializerSource.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractDataNodeContainerSerializerSource.java deleted file mode 100755 index 681eb4bffe..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractDataNodeContainerSerializerSource.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.ChoiceDispatchSerializer; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; -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.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public abstract class AbstractDataNodeContainerSerializerSource extends AbstractTreeNodeSerializerSource { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractDataNodeContainerSerializerSource.class); - - protected static final String INPUT = "_input"; - private static final String CHOICE_PREFIX = "CHOICE_"; - - //Note: the field takes no effects by augmentation. - private final DataNodeContainer schemaNode; - private final GeneratedType dtoType; - - public AbstractDataNodeContainerSerializerSource(final AbstractGenerator generator, final GeneratedType type, - final DataNodeContainer node) { - super(generator); - this.dtoType = requireNonNull(type); - this.schemaNode = requireNonNull(node); - } - - /** - * Return the character sequence which should be used for start event. - * - * @return Start event character sequence - */ - protected abstract CharSequence emitStartEvent(); - - @Override - public CharSequence getSerializerBody() { - final StringBuilder builder = new StringBuilder(); - builder.append("{\n"); - builder.append(statement(assign(TreeNodeSerializerRegistry.class.getName(), REGISTRY, "$1"))); - builder.append(statement(assign(dtoType.getFullyQualifiedName(), INPUT, - cast(dtoType.getFullyQualifiedName(), "$2")))); - builder.append(statement(assign(BindingStreamEventWriter.class.getName(), STREAM, - cast(BindingStreamEventWriter.class.getName(), "$3")))); - builder.append(statement(assign(BindingSerializer.class.getName(), SERIALIZER, null))); - builder.append("if ("); - builder.append(STREAM); - builder.append(" instanceof "); - builder.append(BindingSerializer.class.getName()); - builder.append(") {"); - builder.append(statement(assign(SERIALIZER, cast(BindingSerializer.class.getName(), STREAM)))); - builder.append('}'); - builder.append(statement(emitStartEvent())); - - emitBody(builder); - emitAfterBody(builder); - builder.append(statement(endNode())); - builder.append(statement("return null")); - builder.append('}'); - return builder; - } - - /** - * Allows for customization of emitting code, which is processed after - * normal DataNodeContainer body. Ideal for augmentations or others. - */ - protected void emitAfterBody(final StringBuilder builder) { - } - - private static Map collectAllProperties(final GeneratedType type, final Map hashMap) { - for (final MethodSignature definition : type.getMethodDefinitions()) { - hashMap.put(definition.getName(), definition.getReturnType()); - } - - /** - * According to binding v2 spec., uses nodes are processed as-if they are direct children - * of parent node, so we can't get properties from implements any more. Uses nodes are processed by invoking - * {@link org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil#resolveDataSchemaNodes()} in which - * {@link org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil#resolveDataSchemaNodesCheck()} - * allows them to be resolved. - */ - - return hashMap; - } - - private static String getGetterName(final DataSchemaNode node) { - final TypeDefinition type; - if (node instanceof TypedDataSchemaNode) { - type = ((TypedDataSchemaNode) node).getType(); - } else { - type = null; - } - - final String prefix; - // Bug 8903: If it is a derived type of boolean, not a built-in type, then the return type - // of method would be the generated type and the prefix should be 'get'. - if (type instanceof BooleanTypeDefinition - && (type.getPath().equals(node.getPath()) || type.getBaseType() == null)) { - prefix = "is"; - } else { - prefix = "get"; - } - return prefix + JavaIdentifierNormalizer.normalizeSpecificIdentifier(node.getQName().getLocalName(), - JavaIdentifier.CLASS); - } - - private boolean emitCheck(final DataSchemaNode schemaChild) { - if (schemaChild.isAugmenting()) { - QName root = schemaChild.getPath().getPathFromRoot().iterator().next(); - return root.getModule().equals(schemaChild.getQName().getModule()); - } - - return true; - } - - /** - * Note: the method would be overrided by {@link AbstractAugmentSerializerSource#getChildNodes()}, - * since all augmentation schema nodes of same target would be grouped into sort of one node, - * so call {@link AbstractAugmentSerializerSource#getChildNodes()} to get all these children - * nodes of same target augmentation schemas. - */ - protected Collection getChildNodes() { - return schemaNode.getChildNodes(); - } - - private void emitBody(final StringBuilder builder) { - final Map getterToType = collectAllProperties(dtoType, new HashMap()); - for (final DataSchemaNode schemaChild : getChildNodes()) { - /** - * As before, it only emitted data nodes which were not added by uses or augment, now - * according to binding v2 specification, augment of the same module is same as inlining, - * all data node children should be processed as-if they were directly defined inside - * target node. - */ - if (emitCheck(schemaChild)) { - final String getter = getGetterName(schemaChild); - final Type childType = getterToType.get(getter); - if (childType == null) { - // FIXME AnyXml nodes are ignored, since their type cannot be found in generated bindnig - // Bug-706 https://bugs.opendaylight.org/show_bug.cgi?id=706 - if (schemaChild instanceof AnyXmlSchemaNode) { - LOG.warn("Node {} will be ignored. AnyXml is not yet supported from binding aware code." - + "Binding Independent code can be used to serialize anyXml nodes.", schemaChild.getPath()); - continue; - } - - throw new IllegalStateException( - String.format("Unable to find type for child node %s. Expected child nodes: %s", - schemaChild.getPath(), getterToType)); - } - emitChild(builder, getter, childType, schemaChild); - } - } - } - - private void emitChild(final StringBuilder builder, final String getterName, final Type childType, - final DataSchemaNode schemaChild) { - builder.append(statement(assign(childType, getterName, cast(childType, invoke(INPUT, getterName))))); - - builder.append("if (").append(getterName).append(" != null) {\n"); - emitChildInner(builder, getterName, childType, schemaChild); - builder.append("}\n"); - } - - private void emitChildInner(final StringBuilder builder, final String getterName, final Type childType, - final DataSchemaNode child) { - if (child instanceof LeafSchemaNode) { - builder.append(statement(leafNode(child.getQName().getLocalName(), getterName))); - } else if (child instanceof AnyXmlSchemaNode) { - builder.append(statement(anyxmlNode(child.getQName().getLocalName(), getterName))); - } else if (child instanceof LeafListSchemaNode) { - final CharSequence startEvent; - if (((LeafListSchemaNode) child).isUserOrdered()) { - startEvent = startOrderedLeafSet(child.getQName().getLocalName(), - invoke(getterName, "size")); - } else { - startEvent = startLeafSet(child.getQName().getLocalName(),invoke(getterName, "size")); - } - builder.append(statement(startEvent)); - final Type valueType = ((ParameterizedType) childType).getActualTypeArguments()[0]; - builder.append(forEach(getterName, valueType, statement(leafSetEntryNode(CURRENT)))); - builder.append(statement(endNode())); - } else if (child instanceof ListSchemaNode) { - final Type valueType = ((ParameterizedType) childType).getActualTypeArguments()[0]; - final ListSchemaNode casted = (ListSchemaNode) child; - emitList(builder, getterName, valueType, casted); - } else if (child instanceof ContainerSchemaNode) { - builder.append(tryToUseCacheElse(getterName,statement(staticInvokeEmitter(childType, getterName)))); - } else if (child instanceof ChoiceSchemaNode) { - final String propertyName = CHOICE_PREFIX + childType.getName(); - staticConstant(propertyName, TreeNodeSerializerImplementation.class, - ChoiceDispatchSerializer.from(loadClass(childType))); - builder.append(tryToUseCacheElse(getterName,statement(invoke(propertyName, - StreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, cast(TreeNode.class.getName(),getterName), - STREAM)))); - } - } - - private static StringBuilder tryToUseCacheElse(final String getterName, final CharSequence statement) { - final StringBuilder b = new StringBuilder(); - - b.append("if ( "); - b.append(SERIALIZER).append("== null || "); - b.append(invoke(SERIALIZER, "serialize", getterName)).append("== null"); - b.append(") {"); - b.append(statement); - b.append('}'); - return b; - } - - private void emitList(final StringBuilder builer, final String getterName, final Type valueType, - final ListSchemaNode child) { - final CharSequence startEvent; - - builer.append(statement(assign("int", "_count", invoke(getterName, "size")))); - if (child.getKeyDefinition().isEmpty()) { - startEvent = startUnkeyedList(classReference(valueType), "_count"); - } else if (child.isUserOrdered()) { - startEvent = startOrderedMapNode(classReference(valueType), "_count"); - } else { - startEvent = startMapNode(classReference(valueType), "_count"); - } - builer.append(statement(startEvent)); - builer.append(forEach(getterName, valueType, tryToUseCacheElse(CURRENT, - statement(staticInvokeEmitter(valueType, CURRENT))))); - builer.append(statement(endNode())); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractSource.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractSource.java deleted file mode 100644 index f7ac8db011..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractSource.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source; - -import com.google.common.annotations.Beta; -import com.google.common.collect.Iterators; -import com.google.common.collect.UnmodifiableIterator; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StaticBindingProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * Base class for preparing types and constants for writer. - * - */ -@Beta -abstract class AbstractSource { - - private final Set staticConstants = new HashSet<>(); - - /** - * Create new static constant of specific type with value. - * - * @param name - * - name of constant - * @param type - * - specific type of constant - * @param value - * - value of constant - * @param - * - type of constant - */ - final void staticConstant(final String name, final Class type, final T value) { - this.staticConstants.add(new StaticBindingProperty(name, type, value)); - } - - /** - * Get set of static constants. - * - * @return unmodifiable view of set of static constants - */ - public final Set getStaticConstants() { - return Collections.unmodifiableSet(this.staticConstants); - } - - /** - * Prepare common part of invoke of method on object. - * - * @param object - * - object for invoke method - * @param methodName - * - method name to be invoked - * @return base part of invoking method on object as String - */ - private static StringBuilder prepareCommonInvokePart(final CharSequence object, final String methodName) { - final StringBuilder sb = new StringBuilder(); - if (object != null) { - sb.append(object); - sb.append('.'); - } - return sb.append(methodName).append('('); - } - - /** - * Prepare invoking method on object with an argument. - * - * @param object - * - object for invoke method - * @param methodName - * - method name to be invoked - * @param arg - * - argument of method - * @return invoking method on object with an argument as String - */ - static final CharSequence invoke(final CharSequence object, final String methodName, final Object arg) { - return prepareCommonInvokePart(object, methodName).append(arg).append(')'); - } - - /** - * Prepare invoking method on object with more arguments. - * - * @param object - * - object for invoke method - * @param methodName - * - method name to be invoked - * @param args - * - arguments of method - * @return invoking method on object with more arguments as String - */ - protected static final CharSequence invoke(final CharSequence object, final String methodName, - final Object... args) { - final StringBuilder sb = prepareCommonInvokePart(object, methodName); - - final UnmodifiableIterator iterator = Iterators.forArray(args); - while (iterator.hasNext()) { - sb.append(iterator.next()); - if (iterator.hasNext()) { - sb.append(','); - } - } - return sb.append(')'); - } - - /** - * Assign of value to variable. - * - * @param var - * - name of variable - * @param value - * - value of variable - * @return assigned value to variable as char sequence - */ - static final CharSequence assign(final String var, final CharSequence value) { - return assign((String) null, var, value); - } - - /** - * Assign of value to variable of specific type. - * - * @param type - * - specific type of value - * @param var - * - name of variable - * @param value - * - value of variable - * @return assigned value to variable of specific type as char sequence, if - * type is null then there is not added type to final string of - * assigned value - */ - static final CharSequence assign(final String type, final String var, final CharSequence value) { - final StringBuilder sb = new StringBuilder(); - if (type != null) { - sb.append(type); - sb.append(' '); - } - return sb.append(var).append(" = ").append(value); - } - - /** - * Assign of value to variable of specific type. - * - * @param type - * - specific type of value - * @param var - * - name of variable - * @param value - * - value of variable - * @return assigned value to variable of specific type as char sequence, if - * type is null then there is not added type to final string of - * assigned value - */ - static final CharSequence assign(final Type type, final String var, final CharSequence value) { - return assign(type.getFullyQualifiedName(), var, value); - } - - /** - * Cast value to specific type. - * - * @param type - * - specific type - * @param value - * - value for cast - * @return casted value to specifc type as char sequence - */ - static final CharSequence cast(final Type type, final CharSequence value) { - return cast(type.getFullyQualifiedName(), value); - } - - /** - * Cast value to specific type. - * - * @param type - * - specific type - * @param value - * - value for cast - * @return casted value to specifc type as char sequence - */ - static final CharSequence cast(final String type, final CharSequence value) { - return "((" + type + ") " + value + ')'; - } - - /** - * Create loop through iterable object with specific body. - * - * @param iterable - * - iterable object - * @param iteratorName - * - name of iterator variable of iterable object - * @param valueType - * - type of iterable item - * @param valueName - * - name of variable of iterable item - * @param body - * - specific body for porcess of iterable item - * @return loop through iterable object with specific body as String - */ - static final CharSequence forEach(final String iterable, final String iteratorName, - final String valueType, final String valueName, final CharSequence body) { - final StringBuilder sb = new StringBuilder(); - sb.append(statement(assign(java.util.Iterator.class.getName(), iteratorName, invoke(iterable, "iterator")))); - sb.append("while (").append(invoke(iteratorName, "hasNext")).append(") {\n"); - sb.append(statement(assign(valueType, valueName, cast(valueType, invoke(iteratorName, "next"))))); - sb.append(body); - return sb.append("\n}\n"); - } - - /** - * Create new Java statement. - * - * @param statement - * - input for creating new Java statement - * @return java statement - */ - static final CharSequence statement(final CharSequence statement) { - return new StringBuilder(statement).append(";\n"); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractTreeNodeSerializerSource.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractTreeNodeSerializerSource.java deleted file mode 100644 index 487d6d2cbf..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/generator/spi/source/AbstractTreeNodeSerializerSource.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.source; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.spi.generator.AbstractStreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; - -@Beta -public abstract class AbstractTreeNodeSerializerSource extends AbstractSource { - - private static final ClassLoadingStrategy STRATEGY = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(); - - static final String SERIALIZER = "_serializer"; - static final String STREAM = "_stream"; - static final String ITERATOR = "_iterator"; - static final String CURRENT = "_current"; - static final String REGISTRY = "_registry"; - - private final AbstractGenerator generator; - - /** - * Set up generator. - * - * @param generator - * -parent generator - */ - AbstractTreeNodeSerializerSource(final AbstractGenerator generator) { - this.generator = requireNonNull(generator); - } - - @SuppressWarnings("unchecked") - Class> loadClass(final Type childType) { - try { - return (Class>) STRATEGY.loadClass(childType); - } catch (final ClassNotFoundException e) { - throw new IllegalStateException("Could not load referenced class ", e); - } - } - - /** - * Returns body of static serialize method. - * - *
    - *
  • {@link TreeNodeSerializerRegistry} - registry of serializers - *
  • {@link TreeNode} - node to be serialized - *
  • {@link BindingStreamEventWriter} - writer to which events should be - * serialized - *
- * - * @return valid javassist code describing static serialization body - */ - public abstract CharSequence getSerializerBody(); - - /** - * Invoking leafNode method of stream with arguments local name and value. - * - * @param localName - * - argument for invoking leafNode - * @param value - * - argument for invoking leafNode - * @return invoking leafNode method as String - */ - static final CharSequence leafNode(final String localName, final CharSequence value) { - return invoke(STREAM, "leafNode", escape(localName), value); - } - - /** - * Invoking startLeafSet method of stream with arguments local name and - * expected. - * - * @param localName - * - argument for invoking startLeafSet - * @param expected - * - argument for invoking startLeafSet - * @return invoking startLeafSet method as String - */ - static final CharSequence startLeafSet(final String localName, final CharSequence expected) { - return invoke(STREAM, "startLeafSet", escape(localName), expected); - } - - /** - * Invoking startOrderedLeafSet method of stream with arguments localname - * and expected. - * - * @param localName - * - argument for invoking startOrderedLeafSet - * @param expected - * - argument for invoking startOrderedLeafSet - * @return invoking startOrderedLeafSet method as String - */ - static final CharSequence startOrderedLeafSet(final String localName, final CharSequence expected) { - return invoke(STREAM, "startOrderedLeafSet", escape(localName), expected); - } - - /** - * Bound local name by quotes. - * - * @param localName - * - to be bounded - * @return bounded local name - */ - static final CharSequence escape(final String localName) { - return '"' + localName + '"'; - } - - /** - * Invoking leafSetEntryNode method of stream with argument value. - * - * @param value - * - argument for invoking leafSetEntryNode - * @return invoking leafSetEntryNode method as String - */ - static final CharSequence leafSetEntryNode(final CharSequence value) { - return invoke(STREAM, "leafSetEntryNode", value); - } - - /** - * Invoking startContainerNode method of stream with arguments type and - * expected. - * - * @param type - * - argument for invoking startContainerNode - * @param expected - * - argument for invoking startContainerNode - * @return invoking startContainerNode method as String - */ - public static final CharSequence startContainerNode(final CharSequence type, final CharSequence expected) { - return invoke(STREAM, "startContainerNode", type, expected); - } - - /** - * Invoking startUnkeyedList method of stream with arguments type and - * expected. - * - * @param type - * - argument for invoking startUnkeyedList - * @param expected - * - argument for invoking startUnkeyedList - * @return invoking startUnkeyedList method as String - */ - static final CharSequence startUnkeyedList(final CharSequence type, final CharSequence expected) { - return invoke(STREAM, "startUnkeyedList", type, expected); - } - - /** - * Invoking startUnkeyedListItem of stream with argument expected. - * - * @param expected - * - argument for invoking startUnkeyedListItem - * @return invoking startUnkeyedListItem method as String - */ - protected static final CharSequence startUnkeyedListItem(final CharSequence expected) { - return invoke(STREAM, "startUnkeyedListItem", expected); - } - - /** - * Invoking startMapNode method of stream with arguments type and expected. - * - * @param type - * - argument for invoking startMapNode - * @param expected - * - argument for invoking startMapNode - * @return invoking startMapNode method as String - */ - static final CharSequence startMapNode(final CharSequence type, final CharSequence expected) { - return invoke(STREAM, "startMapNode", type, expected); - } - - /** - * Invoking startOrderedMapNode method of stream with arguments type and - * expected. - * - * @param type - * - argument for invoking startOrderedMapNode - * @param expected - * - argument for invoking startOrderedMapNode - * @return invoking startOrderedMapNode method as String - */ - static final CharSequence startOrderedMapNode(final CharSequence type, final CharSequence expected) { - return invoke(STREAM, "startOrderedMapNode", type, expected); - } - - /** - * Invoking startMapEntryNode method of stream with arguments key and - * expected. - * - * @param key - * - argument for invoking startMapEntryNode - * @param expected - * - argument for invoking startMapEntryNode - * @return invoking startMapEntryNode method as String - */ - protected static final CharSequence startMapEntryNode(final CharSequence key, final CharSequence expected) { - return invoke(STREAM, "startMapEntryNode", key, expected); - } - - /** - * Invoking startAugmentationNode of stream with argument key. - * - * @param key - * - argument for invoking startAugmentationNode - * @return invoking startAugmentationNode method as String - */ - protected static final CharSequence startAugmentationNode(final CharSequence key) { - return invoke(STREAM, "startAugmentationNode", key); - } - - /** - * Invoking startChoiceNode method of stream with arguments localname and - * expected. - * - * @param localName - * - argument for invoking startChoiceNode - * @param expected - * - argument for invoking startChoiceNode - * @return invoking startChoiceNode method as String - */ - static final CharSequence startChoiceNode(final CharSequence localName, final CharSequence expected) { - return invoke(STREAM, "startChoiceNode", localName, expected); - } - - /** - * Invoking startCaseNode method of stream with arguments localname and - * expected. - * - * @param localName - * - argument for invoking startCaseNode - * @param expected - * - argument for invoking startCaseNode - * @return invoking startCaseNode method as String - */ - protected static final CharSequence startCaseNode(final CharSequence localName, final CharSequence expected) { - return invoke(STREAM, "startCase", localName, expected); - } - - /** - * Invoking anyxmlNode method of stream with arguments name and - * value. - * - * @param name - * - argument for invoking anyxmlNode - * @param value - * - argument for invoking anyxmlNode - * @return invoking anyxmlNode method as String - */ - static final CharSequence anyxmlNode(final String name, final String value) - throws IllegalArgumentException { - return invoke(STREAM, "anyxmlNode", escape(name), value); - } - - /** - * Invoking anydataNode method of stream with arguments name and - * value. - * - * @param name - * - argument for invoking anydataNode - * @param value - * - argument for invoking anydataNode - * @return invoking anydataNode method as String - */ - static final CharSequence anydataNode(final String name, final String value) - throws IllegalArgumentException { - return invoke(STREAM, "anydataNode", escape(name), name); - } - - /** - * Invoking endNode method of stream without any arguments. - * - * @return invoking andNode method as String - */ - static final CharSequence endNode() { - return invoke(STREAM, "endNode"); - } - - /** - * Prepare loop through iterable object with specific body. - * - * @param iterable - * - name of iterable object - * @param valueType - * - type of iterate objects - * @param body - * - specific body of loop - * @return loop through iterable object as String - */ - static final CharSequence forEach(final String iterable, final Type valueType, final CharSequence body) { - return forEach(iterable, ITERATOR, valueType.getFullyQualifiedName(), CURRENT, body); - } - - /** - * Returns class reference for type. - * - * @param type - * - type for referencing class - * @return referenced class of type - */ - protected static final CharSequence classReference(final Type type) { - return type.getFullyQualifiedName() + ".class"; - } - - /** - * After getting class of childType from class loader, prepare invoking of - * serialize() method from instance of reached class of childType with - * arguments {@link #REGISTRY}, name and {@link #STREAM}. - * - * @param childType - * - type of child for getting class from classloader - * @param name - * - argument for invoking serialize method of instance childType - * class - * @return invoking serialize method with specific arguments as String - */ - final CharSequence staticInvokeEmitter(final Type childType, final String name) { - final Class cls; - try { - cls = STRATEGY.loadClass(childType); - } catch (final ClassNotFoundException e) { - throw new IllegalStateException("Failed to invoke emitter", e); - } - - final String className = this.generator.loadSerializerFor(cls) + ".getInstance()"; - return invoke(className, AbstractStreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, name, STREAM); - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AnyxmlCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AnyxmlCodec.java deleted file mode 100755 index 9f6798aca9..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AnyxmlCodec.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import javax.xml.transform.dom.DOMSource; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.yangtools.concepts.Codec; -import org.w3c.dom.Document; - -/** - * Codec for serialize/deserialize anyxml. - */ -@Beta -public final class AnyxmlCodec implements Codec { - - private final BindingRuntimeContext context; - - /** - * Prepared binding runtime context for anyxml codec. - * - * @param context - * - binding runtime context - */ - public AnyxmlCodec(final BindingRuntimeContext context) { - this.context = requireNonNull(context); - } - - @Override - public Document deserialize(final DOMSource input) { - Preconditions.checkArgument(input != null, "Input must not be null."); - return (Document) input.getNode(); - } - - @Override - public DOMSource serialize(final Document input) { - Preconditions.checkArgument(input != null, "Input must not be null."); - return new DOMSource(input); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingNormalizedNodeCodecRegistry.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingNormalizedNodeCodecRegistry.java deleted file mode 100644 index 38c77f8a3e..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingNormalizedNodeCodecRegistry.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import java.io.IOException; -import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.function.Function; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory.BindingNormalizedNodeWriterFactory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory.BindingTreeCodecFactory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.api.TreeNodeSerializerGenerator; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.NotificationCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.BindingCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.context.ModuleInfoBackedContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; -import org.opendaylight.yangtools.concepts.Delegator; -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; -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.MapNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -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; - -/** - * Serializing and deserializing Binding and DOM data. - */ -@Beta -public class BindingNormalizedNodeCodecRegistry implements TreeNodeSerializerRegistry, BindingTreeCodecFactory, - BindingNormalizedNodeWriterFactory, BindingNormalizedNodeSerializer { - - private static final Logger LOG = LoggerFactory.getLogger(BindingNormalizedNodeCodecRegistry.class); - - private final TreeNodeSerializerGenerator generator; - private final LoadingCache, TreeNodeSerializer> serializers; - private volatile BindingCodecContext codecContext; - - /** - * Prepare generator for generating serializers and create loader for serializers. - * - * @param generator - * - serializer generator - */ - public BindingNormalizedNodeCodecRegistry(final TreeNodeSerializerGenerator generator) { - this.generator = requireNonNull(generator); - this.serializers = CacheBuilder.newBuilder().weakKeys().build(new GeneratorLoader()); - } - - @Override - public TreeNodeSerializer getSerializer(final Class type) { - return serializers.getUnchecked(type); - } - - /** - * Get binding tree codec context. - * - * @return codec context - */ - public BindingTreeCodec getCodecContext() { - return codecContext; - } - - /** - * Create codec context based on runtime context and notify generator that runtime context has been - * updated. - * - * @param context - * - runtime context - */ - public void onBindingRuntimeContextUpdated(final BindingRuntimeContext context) { - codecContext = create(context); - generator.onBindingRuntimeContextUpdated(context); - } - - @Nullable - @Override - public YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull final InstanceIdentifier binding) { - return codecContext.getInstanceIdentifierCodec().serialize(binding); - } - - @Nullable - @Override - public InstanceIdentifier fromYangInstanceIdentifier(@Nonnull final YangInstanceIdentifier dom) { - return codecContext.getInstanceIdentifierCodec().deserialize(dom); - } - - @Nullable - @Override - public Entry> - toNormalizedNode(final InstanceIdentifier path, final T data) { - final NormalizedNodeResult result = new NormalizedNodeResult(); - // We create DOM stream writer which produces normalized nodes - final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result); - - // We create Binding Stream Writer which translates from Binding to Normalized Nodes - final Entry writeCtx = - codecContext.newWriter(path, domWriter); - - // We get serializer which reads binding data and uses Binding To Normalized Node writer to write - // result - try { - getSerializer(path.getTargetType()).serialize(data, writeCtx.getValue()); - } catch (final IOException e) { - LOG.error("Unexpected failure while serializing path {} data {}", path, data, e); - throw new IllegalStateException("Failed to create normalized node", e); - } - return new SimpleEntry<>(writeCtx.getKey(), result.getResult()); - } - - @Nonnull - @SuppressWarnings("rawtypes") - @Override - public ContainerNode toNormalizedNodeNotification(@Nonnull final Notification data) { - final NormalizedNodeResult result = new NormalizedNodeResult(); - // We create DOM stream writer which produces normalized nodes - final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result); - @SuppressWarnings("unchecked") - final Class type = (Class) ((Instantiable) data).implementedInterface(); - @SuppressWarnings("unchecked") - final BindingStreamEventWriter writer = newNotificationWriter((Class) type, domWriter); - try { - getSerializer(type).serialize((TreeNode) data, writer); - } catch (final IOException e) { - LOG.error("Unexpected failure while serializing data {}", data, e); - throw new IllegalStateException("Failed to create normalized node", e); - } - return (ContainerNode) result.getResult(); - - } - - @Nonnull - @SuppressWarnings("unchecked") - @Override - public ContainerNode toNormalizedNodeOperationData(@Nonnull final TreeNode data) { - final NormalizedNodeResult result = new NormalizedNodeResult(); - // We create DOM stream writer which produces normalized nodes - final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result); - @SuppressWarnings("rawtypes") - final Class type = data.getClass(); - final Class> instData = (Class>) data.getClass(); - final BindingStreamEventWriter writer = newOperationWriter(instData, domWriter); - try { - getSerializer(type).serialize(data, writer); - } catch (final IOException e) { - LOG.error("Unexpected failure while serializing data {}", data, e); - throw new IllegalStateException("Failed to create normalized node", e); - } - return (ContainerNode) result.getResult(); - } - - private static boolean isBindingRepresentable(final NormalizedNode data) { - if (data instanceof ChoiceNode) { - return false; - } - if (data instanceof LeafNode) { - return false; - } - if (data instanceof LeafSetNode) { - return false; - } - if (data instanceof LeafSetEntryNode) { - return false; - } - if (data instanceof MapNode) { - return false; - } - if (data instanceof UnkeyedListNode) { - return false; - } - - return true; - } - - @Nullable - @Override - public Entry, TreeNode> fromNormalizedNode(@Nonnull final YangInstanceIdentifier path, - final NormalizedNode data) { - if (!isBindingRepresentable(data)) { - return null; - } - - final List> builder = new ArrayList<>(); - 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()); - } - return null; - } - - final TreeNode lazyObj = codec.deserialize(data); - final InstanceIdentifier bindingPath = InstanceIdentifier.create(builder); - return new SimpleEntry<>(bindingPath, lazyObj); - } - - @Nullable - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Notification fromNormalizedNodeNotification(@Nonnull final SchemaPath path, - @Nonnull final ContainerNode data) { - final NotificationCodecContext codec = codecContext.getNotificationContext(path); - return codec.deserialize(data); - } - - @Nullable - @Override - public TreeNode fromNormalizedNodeOperationData(@Nonnull final SchemaPath path, @Nonnull final ContainerNode data) { - final OperationInputCodec codec = codecContext.getOperationInputCodec(path); - return codec.deserialize(data); - } - - @Nonnull - @Override - public Entry - newWriterAndIdentifier(@Nonnull final InstanceIdentifier path, - @Nonnull final NormalizedNodeStreamWriter domWriter) { - return codecContext.newWriter(path, domWriter); - } - - @Nonnull - @Override - public BindingStreamEventWriter newWriter(@Nonnull final InstanceIdentifier path, - @Nonnull final NormalizedNodeStreamWriter domWriter) { - return codecContext.newWriterWithoutIdentifier(path, domWriter); - } - - @Nonnull - @Override - public BindingStreamEventWriter newNotificationWriter(@Nonnull final Class> notification, - @Nonnull final NormalizedNodeStreamWriter domWriter) { - return codecContext.newNotificationWriter(notification, domWriter); - } - - @Nonnull - @Override - public BindingStreamEventWriter newOperationWriter( - @Nonnull final Class> operationInputOrOutput, - @Nonnull final NormalizedNodeStreamWriter domWriter) { - return codecContext.newOperationWriter(operationInputOrOutput, domWriter); - } - - /** - * Deserialize function based on tree node codec context resolved by binding path. - * - * @param path - * - binding identifier - * @return function deserializer of codec context of binding path - */ - public Function>, Optional> - deserializeFunction(final InstanceIdentifier path) { - final TreeNodeCodecContext ctx = - (TreeNodeCodecContext) codecContext.getCodecContextNode(path, null); - return new DeserializeFunction<>(ctx); - } - - @Override - public BindingCodecContext create(final BindingRuntimeContext context) { - return new BindingCodecContext(context, this); - } - - @Override - @SuppressWarnings("checkstyle:illegalCatch") - public BindingCodecContext create(final SchemaContext context, final Class... bindingClasses) { - final ModuleInfoBackedContext strategy = ModuleInfoBackedContext.create(); - for (final Class bindingCls : bindingClasses) { - try { - strategy.registerModuleInfo(BindingReflections.getModuleInfo(bindingCls)); - } catch (final Exception e) { - throw new IllegalStateException( - "Could not create BindingRuntimeContext from class " + bindingCls.getName(), e); - } - } - final BindingRuntimeContext runtimeCtx = BindingRuntimeContext.create(strategy, context); - return create(runtimeCtx); - } - - private static final class DeserializeFunction implements Function>, Optional> { - private final TreeNodeCodecContext ctx; - - DeserializeFunction(final TreeNodeCodecContext ctx) { - this.ctx = ctx; - } - - @Nullable - @SuppressWarnings("unchecked") - @Override - public Optional apply(@Nullable final Optional> input) { - if (input.isPresent()) { - return Optional.of((T) ctx.deserialize(input.get())); - } - return Optional.empty(); - } - } - - private final class GeneratorLoader extends CacheLoader, TreeNodeSerializer> { - @Override - public TreeNodeSerializer load(final Class key) throws Exception { - final TreeNodeSerializerImplementation prototype = generator.getSerializer(key); - return new TreeNodeSerializerProxy(prototype); - } - } - - private final class TreeNodeSerializerProxy - implements TreeNodeSerializer, Delegator { - private final TreeNodeSerializerImplementation delegate; - - TreeNodeSerializerProxy(final TreeNodeSerializerImplementation delegate) { - this.delegate = delegate; - } - - @Override - public TreeNodeSerializerImplementation getDelegate() { - return delegate; - } - - @Override - public void serialize(final TreeNode obj, final BindingStreamEventWriter stream) throws IOException { - delegate.serialize(BindingNormalizedNodeCodecRegistry.this, obj, stream); - } - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingToNormalizedNodeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingToNormalizedNodeCodec.java deleted file mode 100644 index c59f2510a7..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/BindingToNormalizedNodeCodec.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.ImmutableBiMap; -import java.lang.reflect.Method; -import java.util.AbstractMap.SimpleEntry; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory.BindingTreeCodecFactory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException; -import org.opendaylight.yangtools.yang.data.impl.schema.Builders; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes; -import org.opendaylight.yangtools.yang.model.api.ActionDefinition; -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.OperationDefinition; -import org.opendaylight.yangtools.yang.model.api.RpcDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContextListener; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Codec for serialize/deserialize Binding and DOM data. - */ -@Beta -public final class BindingToNormalizedNodeCodec - implements BindingTreeCodecFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable { - - private static final long WAIT_DURATION_SEC = 5; - private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class); - - private final BindingNormalizedNodeCodecRegistry codecRegistry; - private final GeneratedClassLoadingStrategy classLoadingStrategy; - private final FutureSchema futureSchema; - private final LoadingCache, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder() - .softValues().build(new CacheLoader, YangInstanceIdentifier>() { - - @Override - public YangInstanceIdentifier load(@Nonnull final InstanceIdentifier key) throws Exception { - return toYangInstanceIdentifierBlocking(key); - } - - }); - - private volatile BindingRuntimeContext runtimeContext; - - /** - * Init class without waiting for schema. - * - * @param classLoadingStrategy - * - class loader - * @param codecRegistry - * - codec registry - */ - public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy, - final BindingNormalizedNodeCodecRegistry codecRegistry) { - this(classLoadingStrategy, codecRegistry, false); - } - - /** - * Init class with waiting for schema. - * - * @param classLoadingStrategy - * - class loader - * @param codecRegistry - * - codec registry - * @param waitForSchema - * - boolean of waiting for schema - */ - public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy, - final BindingNormalizedNodeCodecRegistry codecRegistry, final boolean waitForSchema) { - this.classLoadingStrategy = requireNonNull(classLoadingStrategy, "classLoadingStrategy"); - this.codecRegistry = requireNonNull(codecRegistry, "codecRegistry"); - this.futureSchema = waitForSchema ? new FutureSchema(WAIT_DURATION_SEC, TimeUnit.SECONDS) : null; - } - - /** - * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier with waiting - * for schema. - * - * @param binding - * - Binding Instance Identifier - * @return DOM Instance Identifier - */ - public YangInstanceIdentifier toYangInstanceIdentifierBlocking( - final InstanceIdentifier binding) { - try { - return codecRegistry.toYangInstanceIdentifier(binding); - } catch (final MissingSchemaException e) { - waitForSchema(decompose(binding), e); - return codecRegistry.toYangInstanceIdentifier(binding); - } - } - - /** - * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier. - * - * @param binding - * - Binding Instance Identifier - * @return DOM Instance Identifier - * @throws IllegalArgumentException - * If supplied Instance Identifier is not valid. - */ - public YangInstanceIdentifier toNormalized(final InstanceIdentifier binding) { - return codecRegistry.toYangInstanceIdentifier(binding); - } - - @Nullable - @Override - public YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull final InstanceIdentifier binding) { - return codecRegistry.toYangInstanceIdentifier(binding); - } - - /** - * Get cached DOM identifier of Binding identifier. - * - * @param binding - * - binding identifier - * @return DOM identifier - */ - public YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier binding) { - return iiCache.getUnchecked(binding); - } - - @Nullable - @Override - public Entry> - toNormalizedNode(final InstanceIdentifier path, final T data) { - try { - return codecRegistry.toNormalizedNode(path, data); - } catch (final MissingSchemaException e) { - waitForSchema(decompose(path), e); - return codecRegistry.toNormalizedNode(path, data); - } - } - - /** - * Converts Binding Map.Entry to DOM Map.Entry. - * - *

- * Same as {@link #toNormalizedNode(InstanceIdentifier, TreeNode)}. - * - * @param binding - * Map Entry with InstanceIdentifier as key and DataObject as value. - * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode} as value. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Nullable - public Entry> - toNormalizedNode(final Entry, TreeNode> binding) { - return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue()); - } - - @Nullable - @Override - public Entry, TreeNode> fromNormalizedNode(@Nonnull final YangInstanceIdentifier path, - final NormalizedNode data) { - return codecRegistry.fromNormalizedNode(path, data); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Nullable - @Override - public Notification fromNormalizedNodeNotification(@Nonnull final SchemaPath path, - @Nonnull final ContainerNode data) { - return codecRegistry.fromNormalizedNodeNotification(path, data); - } - - @Nullable - @Override - public TreeNode fromNormalizedNodeOperationData(@Nonnull final SchemaPath path, @Nonnull final ContainerNode data) { - return codecRegistry.fromNormalizedNodeOperationData(path, data); - } - - @Nullable - @Override - public InstanceIdentifier fromYangInstanceIdentifier(@Nonnull final YangInstanceIdentifier dom) { - return codecRegistry.fromYangInstanceIdentifier(dom); - } - - @SuppressWarnings("rawtypes") - @Nonnull - @Override - public ContainerNode toNormalizedNodeNotification(@Nonnull final Notification data) { - return codecRegistry.toNormalizedNodeNotification(data); - } - - @Nonnull - @Override - public ContainerNode toNormalizedNodeOperationData(@Nonnull final TreeNode data) { - return codecRegistry.toNormalizedNodeOperationData(data); - } - - /** - * Returns a Binding-Aware instance identifier from normalized instance-identifier if it is possible to - * create representation. - * - *

- * Returns Optional.empty for cases where target is mixin node except augmentation. - * - */ - public Optional> toBinding(final YangInstanceIdentifier normalized) - throws DeserializationException { - try { - return Optional.ofNullable(codecRegistry.fromYangInstanceIdentifier(normalized)); - } catch (final IllegalArgumentException e) { - return Optional.empty(); - } - } - - /** - * DOM to Binding. - * - * @param normalized - * - DOM object - * @return Binding object - * @throws DeserializationException - * If fail to deserialize - */ - @SuppressWarnings("unchecked") - public Optional, TreeNode>> - toBinding(@Nonnull final Entry> normalized) - throws DeserializationException { - try { - final Entry, TreeNode> binding = - Entry.class.cast(codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue())); - return Optional.ofNullable(binding); - } catch (final IllegalArgumentException e) { - return Optional.empty(); - } - } - - @Override - public void onGlobalContextUpdated(final SchemaContext arg0) { - runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, arg0); - codecRegistry.onBindingRuntimeContextUpdated(runtimeContext); - if (futureSchema != null) { - futureSchema.onRuntimeContextUpdated(runtimeContext); - } - } - - /** - * Prepare deserialize function of Binding identifier to DOM. - * - * @param path - * - Binding identifier - * @return DOM function - */ - public Function>, Optional> - deserializeFunction(final InstanceIdentifier path) { - return codecRegistry.deserializeFunction(path); - } - - /** - * Get codec registry. - * - * @return codec registry - */ - public BindingNormalizedNodeCodecRegistry getCodecRegistry() { - return codecRegistry; - } - - @Override - public void close() { - // NOOP Intentionally - } - - /** - * Get codec factory. - * - * @return codec factory - */ - public BindingNormalizedNodeCodecRegistry getCodecFactory() { - return codecRegistry; - } - - /** - * Resolve method with path of specific RPC as binding object. - * - * @param key - * - RPC as binding object - * @return map of method with path of specific RPC - */ - @Deprecated - public ImmutableBiMap getRPCMethodToSchemaPath(final Class key) { - final Module module = getModuleBlocking(key); - final ImmutableBiMap.Builder ret = ImmutableBiMap.builder(); - try { - for (final RpcDefinition rpcDef : module.getRpcs()) { - final Method method = runtimeContext.findOperationMethod(key, rpcDef); - ret.put(method, rpcDef.getPath()); - } - } catch (final NoSuchMethodException e) { - throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e); - } - return ret.build(); - } - - /** - * Get Action schema path. - * - * @param type - * - Action implementation class type - * @return schema path of Action - */ - public SchemaPath getActionPath(final Class> type) { - final ActionDefinition schema = runtimeContext.getActionDefinition(type); - checkArgument(schema != null, "Failed to find schema for %s", type); - return schema.getPath(); - } - - /** - * Get RPC schema path. - * - * @param type - * - RPC implementation class type - * @return schema path of RPC - */ - public SchemaPath getRpcPath(final Class> type) { - final RpcDefinition schema = runtimeContext.getRpcDefinition(type); - checkArgument(schema != null, "Failed to find schema for %s", type); - return schema.getPath(); - } - - public RpcDefinition getRpcDefinition(final Class> type) { - final RpcDefinition schema = runtimeContext.getRpcDefinition(type); - checkArgument(schema != null, "Failed to find schema for %s", type); - return schema; - } - - /** - * Resolve method with definition of specific RPC as binding object. - * - * @param key - * - RPC as binding object - * @return map of method with definition of specific RPC - */ - public ImmutableBiMap getRPCMethodToSchema(final Class key) { - final Module module = getModuleBlocking(key); - final ImmutableBiMap.Builder ret = ImmutableBiMap.builder(); - try { - for (final RpcDefinition rpcDef : module.getRpcs()) { - final Method method = runtimeContext.findOperationMethod(key, rpcDef); - ret.put(method, rpcDef); - } - } catch (final NoSuchMethodException e) { - throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e); - } - return ret.build(); - } - - /** - * Resolve method with definition of specific action as binding object. - * - * @param key - * - action as binding object - * @return map of method with definition of specific action - */ - public ImmutableBiMap getActionMethodToSchema(final Class key) { - final Module module = getModuleBlocking(key); - final ImmutableBiMap.Builder ret = ImmutableBiMap.builder(); - try { - for (final ActionDefinition actionDefinition : runtimeContext.getSchemaContext().getActions()) { - final QName qName = actionDefinition.getQName(); - if (qName.getModule().equals(module.getQNameModule())) { - final Method method = runtimeContext.findOperationMethod(key, actionDefinition); - ret.put(method, actionDefinition); - } - } - } catch (final NoSuchMethodException e) { - throw new IllegalStateException("Action defined in model does not have representation in generated class.", - e); - } - return ret.build(); - } - - private Module getModuleBlocking(final Class modeledClass) { - final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass); - BindingRuntimeContext localRuntimeContext = runtimeContext; - Module module = localRuntimeContext == null ? null - : localRuntimeContext.getSchemaContext().findModule(moduleName).get(); - if (module == null && futureSchema != null && futureSchema.waitForSchema(moduleName)) { - localRuntimeContext = runtimeContext; - Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available."); - module = localRuntimeContext.getSchemaContext().findModule(moduleName).get(); - } - Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass); - return module; - } - - private void waitForSchema(final Collection> binding, final MissingSchemaException exception) { - if (futureSchema != null) { - LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(), - futureSchema.getUnit()); - if (!futureSchema.waitForSchema(binding)) { - return; - } - } - throw exception; - } - - @Override - public BindingTreeCodec create(final BindingRuntimeContext context) { - return codecRegistry.create(context); - } - - @Override - public BindingTreeCodec create(final SchemaContext context, final Class... bindingClasses) { - return codecRegistry.create(context, bindingClasses); - } - - /** - * Get subtree codec of DOM identifier. - * - * @param domIdentifier - * - DOM identifier - * @return codec for subtree - */ - @Nonnull - public Map.Entry, BindingTreeNodeCodec> - getSubtreeCodec(final YangInstanceIdentifier domIdentifier) { - - final BindingTreeCodec currentCodecTree = codecRegistry.getCodecContext(); - final InstanceIdentifier bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier); - checkArgument(bindingPath != null); - /** - * If we are able to deserialize YANG instance identifier, getSubtreeCodec must return non-null value. - */ - final BindingTreeNodeCodec codecContext = currentCodecTree.getSubtreeCodec(bindingPath); - return new SimpleEntry<>(bindingPath, codecContext); - } - - /** - * Get specific notification classes as Binding objects. - * - * @param interested - * - set of specific notifications paths - * @return notification as Binding objects according to input set of their DOM paths - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Set> getNotificationClasses(final Set interested) { - final Set> result = new HashSet<>(); - final Set knownNotifications = runtimeContext.getSchemaContext().getNotifications(); - for (final NotificationDefinition notification : knownNotifications) { - if (interested.contains(notification.getPath())) { - try { - result.add((Class) runtimeContext.getClassForSchema(notification)); - } catch (final IllegalStateException e) { - // Ignore - LOG.warn("Class for {} is currently not known.", notification.getPath(), e); - } - } - } - return result; - } - - private static Collection> decompose(final InstanceIdentifier path) { - final Set> clazzes = new HashSet<>(); - for (final TreeArgument arg : path.getPathArguments()) { - clazzes.add(arg.getType()); - } - return clazzes; - } - - /** - * Resolve DOM object on specific DOM identifier. - * - * @param parentPath - * - DOM identifier - * @return DOM object - */ - public NormalizedNode instanceIdentifierToNode(final YangInstanceIdentifier parentPath) { - return ImmutableNodes.fromInstanceId(runtimeContext.getSchemaContext(), parentPath); - } - - /** - * Get default DOM object on path for list. - * - * @param parentMapPath - * - path - * @return specific DOM object - */ - public NormalizedNode getDefaultNodeFor(final YangInstanceIdentifier parentMapPath) { - final BindingTreeNodeCodec mapCodec = codecRegistry.getCodecContext().getSubtreeCodec(parentMapPath); - final Object schema = mapCodec.getSchema(); - if (schema instanceof ListSchemaNode) { - final ListSchemaNode castedSchema = (ListSchemaNode) schema; - if (castedSchema.isUserOrdered()) { - return Builders.orderedMapBuilder(castedSchema).build(); - } else { - return Builders.mapBuilder(castedSchema).build(); - } - } - throw new IllegalArgumentException("Path does not point to list schema node"); - } - - /** - * Binding subtree identifiers to DOM subtree identifiers. - * - * @param subtrees - * - binding subtree - * @return DOM subtree - */ - public Collection - toDOMDataTreeIdentifiers(final Collection> subtrees) { - final Set ret = new HashSet<>(subtrees.size()); - - for (final DataTreeIdentifier subtree : subtrees) { - ret.add(toDOMDataTreeIdentifier(subtree)); - } - return ret; - } - - //FIXME: avoid the duplication of the function above. - public

Set - toDOMDataTreeIdentifiers(final Set> subtrees) { - final Set ret = new HashSet<>(subtrees.size()); - - for (final DataTreeIdentifier subtree : subtrees) { - ret.add(toDOMDataTreeIdentifier(subtree)); - } - return ret; - } - - /** - * Create new DOM data tree identifier from Binding data tree identifier. - * - * @param path - * - binding data tree identifier - * @return DOM data tree identifier - */ - public DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier path) { - final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier()); - return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath); - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/FutureSchema.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/FutureSchema.java deleted file mode 100644 index fc1b634ec3..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/FutureSchema.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.annotations.Beta; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Predicate; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.yang.common.QNameModule; - -@Beta -class FutureSchema implements AutoCloseable { - - private final List postponedOperations = new CopyOnWriteArrayList<>(); - private final SettableFuture schemaPromise = SettableFuture.create(); - private final long duration; - private final TimeUnit unit; - - protected FutureSchema(final long time, final TimeUnit unit) { - this.duration = time; - this.unit = unit; - } - - void onRuntimeContextUpdated(final BindingRuntimeContext context) { - for (final FutureSchemaPredicate op : postponedOperations) { - op.unlockIfPossible(context); - } - } - - long getDuration() { - return duration; - } - - TimeUnit getUnit() { - return unit; - } - - @Override - public void close() { - for (final FutureSchemaPredicate op : postponedOperations) { - op.cancel(); - } - } - - private static boolean isSchemaAvailable(final Class clz, final BindingRuntimeContext context) { - final Object schema; - if (Augmentation.class.isAssignableFrom(clz)) { - schema = context.getAugmentationDefinition(clz); - } else { - schema = context.getSchemaDefinition(clz); - } - return schema != null; - } - - boolean waitForSchema(final QNameModule module) { - final FutureSchemaPredicate postponedOp = new FutureSchemaPredicate() { - @Override - public boolean test(final BindingRuntimeContext input) { - return input.getSchemaContext().findModule(module).isPresent(); - } - }; - return postponedOp.waitForSchema(); - } - - boolean waitForSchema(final Collection> bindingClasses) { - final FutureSchemaPredicate postponedOp = new FutureSchemaPredicate() { - @Override - public boolean test(final BindingRuntimeContext context) { - for (final Class clz : bindingClasses) { - if (!isSchemaAvailable(clz, context)) { - return false; - } - } - return true; - } - }; - return postponedOp.waitForSchema(); - } - - private abstract class FutureSchemaPredicate implements Predicate { - - final boolean waitForSchema() { - try { - schemaPromise.get(duration, unit); - return true; - } catch (final InterruptedException | ExecutionException e) { - throw new RuntimeException(e); - } catch (final TimeoutException e) { - return false; - } finally { - postponedOperations.remove(this); - } - } - - final void unlockIfPossible(final BindingRuntimeContext context) { - if (!schemaPromise.isDone() && test(context)) { - schemaPromise.set(null); - } - } - - final void cancel() { - schemaPromise.cancel(true); - } - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentifiableItemCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentifiableItemCodec.java deleted file mode 100644 index 5397e50ad4..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentifiableItemCodec.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.annotations.Beta; -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.reflect.Constructor; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ValueContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.concepts.Identifier; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; - -/** - * Codec for serialize/deserialize list. - */ -@Beta -public final class IdentifiableItemCodec implements Codec> { - - private final Map keyValueContexts; - private final List keysInBindingOrder; - private final ListSchemaNode schema; - private final Class identifiable; - private final MethodHandle ctorInvoker; - private final MethodHandle ctor; - - /** - * Prepare constructor of binding object of list with resolving key values if exists. - * - * @param schema - * - list schema node - * @param keyClass - * - binding class of key - * @param identifiable - * - binding class of list - * @param keyValueContexts - * - key value contexts - */ - public IdentifiableItemCodec(final ListSchemaNode schema, final Class keyClass, - final Class identifiable, final Map keyValueContexts) { - this.schema = schema; - this.identifiable = identifiable; - - try { - ctor = MethodHandles.publicLookup().unreflectConstructor(getConstructor(keyClass)); - } catch (final IllegalAccessException e) { - throw new IllegalArgumentException("Missing construct in class " + keyClass, e); - } - final MethodHandle inv = MethodHandles.spreadInvoker(ctor.type(), 0); - this.ctorInvoker = inv.asType(inv.type().changeReturnType(Identifier.class)); - - /* - * We need to re-index to make sure we instantiate nodes in the order in which they are defined. - */ - final Map keys = new LinkedHashMap<>(); - for (final QName qname : schema.getKeyDefinition()) { - 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 unsortedKeys = schema.getKeyDefinition(); - final List sortedKeys; - if (unsortedKeys.size() > 1) { - final List tmp = new ArrayList<>(unsortedKeys); - tmp.sort((q1, q2) -> q1.getLocalName().compareToIgnoreCase(q2.getLocalName())); - sortedKeys = tmp; - } else { - sortedKeys = unsortedKeys; - } - - this.keysInBindingOrder = ImmutableList.copyOf(sortedKeys); - } - - @Override - @SuppressWarnings("checkstyle:illegalCatch") - public IdentifiableItem deserialize(final NodeIdentifierWithPredicates input) { - final Object[] bindingValues = new Object[keysInBindingOrder.size()]; - int offset = 0; - - for (final QName key : keysInBindingOrder) { - final Object yangValue = input.getKeyValues().get(key); - bindingValues[offset++] = keyValueContexts.get(key).deserialize(yangValue); - } - - final Identifier identifier; - try { - identifier = (Identifier) ctorInvoker.invokeExact(ctor, bindingValues); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier); - return identifiableItem; - } - - @Override - public NodeIdentifierWithPredicates serialize(final IdentifiableItem input) { - final Object value = input.getKey(); - - final Map values = new LinkedHashMap<>(); - for (final Entry valueCtx : keyValueContexts.entrySet()) { - values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value)); - } - return new NodeIdentifierWithPredicates(schema.getQName(), values); - } - - @SuppressWarnings("unchecked") - private static Constructor getConstructor(final Class clazz) { - for (@SuppressWarnings("rawtypes") final Constructor constr : clazz.getConstructors()) { - final Class[] parameters = constr.getParameterTypes(); - if (!clazz.equals(parameters[0])) { - // It is not copy constructor; - return constr; - } - } - throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor."); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentityCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentityCodec.java deleted file mode 100644 index c514862749..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/IdentityCodec.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.yang.common.QName; - -/** - * Codec for serialize/deserialize identity. - */ -@Beta -public final class IdentityCodec implements Codec> { - - private final BindingRuntimeContext context; - - /** - * Prepared binding runtime context for identity codec. - * - * @param context - * - binding runtime context - */ - public IdentityCodec(final BindingRuntimeContext context) { - this.context = requireNonNull(context); - } - - @Override - public Class deserialize(final QName input) { - Preconditions.checkArgument(input != null, "Input must not be null."); - return context.getIdentityClass(input); - } - - @Override - public QName serialize(final Class input) { - Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input)); - return BindingReflections.findQName(input); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierCodec.java deleted file mode 100644 index dccbf1ce22..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierCodec.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.Iterables; -import java.util.ArrayList; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ListNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.BindingCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; - -/** - * Codec for serializer/deserialize DOM and binding identifiers. - * - */ -@Beta -public final class InstanceIdentifierCodec implements Codec> { - - private final BindingCodecContext context; - - /** - * Prepare codec context. - * - * @param context - * - binding codec context - */ - public InstanceIdentifierCodec(final BindingCodecContext context) { - this.context = requireNonNull(context); - } - - @Override - public YangInstanceIdentifier serialize(final InstanceIdentifier input) { - final List domArgs = new ArrayList<>(); - context.getCodecContextNode(input, domArgs); - return YangInstanceIdentifier.create(domArgs); - } - - @Override - public InstanceIdentifier deserialize(final YangInstanceIdentifier input) { - final List> builder = new ArrayList<>(); - final NodeCodecContext codec = context.getCodecContextNode(input, builder); - - if (codec == null) { - return null; - } - - if (codec instanceof ListNodeCodecContext && Iterables.getLast(builder) instanceof Item) { - // We ended up in list, but without key, which means it represent list as a whole, - // which is not binding representable. - return null; - } - - return InstanceIdentifier.create(builder); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/MissingSchemaException.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/MissingSchemaException.java deleted file mode 100644 index f002a29309..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/MissingSchemaException.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.base.Preconditions; -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.PathArgument; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -/** - * Thrown when codec was used with data which are not modeled - * and available in schema used by codec. - */ -public class MissingSchemaException extends IllegalArgumentException { - - private static final long serialVersionUID = 1L; - - protected MissingSchemaException(final String msg) { - super(msg); - } - - protected MissingSchemaException(final String msg, final Throwable cause) { - super(msg, cause); - } - - private static MissingSchemaException create(final String format, final Object... args) { - return new MissingSchemaException(String.format(format, args)); - } - - public static void checkModulePresent(final SchemaContext schemaContext, final QName name) { - if (!schemaContext.findModule(name.getModule()).isPresent()) { - throw MissingSchemaException.create("Module %s is not present in current schema context.",name.getModule()); - } - } - - public static void checkModulePresent(final SchemaContext schemaContext, final YangInstanceIdentifier.PathArgument - child) { - checkModulePresent(schemaContext, extractName(child)); - } - - private static QName extractName(final PathArgument child) { - if (child instanceof YangInstanceIdentifier.AugmentationIdentifier) { - final Set children = ((YangInstanceIdentifier.AugmentationIdentifier) child).getPossibleChildNames(); - Preconditions.checkArgument(!children.isEmpty(),"Augmentation without childs must not be used in data"); - return children.iterator().next(); - } - return child.getNodeType(); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodec.java deleted file mode 100644 index 939f50289c..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodec.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Non caching codec. - * - * @param - * - type of tree node - */ -@Beta -public class NonCachingCodec implements BindingNormalizedNodeCachingCodec { - - private final BindingNormalizedNodeCodec delegate; - - public NonCachingCodec(final BindingNormalizedNodeCodec delegate) { - this.delegate = delegate; - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - return delegate.deserialize(data); - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final D data) { - return delegate.serialize(data); - } - - @Override - public void close() { - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/OperationInputCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/OperationInputCodec.java deleted file mode 100644 index 5e82aa5a75..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/OperationInputCodec.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Marker interface for codecs dealing with operation input being potentially unmapped. We use this interface - * to mark both {@link UnmappedOperationInputCodec} and ContainerNodeCodecContext, which results in bimorphic - * invocation in BindingNormalizedNodeCodecRegistry. - * - *

- * Without this interface we could end up with megamorphic invocation, as the two implementations cannot share - * class hierarchy. - * - * @param - * - Binding representation of data - */ -@Beta -public interface OperationInputCodec extends BindingNormalizedNodeCodec { - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnionTypeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnionTypeCodec.java deleted file mode 100755 index 7c56dd7525..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnionTypeCodec.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer.normalizeSpecificIdentifier; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableSet; -import java.lang.reflect.Method; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.concurrent.Callable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.UnionValueOptionContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.BindingCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ReflectionBasedCodec; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.BaseYangTypes; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; -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.LeafrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; - -/** - * Codec for serialize/deserialize union type. - * - */ -@Beta -public final class UnionTypeCodec extends ReflectionBasedCodec { - - private final ImmutableSet typeCodecs; - - private UnionTypeCodec(final Class unionCls, final Set codecs) { - super(unionCls); - typeCodecs = ImmutableSet.copyOf(codecs); - } - - /** - * Loading union type codec for all subtypes of union. - * - * @param unionCls - * - binding class of union - * @param unionType - * - type definition of union - * @param bindingCodecContext - * - binding codec context - * @return union codec - */ - public static Callable loader(final Class unionCls, final UnionTypeDefinition unionType, - final BindingCodecContext bindingCodecContext) { - return () -> { - final Set values = new LinkedHashSet<>(); - for (final TypeDefinition subtype : unionType.getTypes()) { - if (subtype instanceof LeafrefTypeDefinition) { - addLeafrefValueCodec(unionCls, unionType, bindingCodecContext, values, subtype); - } else { - final Method valueGetter = unionCls.getMethod("get" - + normalizeSpecificIdentifier(subtype.getQName().getLocalName(), JavaIdentifier.CLASS)); - final Class valueType = valueGetter.getReturnType(); - final Codec valueCodec = bindingCodecContext.getCodec(valueType, subtype); - values.add(new UnionValueOptionContext(unionCls, valueType, valueGetter, valueCodec)); - } - } - return new UnionTypeCodec(unionCls, values); - }; - } - - /** - * Prepare codec for type from leaf's return type of leafref. - * - * @param unionCls - * - union class - * @param unionType - * - union type - * @param bindingCodecContext - * - binding codec context - * @param values - * - union values - * @param subtype - * - subtype of union - * @throws NoSuchMethodException when the getter method is not found - */ - private static void addLeafrefValueCodec(final Class unionCls, final UnionTypeDefinition unionType, - final BindingCodecContext bindingCodecContext, final Set values, - final TypeDefinition subtype) throws NoSuchMethodException { - final SchemaContext schemaContext = bindingCodecContext.getRuntimeContext().getSchemaContext(); - final Module module = schemaContext.findModule(subtype.getQName().getModule()).get(); - final RevisionAwareXPath xpath = ((LeafrefTypeDefinition) subtype).getPathStatement(); - // find schema node in schema context by xpath of leafref - final SchemaNode dataNode; - if (xpath.isAbsolute()) { - dataNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath); - } else { - dataNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, unionType, xpath); - } - - final LeafSchemaNode typeNode = (LeafSchemaNode) dataNode; - - // prepare name of type form return type of referenced leaf - final String typeName = BaseYangTypes.BASE_YANG_TYPES_PROVIDER - .javaTypeForSchemaDefinitionType(typeNode.getType(), typeNode, null).getName(); - - // get method via reflection from generated code according to - // get_TypeName_Value method - final String method = normalizeSpecificIdentifier(new StringBuilder("get").append("_") - .append(typeName).append(unionCls.getSimpleName()).append("Value").toString(), - JavaIdentifier.METHOD); - final Method valueGetterParent = unionCls.getMethod(method); - final Class returnType = valueGetterParent.getReturnType(); - - // prepare codec of union subtype according to return type of referenced - // leaf - final Codec valueCodec = bindingCodecContext.getCodec(returnType, subtype); - values.add(new UnionValueOptionContext(unionCls, returnType, valueGetterParent, valueCodec)); - } - - @Override - public Object deserialize(final Object input) { - for (final UnionValueOptionContext member : typeCodecs) { - final Object ret = member.deserializeUnion(input); - if (ret != null) { - return ret; - } - } - - throw new IllegalArgumentException( - String.format("Failed to construct instance of %s for input %s", getTypeClass(), input)); - } - - @Override - public Object serialize(final Object input) { - if (input != null) { - for (final UnionValueOptionContext valCtx : typeCodecs) { - final Object domValue = valCtx.serialize(input); - if (domValue != null) { - return domValue; - } - } - } - return null; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnmappedOperationInputCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnmappedOperationInputCodec.java deleted file mode 100644 index 20d9c18f2b..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/UnmappedOperationInputCodec.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Singleton codec for translating operations with implicit input statements, which are not mapped by binding - * spec v2. Since there is no equivalent, we always return null. - * - * @param - * - TreeNode type - */ -@Beta -public final class UnmappedOperationInputCodec implements OperationInputCodec { - - private static final UnmappedOperationInputCodec INSTANCE = new UnmappedOperationInputCodec<>(); - - private UnmappedOperationInputCodec() { - - } - - @SuppressWarnings("unchecked") - public static UnmappedOperationInputCodec getInstance() { - return (UnmappedOperationInputCodec) INSTANCE; - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - return null; - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final D data) { - throw new UnsupportedOperationException("Serialization of " + data + " not supported"); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/AbstractBindingNormalizedNodeCacheHolder.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/AbstractBindingNormalizedNodeCacheHolder.java deleted file mode 100644 index f155b8c37f..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/AbstractBindingNormalizedNodeCacheHolder.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Abstract Holder of Binding to Normalized Node caches indexed by - * {@link DataContainerCodecContext} to which cache is associated. - * - */ -@Beta -public abstract class AbstractBindingNormalizedNodeCacheHolder { - - private final Set> cachedValues; - private final LoadingCache, BindingNormalizedNodeCache> caches = CacheBuilder - .newBuilder().build(new CacheLoader, BindingNormalizedNodeCache>() { - - @Override - public BindingNormalizedNodeCache load(@Nonnull final DataContainerCodecContext key) - throws Exception { - return new BindingNormalizedNodeCache(AbstractBindingNormalizedNodeCacheHolder.this, key); - } - - }); - - protected AbstractBindingNormalizedNodeCacheHolder(@Nonnull final Set> cacheSpec) { - cachedValues = requireNonNull(cacheSpec); - } - - public BindingNormalizedNodeCache getCachingSerializer(final DataContainerCodecContext childCtx) { - if (isCached(childCtx.getBindingClass())) { - return caches.getUnchecked(childCtx); - } - return null; - } - - /** - * Check if specific type is cached. - * - * @param type - * - type for check - * @return true if type is cached, false otherwise - */ - public boolean isCached(final Class type) { - return cachedValues.contains(type); - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/BindingNormalizedNodeCache.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/BindingNormalizedNodeCache.java deleted file mode 100644 index 84561ad2a0..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/BindingNormalizedNodeCache.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.CachingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Cached NormalizedNode representation of TreeNode. - */ -@Beta -public class BindingNormalizedNodeCache extends CacheLoader> { - - @SuppressWarnings("rawtypes") - private final DataContainerCodecContext subtreeRoot; - private final AbstractBindingNormalizedNodeCacheHolder cacheHolder; - private final LoadingCache> cache = - CacheBuilder.newBuilder().weakValues().build(this); - - public BindingNormalizedNodeCache(@Nonnull final AbstractBindingNormalizedNodeCacheHolder cacheHolder, - @Nonnull final DataContainerCodecContext subtreeRoot) { - this.cacheHolder = requireNonNull(cacheHolder, "cacheHolder"); - this.subtreeRoot = requireNonNull(subtreeRoot, "subtreeRoot"); - } - - @Override - public NormalizedNode load(@Nonnull final TreeNode key) throws Exception { - return CachingNormalizedNodeSerializer.serializeUsingStreamWriter(cacheHolder, subtreeRoot, key); - } - - /** - * Returns cached NormalizedNode representation of TreeNode. - * - *

- * If representation is not cached, serializes TreeNode and updates cache - * with representation. - * - * @param obj - * - binding object to be deserialized - * @return NormalizedNode representation of binding object - */ - public NormalizedNode get(final TreeNode obj) { - return cache.getUnchecked(obj); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/CachingNormalizedNodeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/CachingNormalizedNodeCodec.java deleted file mode 100644 index e0b83261e8..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/cache/CachingNormalizedNodeCodec.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.CachingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -/** - * Caching codec. - * - * @param - * - type of tree node - */ -@Beta -public class CachingNormalizedNodeCodec extends AbstractBindingNormalizedNodeCacheHolder - implements BindingNormalizedNodeCachingCodec { - - private final DataContainerCodecContext context; - - public CachingNormalizedNodeCodec(final DataContainerCodecContext subtreeRoot, - final Set> cacheSpec) { - super(cacheSpec); - this.context = requireNonNull(subtreeRoot); - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - return context.deserialize(data); - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final D data) { - return CachingNormalizedNodeSerializer.serialize(this, context, data); - } - - @Override - public void close() { - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/AugmentationNodeContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/AugmentationNodeContext.java deleted file mode 100644 index 2dd6c95cd5..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/AugmentationNodeContext.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -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.AugmentationSchemaNode; - -/** - * Context for prototype of augmentation node. - * - * @param - * - type of tree node - */ -@Beta -public final class AugmentationNodeContext> - extends TreeNodeCodecContext { - - /** - * Prepare context for augmentation node from prototype. - * - * @param prototype - * - codec prototype of augmentation node - */ - public AugmentationNodeContext(final DataContainerCodecPrototype prototype) { - super(prototype); - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode normalizedNode) { - Preconditions.checkArgument(normalizedNode instanceof AugmentationNode); - return createBindingProxy((AugmentationNode) normalizedNode); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - return deserialize(normalizedNode); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/CaseNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/CaseNodeCodecContext.java deleted file mode 100644 index 963f47589b..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/CaseNodeCodecContext.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.util.List; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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.ChoiceNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; - -/** - * Codec context for serializing and deserializing choice case node and it's - * path. - * - * @param - * - type of tree node - */ -@Beta -public final class CaseNodeCodecContext extends TreeNodeCodecContext { - - /** - * Prepare context for choice case node from prototype. - * - * @param prototype - * - codec prototype of choice case node - */ - public CaseNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - } - - @SuppressWarnings("rawtypes") - @Override - protected void addYangPathArgument(final TreeArgument arg, final List builder) { - // add your implementation - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode normalizedNode) { - Preconditions.checkState(normalizedNode instanceof ChoiceNode); - return createBindingProxy((ChoiceNode) normalizedNode); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - return deserialize(normalizedNode); - } - - @SuppressWarnings("rawtypes") - @Override - public PathArgument serializePathArgument(final TreeArgument arg) { - Preconditions.checkArgument(arg == null); - return null; - } - - @SuppressWarnings("rawtypes") - @Override - public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(arg == null); - return null; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ChoiceNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ChoiceNodeCodecContext.java deleted file mode 100644 index e2c87b5c50..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ChoiceNodeCodecContext.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -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.Optional; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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.ChoiceNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; -import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Context for prototype of choice node codec. - * - * @param - * - type of tree node - */ -@Beta -public class ChoiceNodeCodecContext extends DataContainerCodecContext { - - private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class); - - private final ImmutableMap> byYangCaseChild; - private final ImmutableMap, DataContainerCodecPrototype> byClass; - private final ImmutableMap, DataContainerCodecPrototype> byCaseChildClass; - - /** - * Prepare context for choice node from prototype and all case children of choice class. - * - * @param prototype - * - codec prototype of choice node - */ - public ChoiceNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - final Map> byYangCaseChildBuilder = - new HashMap<>(); - final Map, DataContainerCodecPrototype> byClassBuilder = new HashMap<>(); - final Map, DataContainerCodecPrototype> byCaseChildClassBuilder = new HashMap<>(); - final Set> potentialSubstitutions = new HashSet<>(); - - //TODO: Collect all choice/cases' descendant data children including augmented data nodes. - // Walks all cases for supplied choice in current runtime context - for (final Class caze : factory().getRuntimeContext().getCases(getBindingClass())) { - // We try to load case using exact match thus name - // and original schema must equals - final DataContainerCodecPrototype cazeDef = loadCase(caze); - // If we have case definition, this case is instantiated - // at current location and thus is valid in context of parent choice - if (cazeDef != null) { - byClassBuilder.put(cazeDef.getBindingClass(), cazeDef); - // Updates collection of case children - @SuppressWarnings("unchecked") - final Class> cazeCls = (Class>) caze; - for (final Class cazeChild : BindingReflections.getChildrenClasses(cazeCls)) { - byCaseChildClassBuilder.put(cazeChild, cazeDef); - } - // Updates collection of YANG instance identifier to case - for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) { - if (cazeChild.isAugmenting()) { - final AugmentationSchemaNode augment = - SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(), cazeChild); - if (augment != null) { - byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef); - continue; - } - } - byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef); - } - } else { - /* - * If case definition is not available, we store it for later check if it could be used as - * substitution of existing one. - */ - potentialSubstitutions.add(caze); - } - } - - final Map, DataContainerCodecPrototype> bySubstitutionBuilder = new HashMap<>(); - /* - * Walks all cases which are not directly instantiated and tries to match them to instantiated cases - - * represent same data as instantiated case, only case name or schema path is different. This is - * required due property of binding specification, that if choice is in grouping schema path location - * is lost, and users may use incorrect case class using copy builders. - */ - for (final Class substitution : potentialSubstitutions) { - for (final Entry, DataContainerCodecPrototype> real : byClassBuilder.entrySet()) { - if (BindingReflections.isSubstitutionFor(substitution, real.getKey())) { - bySubstitutionBuilder.put(substitution, real.getValue()); - break; - } - } - } - byClassBuilder.putAll(bySubstitutionBuilder); - byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder); - byClass = ImmutableMap.copyOf(byClassBuilder); - byCaseChildClass = ImmutableMap.copyOf(byCaseChildClassBuilder); - } - - @SuppressWarnings("unchecked") - @Nonnull - @Override - public DataContainerCodecContext streamChild(@Nonnull final Class childClass) { - final DataContainerCodecPrototype child = byClass.get(childClass); - return (DataContainerCodecContext) childNonNull(child, childClass, "Supplied class %s is not valid case", childClass).get(); - } - - @SuppressWarnings("unchecked") - @Override - public Optional> - possibleStreamChild(@Nonnull final Class childClass) { - final DataContainerCodecPrototype child = byClass.get(childClass); - if (child != null) { - return Optional.of((DataContainerCodecContext) child.get()); - } - return Optional.empty(); - } - - - /** - * Gets the map of case class and prototype for {@link - * org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext} - * to catch choice/cases' data child by class. - * - * @return the map of case class and prototype - */ - public Map, DataContainerCodecPrototype> getClassCaseChildren() { - return byCaseChildClass; - } - - - /** - * Gets the map of case path argument and prototype for {@link - * org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext} - * to catch choice/cases' data child by class. - * - * @return the the map of case path and prototype - */ - public Map> getYangCaseChildren() { - return byYangCaseChild; - } - - public DataContainerCodecContext getCaseByChildClass(final @Nonnull Class type) { - final DataContainerCodecPrototype protoCtx = - childNonNull(byCaseChildClass.get(type), type, "Class %s is not child of any cases for %s", type, - bindingArg()); - return protoCtx.get(); - } - - private DataContainerCodecPrototype loadCase(final Class childClass) { - final Optional childSchema = - factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(), childClass); - if (childSchema.isPresent()) { - return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory()); - } - - LOG.debug("Supplied class %s is not valid case in schema %s", childClass, getSchema()); - return null; - } - - @Nonnull - @Override - public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) { - final DataContainerCodecPrototype cazeProto; - if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) { - cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType())); - } else { - cazeProto = byYangCaseChild.get(arg); - } - - return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get() - .yangPathArgumentChild(arg); - } - - @SuppressWarnings("unchecked") - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - Preconditions.checkArgument(data instanceof ChoiceNode); - final NormalizedNodeContainer> casted = - (NormalizedNodeContainer>) data; - final NormalizedNode first = Iterables.getFirst(casted.getValue(), null); - - if (first == null) { - return null; - } - final DataContainerCodecPrototype caze = byYangCaseChild.get(first.getIdentifier()); - return (D) caze.get().deserialize(data); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - return deserialize(normalizedNode); - } - - @Nonnull - @Override - public TreeArgument deserializePathArgument(@Nonnull final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(getDomPathArgument().equals(arg)); - return null; - } - - @Nonnull - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(@Nonnull final TreeArgument arg) { - return getDomPathArgument(); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ContainerNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ContainerNodeCodecContext.java deleted file mode 100644 index 635f278dce..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ContainerNodeCodecContext.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.OperationInputCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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; - -/** - * Context for prototype of container node. - * - * @param - * - type of tree node - */ -@Beta -public class ContainerNodeCodecContext extends TreeNodeCodecContext - implements OperationInputCodec { - - /** - * Prepare context for container node from prototype. - * - * @param prototype - * - codec prototype of container node - */ - public ContainerNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - Preconditions.checkState(data instanceof ContainerNode); - return createBindingProxy((ContainerNode) data); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - return deserialize(normalizedNode); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/KeyedListNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/KeyedListNodeCodecContext.java deleted file mode 100644 index fe805f5832..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/KeyedListNodeCodecContext.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import java.lang.reflect.Method; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.concepts.Identifiable; -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.api.schema.MapEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; - -/** - * Codec context for serializing and deserializing keyed list node and it's - * path. - * - * @param - * - type of tree node - */ -@Beta -public final class KeyedListNodeCodecContext> extends ListNodeCodecContext { - - private final Codec> codec; - private final Method keyGetter; - - /** - * Prepare context for keyed list node from prototype. - * - * @param prototype - * - codec prototype of keyed list node - */ - public KeyedListNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - this.codec = factory().getPathArgumentCodec(getBindingClass(), getSchema()); - try { - this.keyGetter = getBindingClass().getMethod("getIdentifier"); - } catch (final NoSuchMethodException e) { - throw new IllegalStateException("Required method not available", e); - } - } - - @SuppressWarnings("rawtypes") - @Override - public void addYangPathArgument(final TreeArgument arg, final List builder) { - /* - * DOM Instance Identifier for list is always represent by two entries - * one for map and one for children. This is also true for wildcarded - * instance identifiers - */ - if (builder == null) { - return; - } - - super.addYangPathArgument(arg, builder); - if (arg instanceof IdentifiableItem) { - builder.add(codec.serialize((IdentifiableItem) arg)); - } else { - // Adding wildcarded - super.addYangPathArgument(arg, builder); - } - } - - @Override - @SuppressWarnings("rawtypes") - public Object getBindingChildValue(final Method method, final NormalizedNodeContainer dom) { - if (dom instanceof MapEntryNode && keyGetter.equals(method)) { - final NodeIdentifierWithPredicates identifier = ((MapEntryNode) dom).getIdentifier(); - return codec.deserialize(identifier).getKey(); - } else { - return super.getBindingChildValue(method, dom); - } - } - - @Override - protected TreeArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) { - if (domArg instanceof NodeIdentifierWithPredicates) { - return codec.deserialize((NodeIdentifierWithPredicates) domArg); - } - return super.getBindingPathArgument(domArg); - } - - @SuppressWarnings("rawtypes") - public NodeIdentifierWithPredicates serialize(final IdentifiableItem keyValues) { - return codec.serialize(keyValues); - } - - @SuppressWarnings("rawtypes") - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) { - if (arg instanceof IdentifiableItem) { - return codec.serialize((IdentifiableItem) arg); - } - return super.serializePathArgument(arg); - } - - @SuppressWarnings("rawtypes") - @Override - public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) { - if (arg instanceof NodeIdentifierWithPredicates) { - return codec.deserialize((NodeIdentifierWithPredicates) arg); - } - return super.deserializePathArgument(arg); - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ListNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ListNodeCodecContext.java deleted file mode 100644 index e98ab26615..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ListNodeCodecContext.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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.UnkeyedListEntryNode; -import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; - -/** - * Codec context for serializing and deserializing list node. - * - * @param - * - type of tree node - */ -@Beta -public class ListNodeCodecContext extends TreeNodeCodecContext { - - /** - * Prepare context for list node from prototype. - * - * @param prototype - * - codec prototype of list node - */ - public ListNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - } - - @Nonnull - @Override - public D deserialize(@Nonnull 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(final NormalizedNode node) { - if (node instanceof MapNode) { - return fromMap((MapNode) node); - } else if (node instanceof MapEntryNode) { - return fromMapEntry((MapEntryNode) node); - } else if (node instanceof UnkeyedListNode) { - return fromUnkeyedList((UnkeyedListNode) node); - } else if (node instanceof UnkeyedListEntryNode) { - return fromUnkeyedListEntry((UnkeyedListEntryNode) node); - } else { - throw new IllegalStateException("Unsupported data type " + node.getClass()); - } - } - - private List fromMap(final MapNode nodes) { - final List ret = new ArrayList<>(nodes.getValue().size()); - for (final MapEntryNode node : nodes.getValue()) { - ret.add(fromMapEntry(node)); - } - return ret; - } - - private D fromMapEntry(final MapEntryNode node) { - return createBindingProxy(node); - } - - private D fromUnkeyedListEntry(final UnkeyedListEntryNode node) { - return createBindingProxy(node); - } - - private List fromUnkeyedList(final UnkeyedListNode nodes) { - // FIXME: Could be this lazy transformed list? - final List ret = new ArrayList<>(nodes.getValue().size()); - for (final UnkeyedListEntryNode node : nodes.getValue()) { - ret.add(fromUnkeyedListEntry(node)); - } - return ret; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/NotificationCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/NotificationCodecContext.java deleted file mode 100644 index eb04792cac..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/NotificationCodecContext.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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; - -/** - * Context for prototype of notification. - * - * @param - * - type of tree node - */ -@SuppressWarnings("rawtypes") -@Beta -public final class NotificationCodecContext - extends TreeNodeCodecContext { - - /** - * Prepare context for notification from prototype. - * - * @param key - * - binding class - * @param schema - * - schema of notification - * @param factory - * - codec context factory - */ - public NotificationCodecContext(final Class key, final NotificationDefinition schema, - final CodecContextFactory factory) { - super(DataContainerCodecPrototype.from(key, schema, factory)); - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode data) { - Preconditions.checkState(data instanceof ContainerNode); - return createBindingProxy((NormalizedNodeContainer) data); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - return deserialize(normalizedNode); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/SchemaRootCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/SchemaRootCodecContext.java deleted file mode 100644 index 5b8bdf8f9a..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/SchemaRootCodecContext.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.util.concurrent.UncheckedExecutionException; -import java.util.Iterator; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.OperationInputCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.UnmappedOperationInputCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecPrototype; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.QNameModule; -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.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.NotificationDefinition; -import org.opendaylight.yangtools.yang.model.api.OperationDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; -import org.opendaylight.yangtools.yang.model.api.meta.StatementSource; -import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; - -/** - * Creates RootNode from supplied CodecContextFactory and make operations with. - * - * @param - * - tree node type - */ -@Beta -public final class SchemaRootCodecContext extends DataContainerCodecContext { - - private final LoadingCache, DataContainerCodecContext> childrenByClass = - CacheBuilder.newBuilder().build(new CacheLoader, DataContainerCodecContext>() { - @Override - public DataContainerCodecContext load(final Class key) { - return createDataTreeChildContext(key); - } - }); - - private final LoadingCache, ContainerNodeCodecContext> operationDataByClass = - CacheBuilder.newBuilder().build(new CacheLoader, ContainerNodeCodecContext>() { - @Override - public ContainerNodeCodecContext load(final Class key) { - return createOperationDataContext(key); - } - }); - - private final LoadingCache, NotificationCodecContext> notificationsByClass = - CacheBuilder.newBuilder().build(new CacheLoader, NotificationCodecContext>() { - @Override - public NotificationCodecContext load(final Class key) { - return createNotificationDataContext(key); - } - }); - - private final LoadingCache> childrenByQName = - CacheBuilder.newBuilder().build(new CacheLoader>() { - @SuppressWarnings("unchecked") - @Override - public DataContainerCodecContext load(final QName qname) { - final DataSchemaNode childSchema = getSchema().getDataChildByName(qname); - childNonNull(childSchema, qname, "Argument %s is not valid child of %s", qname, getSchema()); - if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) { - @SuppressWarnings("rawtypes") - final Class childCls = factory().getRuntimeContext().getClassForSchema(childSchema); - return streamChild(childCls); - } - - throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass()); - } - }); - - private final LoadingCache> operationDataByPath = - CacheBuilder.newBuilder().build(new CacheLoader>() { - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public OperationInputCodec load(final SchemaPath key) { - final ContainerSchemaNode schema = getOperationDataSchema(getSchema(), key); - if (schema instanceof EffectiveStatement && ((EffectiveStatement) schema).getDeclared() - .getStatementSource() != StatementSource.DECLARATION) { - // This is an implicitly-defined input or output statement. We do not have a - // corresponding - // data representation, so we hard-wire it to null. - return UnmappedOperationInputCodec.getInstance(); - } - - final Class cls = factory().getRuntimeContext().getClassForSchema(schema); - return getOperation(cls); - } - }); - - /** - * Returns operation Input or Output Data container from operation definition. - * - * @param schema - * - SchemaContext in which lookup should be performed - * @param path - * - Schema path of operation input/output data container - * @return operation schema or null, if operation is not present in schema context. - */ - private ContainerSchemaNode getOperationDataSchema(final SchemaContext schema, final SchemaPath path) { - requireNonNull(schema, "Schema context must not be null."); - requireNonNull(path, "Schema path must not be null."); - final Iterator it = path.getPathFromRoot().iterator(); - Preconditions.checkArgument(it.hasNext(), "Operation must have QName."); - final QName operationName = it.next(); - Preconditions.checkArgument(it.hasNext(), "input or output must be part of path."); - final QName inOrOut = it.next(); - ContainerSchemaNode contSchemaNode = null; - if ((contSchemaNode = getOperationDataSchema(schema.getOperations(), operationName, inOrOut)) == null) { - contSchemaNode = getOperationDataSchema(schema.getActions(), operationName, inOrOut); - } - return contSchemaNode; - } - - private ContainerSchemaNode getOperationDataSchema(final Set operations, - final QName operationName, final QName inOrOut) { - for (final OperationDefinition potential : operations) { - if (operationName.equals(potential.getQName())) { - return getOperationDataSchema(potential, inOrOut); - } - } - return null; - } - - private ContainerSchemaNode getOperationDataSchema(final OperationDefinition operation, final QName qname) { - requireNonNull(operation, "Operation Schema must not be null."); - requireNonNull(qname, "QName must not be null."); - switch (qname.getLocalName()) { - case "input": - return operation.getInput(); - case "output": - return operation.getOutput(); - default: - throw new IllegalArgumentException( - "Supplied qname " + qname + " does not represent operation input or output."); - } - } - - private final LoadingCache> notificationsByPath = - CacheBuilder.newBuilder().build(new CacheLoader>() { - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public NotificationCodecContext load(final SchemaPath key) throws Exception { - final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(), key); - final Class clz = factory().getRuntimeContext().getClassForSchema(schema); - return getNotification(clz); - } - }); - - private SchemaRootCodecContext(final DataContainerCodecPrototype dataPrototype) { - super(dataPrototype); - } - - /** - * Creates RootNode from supplied CodecContextFactory. - * - * @param factory - * - CodecContextFactory - * @return schema root node - */ - public static SchemaRootCodecContext create(final CodecContextFactory factory) { - final DataContainerCodecPrototype prototype = DataContainerCodecPrototype.rootPrototype(factory); - return new SchemaRootCodecContext<>(prototype); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Nonnull - @Override - public DataContainerCodecContext streamChild(@Nonnull final Class childClass) - throws IllegalArgumentException { - /* - * FIXME: This is still not solved for operations TODO: Probably performance wise operations, Data and - * Notification loading cache should be merge for performance resons. Needs microbenchmark to - * determine which is faster (keeping them separate or in same cache). - */ - if (Notification.class.isAssignableFrom(childClass)) { - return (DataContainerCodecContext) getNotification((Class) childClass); - } - return (DataContainerCodecContext) getOrRethrow(childrenByClass, childClass); - } - - @Override - public Optional> - possibleStreamChild(@Nonnull final Class childClass) { - throw new UnsupportedOperationException("Not supported"); - } - - @Nonnull - @Override - public DataContainerCodecContext yangPathArgumentChild(final PathArgument arg) { - return getOrRethrow(childrenByQName, arg.getNodeType()); - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode normalizedNode) { - throw new UnsupportedOperationException("Could not create Binding data representation for root"); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - throw new UnsupportedOperationException("Unable to deserialize root"); - } - - @Nullable - @Override - public TreeArgument deserializePathArgument(@Nullable final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(arg == null); - return null; - } - - @Nullable - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(@Nullable final TreeArgument arg) { - Preconditions.checkArgument(arg == null); - return null; - } - - /** - * Get operation as binding object of binding class. - * - * @param operationInputOrOutput - * - binding class - * @return container node codec context of operation - */ - public ContainerNodeCodecContext getOperation(final Class> operationInputOrOutput) { - return getOrRethrow(operationDataByClass, operationInputOrOutput); - } - - /** - * Get operation input as binding object according to schema path of operation. - * - * @param operation - * - schema path of operation - * @return operation input codec of operation - */ - public OperationInputCodec getOperation(final SchemaPath operation) { - return getOrRethrow(operationDataByPath, operation); - } - - /** - * Get notification as binding object of binding class. - * - * @param notification - * - binding class - * @return notification codec context of notification - */ - @SuppressWarnings("rawtypes") - public NotificationCodecContext getNotification(final Class notification) { - return getOrRethrow(notificationsByClass, notification); - } - - /** - * Get notification as binding object according to schema path of notification. - * - * @param notification - * - schema path of notification - * @return notification codec context of notification - */ - public NotificationCodecContext getNotification(final SchemaPath notification) { - return getOrRethrow(notificationsByPath, notification); - } - - - - private DataContainerCodecContext createDataTreeChildContext(final Class key) { - final QName qname = BindingReflections.findQName(key); - final DataSchemaNode childSchema = - childNonNull(getSchema().getDataChildByName(qname), key, "%s is not top-level item.", key); - return DataContainerCodecPrototype.from(key, childSchema, factory()).get(); - } - - private ContainerNodeCodecContext createOperationDataContext(final Class key) { - Preconditions.checkArgument(Instantiable.class.isAssignableFrom(key)); - final QName qname = BindingReflections.findQName(key); - final QNameModule module = qname.getModule(); - OperationDefinition operation = null; - final SchemaContext schemaContext = getSchema(); - if ((operation = findPotentialOperation(schemaContext.getOperations(), module, key, qname)) == null) { - operation = findPotentialOperation(schemaContext.getActions(), module, key, qname); - } - Preconditions.checkArgument(operation != null, - "Supplied class %s is not valid operation class.", key); - final ContainerSchemaNode schema = getOperationDataSchema(operation, qname);// SchemaNodeUtils - // .getRpcDataSchema(operation, qname); - Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.", - operation.getQName()); - return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key, schema, factory()).get(); - } - - private OperationDefinition findPotentialOperation(final Set set, - final QNameModule module, final Class key, final QName qname) { - OperationDefinition operation = null; - for (final OperationDefinition potential : getSchema().getOperations()) { - final QName potentialQName = potential.getQName(); - /* - * Check if operation and class represents data from same module and then checks if operation - * local name produces same class name as class name appended with Input/Output based on QName - * associated with bidning class. - * - * FIXME: Rework this to have more precise logic regarding Binding Specification. - */ - final String moduleClassName = JavaIdentifierNormalizer - .normalizeSpecificIdentifier(potentialQName.getLocalName(), JavaIdentifier.CLASS); - final String keyClassName = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(qname.getLocalName(), JavaIdentifier.CLASS); - if (module.equals(potentialQName.getModule()) - && key.getSimpleName().equals(moduleClassName + keyClassName)) { - operation = potential; - break; - } - } - return operation; - } - - 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); - /** - * FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context to retrieve - * notification via index. - */ - final NotificationDefinition schema = - SchemaContextUtil.getNotificationSchema(getSchema(), SchemaPath.create(true, qname)); - Preconditions.checkArgument(schema != null, "Supplied %s is not valid notification", notificationType); - - return new NotificationCodecContext<>(notificationType, schema, factory()); - } - - private static V getOrRethrow(final LoadingCache cache, final K key) { - try { - return cache.getUnchecked(key); - } catch (final UncheckedExecutionException e) { - final Throwable cause = e.getCause(); - if (cause != null) { - Throwables.propagateIfPossible(cause); - } - throw e; - } - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContext.java deleted file mode 100644 index e9e125aa08..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContext.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Throwables; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.Method; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.EncapsulatedValueCodec; -import org.opendaylight.yangtools.concepts.Codec; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Context for serializing input value of union type and deserializing objects to binding. - * - */ -@Beta -public class UnionValueOptionContext { - - private static final Logger LOG = LoggerFactory.getLogger(UnionValueOptionContext.class); - - private static final MethodType OBJECT_TYPE = MethodType.methodType(Object.class, Object.class); - - private final Class bindingType; - private final Codec codec; - private final MethodHandle getter; - private final MethodHandle unionCtor; - - /** - * Prepare union as binding object and codec for this object, make a direct method handle of getting union - * type and constructor of union type for initializing it. - * - * @param unionType - * - union as binding object - * @param valueType - * - returned type of union - * @param getter - * - method for getting union type - * @param codec - * - codec for serialize/deserialize type of union - */ - public UnionValueOptionContext(final Class unionType, final Class valueType, final Method getter, - final Codec codec) { - this.bindingType = requireNonNull(valueType); - this.codec = requireNonNull(codec); - - try { - this.getter = MethodHandles.publicLookup().unreflect(getter).asType(OBJECT_TYPE); - } catch (final IllegalAccessException e) { - throw new IllegalStateException("Failed to access method " + getter, e); - } - - try { - this.unionCtor = MethodHandles.publicLookup() - .findConstructor(unionType, MethodType.methodType(void.class, valueType)).asType(OBJECT_TYPE); - } catch (IllegalAccessException | NoSuchMethodException e) { - throw new IllegalStateException( - String.format("Failed to access constructor for %s in type %s", valueType, unionType), e); - } - } - - /** - * Serialize input based on prepared codec. - * - * @param input - * - object to serialize - * @return serialized objetc - */ - public Object serialize(final Object input) { - final Object baValue = getValueFrom(input); - return baValue == null ? null : codec.serialize(baValue); - } - - /** - * Deserialize input object via prepared codec for invoking new object of union as binding. - * - * @param input - * - input object for deserializing - * @return deserialized union binding type object - */ - @SuppressWarnings("checkstyle:illegalCatch") - public Object deserializeUnion(final Object input) { - // Side-step potential exceptions by checking the type if it is available - if (codec instanceof EncapsulatedValueCodec && !((EncapsulatedValueCodec) codec).canAcceptObject(input)) { - return null; - } - - final Object value; - try { - value = codec.deserialize(input); - } catch (final Exception e) { - LOG.debug("Codec {} failed to deserialize input {}", codec, input, e); - return null; - } - - try { - return unionCtor.invokeExact(value); - } catch (final ClassCastException e) { - // This case can happen. e.g. NOOP_CODEC - LOG.debug("Failed to instantiate {} for input {} value {}", bindingType, input, value, e); - return null; - } catch (final Throwable e) { - throw new IllegalArgumentException("Failed to construct union for value " + value, e); - } - } - - @SuppressWarnings("checkstyle:illegalCatch") - private Object getValueFrom(final Object input) { - try { - return getter.invokeExact(input); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - } - - @Override - public int hashCode() { - return bindingType.hashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof UnionValueOptionContext)) { - return false; - } - - final UnionValueOptionContext other = (UnionValueOptionContext) obj; - return bindingType.equals(other.bindingType); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ValueContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ValueContext.java deleted file mode 100644 index 1be2087367..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/ValueContext.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.LeafNodeCodecContext; -import org.opendaylight.yangtools.concepts.Codec; - -/** - * Context for serialize/deserialize leaf. - */ -@Beta -public final class ValueContext { - - private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class); - private final Codec codec; - private final MethodHandle getter; - private final Class identifier; - private final String getterName; - - /** - * Prepare codec of leaf value and getter of binding leaf object for getting leaf. - * - * @param identifier - * - binding class - * @param leaf - * - leaf codec context - */ - public ValueContext(final Class identifier, final LeafNodeCodecContext leaf) { - getterName = leaf.getGetter().getName(); - try { - getter = MethodHandles.publicLookup().unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD); - } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) { - throw new IllegalStateException( - String.format("Cannot find method %s in class %s", getterName, identifier), e); - } - this.identifier = identifier; - codec = leaf.getValueCodec(); - } - - /** - * Get object via invoking getter with input and serializes it by prepared codec of leaf. - * - * @param obj - * - input object - * @return serialized invoked object - */ - @SuppressWarnings("checkstyle:illegalCatch") - public Object getAndSerialize(final Object obj) { - final Object value; - try { - value = getter.invokeExact(obj); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - - Preconditions.checkArgument(value != null, - "All keys must be specified for %s. Missing key is %s. Supplied key is %s", - identifier, getterName, obj); - return codec.serialize(value); - } - - /** - * Deserialize input object by prepared codec. - * - * @param obj - * - input object - * @return deserialized object - */ - public Object deserialize(final Object obj) { - return codec.deserialize(obj); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/AnyxmlNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/AnyxmlNodeCodecContext.java deleted file mode 100755 index db5bf5dc43..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/AnyxmlNodeCodecContext.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableCollection; -import java.lang.reflect.Method; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.concepts.Codec; -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.NormalizedNode; -import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -@Beta -public final class AnyxmlNodeCodecContext extends NodeCodecContext - implements NodeContextSupplier { - - private final YangInstanceIdentifier.PathArgument yangIdentifier; - private final Codec valueCodec; - private final Method getter; - private final DataSchemaNode schema; - - AnyxmlNodeCodecContext(final DataSchemaNode schema, final Codec codec, final Method getter, - final SchemaContext schemaContext) { - this.yangIdentifier = new YangInstanceIdentifier.NodeIdentifier(schema.getQName()); - this.valueCodec = requireNonNull(codec); - this.getter = requireNonNull(getter); - this.schema = requireNonNull(schema); - } - - @Override - public YangInstanceIdentifier.PathArgument getDomPathArgument() { - return yangIdentifier; - } - - public Codec getValueCodec() { - return valueCodec; - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode normalizedNode) { - throw new UnsupportedOperationException("Anyxml can not be deserialized to TreeNode"); - } - - @Nonnull - @Override - public NodeCodecContext get() { - return this; - } - - public Method getGetter() { - return getter; - } - - @Nonnull - @Override - public BindingTreeNodeCodec bindingPathArgumentChild(@Nonnull final TreeArgument arg, - final List builder) { - throw new IllegalArgumentException("Anyxml does not have children"); - } - - @Nonnull - @Override - public BindingNormalizedNodeCachingCodec createCachingCodec( - @Nonnull final ImmutableCollection> cacheSpecifier) { - throw new UnsupportedOperationException("Anyxml does not support caching codec."); - } - - @Nonnull - @Override - public Class getBindingClass() { - throw new UnsupportedOperationException("Anyxml does not have DataObject representation"); - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final D data) { - throw new UnsupportedOperationException("Separate serialization of Anyxml node is not supported."); - } - - @Override - public void writeAsNormalizedNode(final D data, final NormalizedNodeStreamWriter writer) { - throw new UnsupportedOperationException("Separate serialization of Anyxml node is not supported."); - } - - @Nonnull - @Override - public BindingTreeNodeCodec streamChild(@Nonnull final Class childClass) { - throw new IllegalArgumentException("Anyxml does not have children"); - } - - @Override - public Optional> possibleStreamChild( - @Nonnull final Class childClass) { - throw new IllegalArgumentException("Anyxml does not have children"); - } - - @Nonnull - @Override - public BindingTreeNodeCodec yangPathArgumentChild(final YangInstanceIdentifier.PathArgument child) { - throw new IllegalArgumentException("Anyxml does not have children"); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - if (normalizedNode instanceof AnyXmlNode) { - return valueCodec.deserialize(normalizedNode.getValue()); - } - return null; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(getDomPathArgument().equals(arg)); - return null; - } - - @SuppressWarnings("rawtypes") - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) { - return getDomPathArgument(); - } - - @Nonnull - @Override - public DataSchemaNode getSchema() { - return schema; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/BindingCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/BindingCodecContext.java deleted file mode 100644 index a3564d3d4f..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/BindingCodecContext.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.AbstractMap.SimpleEntry; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Callable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.xml.transform.dom.DOMSource; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.AnyxmlCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.IdentifiableItemCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.IdentityCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.InstanceIdentifierCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.OperationInputCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.UnionTypeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.CaseNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ListNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.NotificationCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.SchemaRootCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ValueContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext.CodecContextFactory; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.concepts.Identifier; -import org.opendaylight.yangtools.concepts.Immutable; -import org.opendaylight.yangtools.util.ClassLoaderUtils; -import org.opendaylight.yangtools.yang.common.Empty; -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.stream.NormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; -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.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -/** - * Binding codec context for holding runtime part and codecs. - */ -@Beta -public final class BindingCodecContext implements CodecContextFactory, BindingTreeCodec, Immutable { - - private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class); - - private final Codec> instanceIdentifierCodec; - private final Codec> identityCodec; - private final Codec anyxmlCodec; - private final BindingNormalizedNodeCodecRegistry registry; - private final BindingRuntimeContext context; - private final SchemaRootCodecContext root; - - /** - * Prepare runtime context and codec registry. - * - * @param context - * - runtime context - * @param registry - * - binding normalized node codec registry - */ - public BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) { - this.context = requireNonNull(context, "Binding Runtime Context is required."); - this.root = SchemaRootCodecContext.create(this); - this.identityCodec = new IdentityCodec(context); - this.anyxmlCodec = new AnyxmlCodec(context); - this.instanceIdentifierCodec = new InstanceIdentifierCodec(this); - this.registry = requireNonNull(registry); - } - - @Override - public BindingRuntimeContext getRuntimeContext() { - return context; - } - - /** - * Get instance identifier codec. - * - * @return instance identifier codec - */ - public Codec> getInstanceIdentifierCodec() { - return instanceIdentifierCodec; - } - - /** - * Get identity codec. - * - * @return identity codec - */ - public Codec> getIdentityCodec() { - return identityCodec; - } - - /** - * Get anyxml codec. - * - * @return anyxml codec - */ - public Codec getAnyxmlCodec() { - return anyxmlCodec; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public TreeNodeSerializer getEventStreamSerializer(final Class type) { - return registry.getSerializer((Class) type); - } - - /** - * Prepare specific writer for binding path. - * - * @param path - * - binding path - * @param domWriter - * - DOM writer - * @return entry of DOM path and writer - */ - public Entry newWriter(final InstanceIdentifier path, - final NormalizedNodeStreamWriter domWriter) { - final List yangArgs = new LinkedList<>(); - final DataContainerCodecContext codecContext = getCodecContextNode(path, yangArgs); - return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter)); - } - - /** - * Prepare specific writer for binding path without DOM identifier. - * - * @param path - * - binding path - * @param domWriter - * - DOM writer - * @return stream event writer for binding path - */ - public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier path, - final NormalizedNodeStreamWriter domWriter) { - return getCodecContextNode(path, null).createWriter(domWriter); - } - - /** - * Prepare specific writer for operations. - * - * @param operationInputOrOutput - * - binding data - * @param domWriter - * - DOM writer - * @return stream event writer for operation - */ - public BindingStreamEventWriter newOperationWriter(final Class> operationInputOrOutput, - final NormalizedNodeStreamWriter domWriter) { - return root.getOperation(operationInputOrOutput).createWriter(domWriter); - } - - @SuppressWarnings("rawtypes") - public BindingStreamEventWriter newNotificationWriter(final Class notification, - final NormalizedNodeStreamWriter domWriter) { - return root.getNotification(notification).createWriter(domWriter); - } - - /** - * Prepare context from Binding and DOM path. - * - * @param binding - * - binding path - * @param builder - * - DOM path - * - * @return context for path - */ - public DataContainerCodecContext getCodecContextNode(final InstanceIdentifier binding, - final List builder) { - DataContainerCodecContext currentNode = root; - for (final TreeArgument bindingArg : binding.getPathArguments()) { - currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder); - Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding); - } - return currentNode; - } - - /** - * Multi-purpose utility function. Traverse the codec tree, looking for the appropriate codec for the - * specified {@link YangInstanceIdentifier}. As a side-effect, gather all traversed binding - * {@link TreeArgument} into the supplied collection. - * - * @param dom - * {@link YangInstanceIdentifier} which is to be translated - * @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 - public NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom, - final @Nullable Collection> bindingArguments) { - 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.yangPathArgumentChild(domArg); - - /* - * List representation in YANG Instance Identifier consists of two arguments: first is list as a - * whole, second is list as an item so if it is /list it means list as whole, if it is /list/list - * - it is wildcarded and if it is /list/list[key] it is concrete item, all this variations are - * expressed in Binding Aware Instance Identifier as Item or IdentifiableItem - */ - if (currentList != null) { - Preconditions.checkArgument(currentList == nextNode, - "List should be referenced two times in YANG Instance Identifier %s", dom); - - // We entered list, so now we have all information to emit - // list path using second list argument. - if (bindingArguments != null) { - bindingArguments.add(currentList.getBindingPathArgument(domArg)); - } - currentList = null; - currentNode = nextNode; - } else if (nextNode instanceof ListNodeCodecContext) { - // We enter list, we do not update current Node yet, - // since we need to verify - 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) { - if (bindingArguments != null) { - 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); - return null; - } - } - - // Algorithm ended in list as whole representation - // we sill need to emit identifier for list - if (currentNode instanceof ChoiceNodeCodecContext) { - LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom); - return null; - } - if (currentNode instanceof CaseNodeCodecContext) { - LOG.debug("Instance identifier targeting a case is not representable (%s)", dom); - return null; - } - - if (currentList != null) { - if (bindingArguments != null) { - bindingArguments.add(currentList.getBindingPathArgument(null)); - } - return currentList; - } - return currentNode; - } - - /** - * Get notification codec according to notification schema path. - * - * @param notification - * - schema path of notification - * @return notification codec context - */ - public NotificationCodecContext getNotificationContext(final SchemaPath notification) { - return root.getNotification(notification); - } - - /** - * Get operation input codec. - * - * @param path - * - path of input data of operation - * @return operation input codec - */ - public OperationInputCodec getOperationInputCodec(final SchemaPath path) { - return root.getOperation(path); - } - - @Override - public ImmutableMap> getLeafNodes(final Class parentClass, - final DataNodeContainer childSchema) { - final Map getterToLeafSchema = new HashMap<>(); - for (final DataSchemaNode leaf : childSchema.getChildNodes()) { - if (leaf instanceof TypedDataSchemaNode) { - getterToLeafSchema.put(getGetterName(leaf, ((TypedDataSchemaNode) leaf).getType()), leaf); - } - } - return getLeafNodesUsingReflection(parentClass, getterToLeafSchema); - } - - @Override - public ImmutableMap> getAnyxmlNodes(final Class parentClass, - final DataNodeContainer childSchema) { - final Map getterToAnyxmlSchema = new HashMap<>(); - for (final DataSchemaNode anyxml : childSchema.getChildNodes()) { - if (anyxml instanceof AnyXmlSchemaNode) { - getterToAnyxmlSchema.put(getGetterName(anyxml.getQName(), false), anyxml); - } - } - return getAnyxmlNodesUsingReflection(parentClass, getterToAnyxmlSchema); - } - - private static String getGetterName(final SchemaNode node, final TypeDefinition typeDef) { - final String suffix = JavaIdentifierNormalizer.normalizeSpecificIdentifier(node.getQName().getLocalName(), - JavaIdentifier.CLASS); - - if (typeDef instanceof BooleanTypeDefinition - && (typeDef.getPath().equals(node.getPath()) || typeDef.getBaseType() == null)) { - return "is" + suffix; - } - - return "get" + suffix; - } - - private static String getGetterName(final QName qname, final boolean booleanOrEmpty) { - final String suffix = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(qname.getLocalName(), JavaIdentifier.CLASS); - if (booleanOrEmpty) { - return "is" + suffix; - } - return "get" + suffix; - } - - private ImmutableMap> getLeafNodesUsingReflection(final Class parentClass, - final Map getterToLeafSchema) { - final Map> leaves = new HashMap<>(); - for (final Method method : parentClass.getMethods()) { - if (method.getParameterTypes().length == 0) { - final DataSchemaNode schema = getterToLeafSchema.get(method.getName()); - final Class valueType; - if (schema instanceof LeafSchemaNode) { - valueType = method.getReturnType(); - } else if (schema instanceof LeafListSchemaNode) { - final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()); - - if (genericType instanceof Class) { - valueType = (Class) genericType; - } else if (genericType instanceof ParameterizedType) { - valueType = (Class) ((ParameterizedType) genericType).getRawType(); - } else { - throw new IllegalStateException("Unexpected return type " + genericType); - } - } else { - continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, - // getImplementedInterface). - } - final Codec codec = getCodec(valueType, schema); - final LeafNodeCodecContext leafNode = - new LeafNodeCodecContext<>(schema, codec, method, context.getSchemaContext()); - leaves.put(schema.getQName().getLocalName(), leafNode); - } - } - return ImmutableMap.copyOf(leaves); - } - - private ImmutableMap> getAnyxmlNodesUsingReflection(final Class parentClass, - final Map getterToAnyxmlSchema) { - final Map> anyxmls = new HashMap<>(); - for (final Method method : parentClass.getMethods()) { - if (method.getParameterTypes().length == 0) { - final DataSchemaNode schema = getterToAnyxmlSchema.get(method.getName()); - if (schema instanceof AnyXmlSchemaNode) { - final Class valueType = method.getReturnType(); - final Codec codec = (Codec) getAnyxmlCodec(); - final AnyxmlNodeCodecContext anyxmlNodeCtx = - new AnyxmlNodeCodecContext<>(schema, codec, method, context.getSchemaContext()); - anyxmls.put(schema.getQName().getLocalName(), anyxmlNodeCtx); - } - } - } - return ImmutableMap.copyOf(anyxmls); - } - - private Codec getCodec(final Class valueType, final DataSchemaNode schema) { - Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema); - - return getCodec(valueType, ((TypedDataSchemaNode) schema).getType()); - } - - /** - * Get specific codec for binding class by type. - * - * @param valueType - * - binding class - * @param instantiatedType - * - type definition - * @return specific codec - */ - public Codec getCodec(final Class valueType, final TypeDefinition instantiatedType) { - if (Class.class.equals(valueType)) { - @SuppressWarnings({ "unchecked", "rawtypes" }) - final Codec casted = (Codec) identityCodec; - return casted; - } else if (InstanceIdentifier.class.equals(valueType)) { - @SuppressWarnings({ "unchecked", "rawtypes" }) - final Codec casted = (Codec) instanceIdentifierCodec; - return casted; - } else if (Empty.class.equals(valueType)) { - return ValueTypeCodec.EMPTY_CODEC; - } else if (BindingReflections.isBindingClass(valueType)) { - return getCodecForBindingClass(valueType, instantiatedType); - } - return ValueTypeCodec.NOOP_CODEC; - } - - @SuppressWarnings("checkstyle:IllegalCatch") - private Codec getCodecForBindingClass(final Class valueType, final TypeDefinition typeDef) { - if (typeDef instanceof IdentityrefTypeDefinition) { - return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec); - } else if (typeDef instanceof InstanceIdentifierTypeDefinition) { - return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec); - } else if (typeDef instanceof UnionTypeDefinition) { - final Callable loader = - UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef, this); - try { - return loader.call(); - } catch (final Exception e) { - throw new IllegalStateException("Unable to load codec for " + valueType, e); - } - } else if (typeDef instanceof LeafrefTypeDefinition) { - final Entry typeWithSchema = context.getTypeWithSchema(valueType); - final Object schema = typeWithSchema.getValue(); - Preconditions.checkState(schema instanceof TypeDefinition); - return getCodec(valueType, (TypeDefinition) schema); - } - return ValueTypeCodec.getCodecFor(valueType, typeDef); - } - - @Override - public Codec> getPathArgumentCodec(final Class listClz, - final ListSchemaNode schema) { - final Class identifier = - ClassLoaderUtils.findFirstGenericArgument(listClz, Identifiable.class); - final Map valueCtx = new HashMap<>(); - 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") - @Nullable - @Override - public BindingTreeNodeCodec getSubtreeCodec(final InstanceIdentifier path) { - return (BindingTreeNodeCodec) getCodecContextNode(path, null); - } - - @Nullable - @Override - public BindingTreeNodeCodec getSubtreeCodec(final YangInstanceIdentifier path) { - return getCodecContextNode(path, null); - } - - @Nullable - @Override - public BindingTreeNodeCodec getSubtreeCodec(final SchemaPath path) { - throw new UnsupportedOperationException("Not implemented yet."); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecContext.java deleted file mode 100644 index 2b7f63f880..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecContext.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableCollection; -import com.google.common.collect.ImmutableSet; -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.MissingSchemaException; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.NonCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache.CachingNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer.BindingToNormalizedStreamWriter; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.QNameModule; -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.stream.NormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; - -@Beta -public abstract class DataContainerCodecContext extends NodeCodecContext { - - private final DataContainerCodecPrototype prototype; - private volatile TreeNodeSerializer eventStreamSerializer; - - protected DataContainerCodecContext(final DataContainerCodecPrototype prototype) { - this.prototype = prototype; - } - - @Nonnull - @Override - public final T getSchema() { - return prototype.getSchema(); - } - - protected final QNameModule namespace() { - return prototype.getNamespace(); - } - - protected final CodecContextFactory factory() { - return prototype.getFactory(); - } - - @Override - public YangInstanceIdentifier.PathArgument getDomPathArgument() { - return prototype.getYangArg(); - } - - /** - * Returns nested node context using supplied YANG Instance Identifier. - * - * @param arg Yang Instance Identifier Argument - * @return Context of child - * @throws IllegalArgumentException If supplied argument does not represent valid child. - */ - @Nonnull - @Override - public abstract NodeCodecContext yangPathArgumentChild(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 or null if supplied {@code arg} does not represent valid child. - * @throws IllegalArgumentException If supplied argument does not represent valid child. - */ - @SuppressWarnings("unchecked") - @Nonnull - @Override - public DataContainerCodecContext bindingPathArgumentChild(@Nonnull final TreeArgument arg, - final List builder) { - final DataContainerCodecContext child = streamChild((Class) arg.getType()); - if (builder != null) { - child.addYangPathArgument(arg,builder); - } - return child; - } - - /** - * Returns de-serialized Binding Path Argument from YANG instance identifier. - * - * @param domArg input path argument - * @return returns binding path argument - */ - @SuppressWarnings("rawtypes") - protected TreeArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) { - return bindingArg(); - } - - @SuppressWarnings("rawtypes") - protected final TreeArgument bindingArg() { - return prototype.getBindingArg(); - } - - @Nonnull - @SuppressWarnings("unchecked") - @Override - public final Class getBindingClass() { - return Class.class.cast(prototype.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 input child class - * @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. - */ - @Nonnull - @Override - public abstract DataContainerCodecContext streamChild(@Nonnull Class 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 input child class - * @return Context of child or Optional.empty is supplied class is not applicable in context. - */ - @Override - public abstract Optional> possibleStreamChild(@Nonnull - Class childClass); - - @Override - public String toString() { - return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]"; - } - - @Nonnull - @Override - public BindingNormalizedNodeCachingCodec createCachingCodec( - @Nonnull final ImmutableCollection> cacheSpecifier) { - if (cacheSpecifier.isEmpty()) { - return new NonCachingCodec(this); - } - return new CachingNormalizedNodeCodec(this, ImmutableSet.copyOf(cacheSpecifier)); - } - - public BindingStreamEventWriter createWriter(final NormalizedNodeStreamWriter domWriter) { - return BindingToNormalizedStreamWriter.create(this, domWriter); - } - - @Nonnull - protected final V childNonNull(@Nullable final V nullable, final YangInstanceIdentifier.PathArgument child, - final String message, final Object... args) { - if (nullable != null) { - return nullable; - } - MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child); - throw IncorrectNestingException.create(message, args); - } - - @Nonnull - protected final V childNonNull(@Nullable final V nullable, final QName child, final String message, - final Object... args) { - if (nullable != null) { - return nullable; - } - MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child); - throw IncorrectNestingException.create(message, args); - } - - @Nonnull - protected final V childNonNull(@Nullable final V nullable, final Class childClass, final String message, - final Object... args) { - if (nullable != null) { - return nullable; - } - MissingSchemaForClassException.check(factory().getRuntimeContext(), childClass); - MissingClassInLoadingStrategyException.check(factory().getRuntimeContext().getStrategy(), childClass); - throw IncorrectNestingException.create(message, args); - } - - public TreeNodeSerializer eventStreamSerializer() { - if (eventStreamSerializer == null) { - eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass()); - } - return eventStreamSerializer; - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final 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(final D data, final NormalizedNodeStreamWriter writer) { - try { - eventStreamSerializer().serialize(data, createWriter(writer)); - } catch (final IOException e) { - throw new IllegalStateException("Failed to serialize Binding DTO",e); - } - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecPrototype.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecPrototype.java deleted file mode 100644 index f668c10bae..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/DataContainerCodecPrototype.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.Iterables; -import javax.annotation.Nonnull; -import javax.annotation.concurrent.GuardedBy; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.AugmentationNodeContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.CaseNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ContainerNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.KeyedListNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ListNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext.CodecContextFactory; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeRoot; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.yang.common.QNameModule; -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.NodeIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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; - -@Beta -public final class DataContainerCodecPrototype implements NodeContextSupplier { - - private final T schema; - private final QNameModule namespace; - private final CodecContextFactory factory; - private final Class bindingClass; - private final Item bindingArg; - private final YangInstanceIdentifier.PathArgument yangArg; - private volatile DataContainerCodecContext instance = null; - - @SuppressWarnings({"rawtypes", "unchecked"}) - private DataContainerCodecPrototype(final Class cls, final YangInstanceIdentifier.PathArgument arg, - final T nodeSchema, final CodecContextFactory factory) { - this.bindingClass = requireNonNull(cls); - this.yangArg = requireNonNull(arg); - this.schema = requireNonNull(nodeSchema); - this.factory = requireNonNull(factory); - - this.bindingArg = new Item(bindingClass); - - if (arg instanceof AugmentationIdentifier) { - this.namespace = Iterables.getFirst( - ((AugmentationIdentifier) arg).getPossibleChildNames(), null).getModule(); - } else { - this.namespace = arg.getNodeType().getModule(); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static DataContainerCodecPrototype from(final Class cls, final T schema, - final CodecContextFactory factory) { - return new DataContainerCodecPrototype(cls, NodeIdentifier.create(schema.getQName()), schema, factory); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - static DataContainerCodecPrototype from(final Class augClass, final AugmentationIdentifier arg, - final AugmentationSchemaNode schema, final CodecContextFactory factory) { - return new DataContainerCodecPrototype(augClass, arg, schema, factory); - } - - - public static DataContainerCodecPrototype from(final Class augClass, - final NotificationDefinition schema, final CodecContextFactory factory) { - final PathArgument arg = NodeIdentifier.create(schema.getQName()); - return new DataContainerCodecPrototype<>(augClass, arg, schema, factory); - } - - public static DataContainerCodecPrototype rootPrototype(final CodecContextFactory factory) { - final SchemaContext schema = factory.getRuntimeContext().getSchemaContext(); - final NodeIdentifier arg = NodeIdentifier.create(schema.getQName()); - return new DataContainerCodecPrototype<>(TreeRoot.class, arg, schema, factory); - } - - public T getSchema() { - return schema; - } - - protected QNameModule getNamespace() { - return namespace; - } - - protected CodecContextFactory getFactory() { - return factory; - } - - public Class getBindingClass() { - return bindingClass; - } - - protected Item getBindingArg() { - return bindingArg; - } - - protected YangInstanceIdentifier.PathArgument getYangArg() { - return yangArg; - } - - @Nonnull - @Override - public DataContainerCodecContext get() { - DataContainerCodecContext tmp = instance; - if (tmp == null) { - synchronized (this) { - tmp = instance; - if (tmp == null) { - tmp = createInstance(); - instance = tmp; - } - } - } - - return tmp; - } - - @GuardedBy("this") - @SuppressWarnings({"rawtypes", "unchecked"}) - protected DataContainerCodecContext createInstance() { - if (schema instanceof ContainerSchemaNode) { - return new ContainerNodeCodecContext(this); - } else if (schema instanceof ListSchemaNode) { - if (Identifiable.class.isAssignableFrom(getBindingClass())) { - return new KeyedListNodeCodecContext(this); - } else { - return new ListNodeCodecContext(this); - } - } else if (schema instanceof ChoiceSchemaNode) { - return new ChoiceNodeCodecContext(this); - } else if (schema instanceof AugmentationSchemaNode) { - return new AugmentationNodeContext(this); - } else if (schema instanceof CaseSchemaNode) { - return new CaseNodeCodecContext(this); - } - throw new IllegalArgumentException("Unsupported type " + bindingClass + " " + schema); - } - - boolean isChoice() { - return schema instanceof ChoiceSchemaNode; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/IncorrectNestingException.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/IncorrectNestingException.java deleted file mode 100644 index 16a4385c84..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/IncorrectNestingException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * Thrown where incorrect nesting of data structures was detected - * and was caused by user. - */ -@Beta -class IncorrectNestingException extends IllegalArgumentException { - - private static final long serialVersionUID = 1L; - - protected IncorrectNestingException(final String message) { - super(message); - } - - public static IncorrectNestingException create(final String message, final Object... args) { - return new IncorrectNestingException(String.format(message, args)); - } - - public static void check(final boolean check, final String message, final Object... args) { - if (!check) { - throw IncorrectNestingException.create(message, args); - } - } - - @Nonnull - public static V checkNonNull(@Nullable final V nullable, final String message, final Object... args) { - if (nullable != null) { - return nullable; - } - throw IncorrectNestingException.create(message, args); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LazyTreeNode.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LazyTreeNode.java deleted file mode 100644 index ef7d8133d6..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LazyTreeNode.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.AugmentationReader; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -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; - -@Beta -class LazyTreeNode implements InvocationHandler, AugmentationReader { - - private static final Logger LOG = LoggerFactory.getLogger(LazyTreeNode.class); - private static final String GET_IMPLEMENTED_INTERFACE = "implementedInterface"; - private static final String TO_STRING = "toString"; - private static final String EQUALS = "equals"; - private static final String GET_AUGMENTATION = "getAugmentation"; - private static final String HASHCODE = "hashCode"; - private static final String AUGMENTATIONS = "augmentations"; - private static final Object NULL_VALUE = new Object(); - - private final ConcurrentHashMap cachedData = new ConcurrentHashMap<>(); - private final NormalizedNodeContainer> data; - private final TreeNodeCodecContext context; - - private volatile ImmutableMap>, Augmentation> cachedAugmentations = null; - private volatile Integer cachedHashcode = null; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - LazyTreeNode(final TreeNodeCodecContext ctx, final NormalizedNodeContainer data) { - this.context = requireNonNull(ctx, "Context must not be null"); - this.data = requireNonNull(data, "Data must not be null"); - } - - @Override - public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - if (method.getParameterTypes().length == 0) { - final String name = method.getName(); - if (GET_IMPLEMENTED_INTERFACE.equals(name)) { - return context.getBindingClass(); - } else if (TO_STRING.equals(name)) { - return bindingToString(); - } else if (HASHCODE.equals(name)) { - return bindingHashCode(); - } else if (AUGMENTATIONS.equals(name)) { - return getAugmentationsImpl(); - } - return getBindingData(method); - } else if (GET_AUGMENTATION.equals(method.getName())) { - return getAugmentationImpl((Class) args[0]); - } else if (EQUALS.equals(method.getName())) { - return bindingEquals(args[0]); - } - throw new UnsupportedOperationException("Unsupported method " + method); - } - - private boolean bindingEquals(final Object other) { - if (other == null) { - return false; - } - if (!context.getBindingClass().isAssignableFrom(other.getClass())) { - return false; - } - try { - for (final Method m : context.getHashCodeAndEqualsMethods()) { - final Object thisValue = getBindingData(m); - final Object otherValue = m.invoke(other); - /* - * added for valid byte array comparison, when list key type is binary - * deepEquals is not used since it does excessive amount of instanceof calls. - */ - if (thisValue instanceof byte[] && otherValue instanceof byte[]) { - if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) { - return false; - } - } else if (!Objects.equals(thisValue, otherValue)) { - return false; - } - } - - if (Augmentable.class.isAssignableFrom(context.getBindingClass())) { - if (!getAugmentationsImpl().equals(getAllAugmentations(other))) { - return false; - } - } - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - LOG.warn("Can not determine equality of {} and {}", this, other, e); - return false; - } - return true; - } - - private static Map>, Augmentation> getAllAugmentations(final Object dataObject) { - if (dataObject instanceof AugmentationReader) { - return ((AugmentationReader) dataObject).getAugmentations(dataObject); - } else if (dataObject instanceof Augmentable) { - return BindingReflections.getAugmentations((Augmentable) dataObject); - } - - throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject); - } - - private Integer bindingHashCode() { - final Integer ret = cachedHashcode; - if (ret != null) { - return ret; - } - - final int prime = 31; - int result = 1; - for (final Method m : context.getHashCodeAndEqualsMethods()) { - final Object value = getBindingData(m); - result = prime * result + Objects.hashCode(value); - } - if (Augmentable.class.isAssignableFrom(context.getBindingClass())) { - result = prime * result + getAugmentationsImpl().hashCode(); - } - cachedHashcode = result; - return result; - } - - private Object getBindingData(final Method method) { - Object cached = cachedData.get(method); - if (cached == null) { - final Object readedValue = context.getBindingChildValue(method, data); - if (readedValue == null) { - cached = NULL_VALUE; - } else { - cached = readedValue; - } - cachedData.putIfAbsent(method, cached); - } - - return cached == NULL_VALUE ? null : cached; - } - - private Map>, Augmentation> getAugmentationsImpl() { - ImmutableMap>, Augmentation> ret = cachedAugmentations; - if (ret == null) { - synchronized (this) { - ret = cachedAugmentations; - if (ret == null) { - ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data)); - cachedAugmentations = ret; - } - } - } - - return ret; - } - - @Override - public Map>, Augmentation> getAugmentations(final Object obj) { - Preconditions.checkArgument(this == Proxy.getInvocationHandler(obj), - "Supplied object is not associated with this proxy handler"); - - return getAugmentationsImpl(); - } - - private Object getAugmentationImpl(final Class cls) { - final ImmutableMap>, Augmentation> aug = cachedAugmentations; - if (aug != null) { - return aug.get(cls); - } - requireNonNull(cls,"Supplied augmentation must not be null."); - - @SuppressWarnings({"unchecked","rawtypes"}) - final Optional> augCtx = context.possibleStreamChild((Class) cls); - if (augCtx.isPresent()) { - final Optional> augData = data.getChild(augCtx.get().getDomPathArgument()); - if (augData.isPresent()) { - return augCtx.get().deserialize(augData.get()); - } - } - return null; - } - - public String bindingToString() { - 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.getBindingClass())) { - helper.add("augmentations", getAugmentationsImpl()); - } - return helper.toString(); - } - - @Override - public int hashCode() { - return Objects.hash(this.context, this.data); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final LazyTreeNode other = (LazyTreeNode) obj; - return Objects.equals(context, other.context) && Objects.equals(data, other.data); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LeafNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LeafNodeCodecContext.java deleted file mode 100644 index 711cfe5155..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/LeafNodeCodecContext.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableCollection; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCachingCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.yang.common.QName; -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.data.impl.codec.TypeDefinitionAwareCodec; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.ModuleImport; -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; - -@Beta -public final class LeafNodeCodecContext extends NodeCodecContext implements NodeContextSupplier { - - private final YangInstanceIdentifier.PathArgument yangIdentifier; - private final Codec valueCodec; - private final Method getter; - private final DataSchemaNode schema; - private final Object defaultObject; - - LeafNodeCodecContext(final DataSchemaNode schema, final Codec codec, final Method getter, - final SchemaContext schemaContext) { - this.yangIdentifier = new YangInstanceIdentifier.NodeIdentifier(schema.getQName()); - this.valueCodec = requireNonNull(codec); - this.getter = requireNonNull(getter); - this.schema = requireNonNull(schema); - - this.defaultObject = createDefaultObject(schema, valueCodec, schemaContext); - } - - private static Object createDefaultObject(final DataSchemaNode schema, final Codec codec, - final SchemaContext schemaContext) { - if (schema instanceof LeafSchemaNode) { - TypeDefinition type = ((LeafSchemaNode) schema).getType(); - Optional defaultValue = type.getDefaultValue(); - if (defaultValue.isPresent()) { - if (type instanceof IdentityrefTypeDefinition) { - return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext); - } - return domValueFromString(codec, type, defaultValue.get()); - } - - while (type.getBaseType() != null && !type.getDefaultValue().isPresent()) { - type = type.getBaseType(); - } - - defaultValue = type.getDefaultValue(); - if (defaultValue.isPresent()) { - if (type instanceof IdentityrefTypeDefinition) { - return qnameDomValueFromString(codec, schema, (String) defaultValue.get(), schemaContext); - } - return domValueFromString(codec, type, defaultValue.get()); - } - } - return null; - } - - private static Object qnameDomValueFromString(final Codec codec, final DataSchemaNode schema, - final String defaultValue, final SchemaContext schemaContext) { - final int prefixEndIndex = defaultValue.indexOf(':'); - if (prefixEndIndex != -1) { - final String defaultValuePrefix = defaultValue.substring(0, prefixEndIndex); - - final Module module = schemaContext.findModule(schema.getQName().getModule()).get(); - - if (module.getPrefix().equals(defaultValuePrefix)) { - return codec.deserialize(QName.create(module.getQNameModule(), - defaultValue.substring(prefixEndIndex + 1))); - } - - final Set imports = module.getImports(); - for (final ModuleImport moduleImport : imports) { - if (moduleImport.getPrefix().equals(defaultValuePrefix)) { - final Module importedModule = schemaContext.findModule(moduleImport.getModuleName(), - moduleImport.getRevision()).get(); - return codec.deserialize(QName.create(importedModule.getQNameModule(), - defaultValue.substring(prefixEndIndex + 1))); - } - } - return null; - } - - return codec.deserialize(QName.create(schema.getQName(), defaultValue)); - } - - private static Object domValueFromString(final Codec codec, final TypeDefinition type, - final Object defaultValue) { - final TypeDefinitionAwareCodec typeDefAwareCodec = TypeDefinitionAwareCodec.from(type); - if (typeDefAwareCodec != null) { - final Object castedDefaultValue = typeDefAwareCodec.deserialize((String) defaultValue); - return codec.deserialize(castedDefaultValue); - } - // FIXME: BUG-4647 Refactor / redesign this to throw hard error, - // once BUG-4638 is fixed and will provide proper getDefaultValue implementation. - return null; - } - - @Override - public YangInstanceIdentifier.PathArgument getDomPathArgument() { - return yangIdentifier; - } - - public Codec getValueCodec() { - return valueCodec; - } - - @Nonnull - @Override - public D deserialize(@Nonnull final NormalizedNode normalizedNode) { - throw new UnsupportedOperationException("Leaf can not be deserialized to TreeNode"); - } - - @Nonnull - @Override - public NodeCodecContext get() { - return this; - } - - public Method getGetter() { - return getter; - } - - @Nonnull - @Override - public BindingTreeNodeCodec bindingPathArgumentChild(@Nonnull final TreeArgument arg, - final List builder) { - throw new IllegalArgumentException("Leaf does not have children"); - } - - @Nonnull - @Override - public BindingNormalizedNodeCachingCodec createCachingCodec( - @Nonnull final ImmutableCollection> cacheSpecifier) { - throw new UnsupportedOperationException("Leaves does not support caching codec."); - } - - @Nonnull - @Override - public Class getBindingClass() { - throw new UnsupportedOperationException("Leaf does not have DataObject representation"); - } - - @Nonnull - @Override - public NormalizedNode serialize(@Nonnull final D data) { - throw new UnsupportedOperationException("Separate serialization of leaf node is not supported."); - } - - @Override - public void writeAsNormalizedNode(final D data, final NormalizedNodeStreamWriter writer) { - throw new UnsupportedOperationException("Separate serialization of leaf node is not supported."); - } - - @Nonnull - @Override - public BindingTreeNodeCodec streamChild(@Nonnull final Class childClass) { - throw new IllegalArgumentException("Leaf does not have children"); - } - - @Override - public Optional> possibleStreamChild( - @Nonnull final Class childClass) { - throw new IllegalArgumentException("Leaf does not have children"); - } - - @Nonnull - @Override - public BindingTreeNodeCodec yangPathArgumentChild(final YangInstanceIdentifier.PathArgument child) { - throw new IllegalArgumentException("Leaf does not have children"); - } - - @Override - protected Object deserializeObject(final NormalizedNode normalizedNode) { - if (normalizedNode instanceof LeafNode) { - return valueCodec.deserialize(normalizedNode.getValue()); - } - if (normalizedNode instanceof LeafSetNode) { - @SuppressWarnings("unchecked") - final Collection> domValues = ((LeafSetNode) normalizedNode).getValue(); - final List result = new ArrayList<>(domValues.size()); - for (final LeafSetEntryNode valueNode : domValues) { - result.add(valueCodec.deserialize(valueNode.getValue())); - } - return result; - } - return null; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(getDomPathArgument().equals(arg)); - return null; - } - - @SuppressWarnings("rawtypes") - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) { - return getDomPathArgument(); - } - - @Nonnull - @Override - public DataSchemaNode getSchema() { - return schema; - } - - /** - * Return the default value object. - * - * @return The default value object, or null if the default value is not defined. - */ - @Nullable - Object defaultObject() { - return defaultObject; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingClassInLoadingStrategyException.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingClassInLoadingStrategyException.java deleted file mode 100644 index 6296b99245..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingClassInLoadingStrategyException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.MissingSchemaException; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; - -/** - * Thrown when user schema for supplied binding class is available in present schema context, but - * binding class itself is not known to codecs because backing class loading strategy did not - * provided it. - */ -@Beta -public class MissingClassInLoadingStrategyException extends MissingSchemaException { - - private static final long serialVersionUID = 1L; - - protected MissingClassInLoadingStrategyException(final String msg, final Throwable cause) { - super(msg, cause); - } - - public static void check(final ClassLoadingStrategy strategy, final Class childClass) { - try { - strategy.loadClass(childClass.getName()); - } catch (final ClassNotFoundException e) { - final String message = - String.format("User supplied class %s is not available in %s.", childClass.getName(), strategy); - throw new MissingClassInLoadingStrategyException(message, e); - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingSchemaForClassException.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingSchemaForClassException.java deleted file mode 100644 index 4bf75e637f..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/MissingSchemaForClassException.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.MissingSchemaException; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; - -/** - * Thrown when Java Binding class was used in data for which codec does not - * have schema. - * - *

- * By serialization / deserialization of this exception {@link #getBindingClass()} - * will return null. - */ -@Beta -public final class MissingSchemaForClassException extends MissingSchemaException { - - private static final long serialVersionUID = 1L; - - private final transient Class bindingClass; - - private MissingSchemaForClassException(final Class clz) { - super(String.format("Schema is not available for %s", clz)); - this.bindingClass = requireNonNull(clz); - } - - static MissingSchemaForClassException forClass(final Class clz) { - return new MissingSchemaForClassException(clz); - } - - public Class getBindingClass() { - return bindingClass; - } - - public static void check(final BindingRuntimeContext runtimeContext, final Class bindingClass) { - final Object schema; - if (Augmentation.class.isAssignableFrom(bindingClass)) { - schema = runtimeContext.getAugmentationDefinition(bindingClass); - } else { - schema = runtimeContext.getSchemaDefinition(bindingClass); - } - if (schema == null) { - throw MissingSchemaForClassException.forClass(bindingClass); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeCodecContext.java deleted file mode 100644 index 532ff750f7..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeCodecContext.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableMap; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.yangtools.concepts.Codec; -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.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; - -/** - * Location specific context for schema nodes, which contains codec specific - * information to properly serialize / deserialize from Java YANG Binding data - * to NormalizedNode data. - * - *

- * Two core subtypes of codec context are available: - *

    - *
  • {@link LeafNodeCodecContext} - Context for nodes, which does not contain - * any nested YANG modeled substructures.
  • - *
  • {@link TreeNodeCodecContext} - Context for nodes, which does contain - * nested YANG modeled substructures. This context nodes contains context - * for children nodes.
  • - *
- * - */ -@Beta -public abstract class NodeCodecContext implements BindingTreeNodeCodec { - /** - * Returns Yang Instance Identifier Path Argument of current node. - * - * @return DOM Path Argument of node - */ - public abstract YangInstanceIdentifier.PathArgument getDomPathArgument(); - - /** - * Immutable factory, which provides access to runtime context, - * create leaf nodes and provides path argument codecs. - * - *

- * During lifetime of factory all calls for same arguments to method must return - * equal result (not necessary same instance of result). - * - */ - protected interface CodecContextFactory { - /** - * Returns immutable runtime context associated with this factory. - * @return runtime context - */ - BindingRuntimeContext getRuntimeContext(); - - /** - * Returns leaf nodes for supplied data container and parent class. - * - * @param type Binding type for which leaves should be loaded. - * @param schema Instantiated schema of binding type. - * @return Map of local name to leaf node context. - */ - ImmutableMap> getLeafNodes(Class type, DataNodeContainer schema); - - /** - * Returns anyxml nodes for supplied data container and parent class. - * - * @param type Binding type for which anyxml should be loaded. - * @param schema Instantiated schema of binding type. - * @return Map of local name to anyxml node context. - */ - ImmutableMap> getAnyxmlNodes(Class type, DataNodeContainer schema); - - /** - * Returns Path argument codec for list item. - * - * @param type Type of list item - * @param schema Schema of list item - * @return Path argument codec for supplied list item. - */ - Codec> getPathArgumentCodec(Class type, - ListSchemaNode schema); - - TreeNodeSerializer getEventStreamSerializer(Class type); - } - - /** - * Serializes supplied Binding Path Argument - * and adds all necessary YANG instance identifiers to supplied list. - * - * @param arg Binding Path Argument - * @param builder DOM Path argument. - */ - @SuppressWarnings("rawtypes") - protected void addYangPathArgument(final TreeArgument arg, - final List builder) { - if (builder != null) { - builder.add(getDomPathArgument()); - } - } - - protected abstract Object deserializeObject(NormalizedNode normalizedNode); -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeContextSupplier.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeContextSupplier.java deleted file mode 100644 index f6014c7fc0..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/NodeContextSupplier.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import java.util.function.Supplier; -import javax.annotation.Nonnull; - -/** - * Type capture of an entity producing NodeCodecContexts. - */ -@Beta -interface NodeContextSupplier extends Supplier> { - - @Override - @Nonnull - NodeCodecContext get(); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/TreeNodeCodecContext.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/TreeNodeCodecContext.java deleted file mode 100755 index 427faa4ded..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/base/TreeNodeCodecContext.java +++ /dev/null @@ -1,421 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSortedMap; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder; -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.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.AugmentationNode; -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.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public abstract class TreeNodeCodecContext - extends DataContainerCodecContext { - - private static final Logger LOG = LoggerFactory.getLogger(TreeNodeCodecContext.class); - private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class); - private static final MethodType TREENODE_TYPE = MethodType.methodType(TreeNode.class, InvocationHandler.class); - private static final Comparator METHOD_BY_ALPHABET = Comparator.comparing(Method::getName); - - private final ImmutableMap> leafChild; - private final ImmutableMap> anyxmlChild; - private final ImmutableMap byYang; - private final ImmutableSortedMap byMethod; - private final ImmutableMap, DataContainerCodecPrototype> byStreamClass; - private final ImmutableMap, DataContainerCodecPrototype> byBindingArgClass; - private final ImmutableMap possibleAugmentations; - private final MethodHandle proxyConstructor; - - private final ConcurrentMap> byYangAugmented = - new ConcurrentHashMap<>(); - private final ConcurrentMap, DataContainerCodecPrototype> byStreamAugmented = new ConcurrentHashMap<>(); - - - protected TreeNodeCodecContext(final DataContainerCodecPrototype prototype) { - super(prototype); - - this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema()); - this.anyxmlChild = factory().getAnyxmlNodes(getBindingClass(), getSchema()); - - final Map, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass()); - - final Map byYangBuilder = new HashMap<>(); - final SortedMap byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET); - final Map, DataContainerCodecPrototype> byStreamClassBuilder = new HashMap<>(); - final Map, DataContainerCodecPrototype> byBindingArgClassBuilder = new HashMap<>(); - - // Adds leaves to mapping - for (final LeafNodeCodecContext leaf : leafChild.values()) { - byMethodBuilder.put(leaf.getGetter(), leaf); - byYangBuilder.put(leaf.getDomPathArgument(), leaf); - } - - for (final AnyxmlNodeCodecContext anyxml : anyxmlChild.values()) { - byMethodBuilder.put(anyxml.getGetter(), anyxml); - byYangBuilder.put(anyxml.getDomPathArgument(), anyxml); - } - - for (final Entry, 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()) { - final ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get(); - choice.getClassCaseChildren().entrySet().forEach(entry -> - byBindingArgClassBuilder.put(entry.getKey(), childProto)); - - choice.getYangCaseChildren().entrySet().forEach(entry -> - byYangBuilder.put(entry.getKey(), childProto)); - } - } - - this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder); - this.byYang = ImmutableMap.copyOf(byYangBuilder); - this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder); - byBindingArgClassBuilder.putAll(byStreamClass); - this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder); - - - if (Augmentable.class.isAssignableFrom(getBindingClass())) { - this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema()); - } else { - this.possibleAugmentations = ImmutableMap.of(); - } - reloadAllAugmentations(); - - final Class proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), - new Class[] { getBindingClass(), AugmentationHolder.class }); - try { - proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE) - .asType(TREENODE_TYPE); - } catch (NoSuchMethodException | IllegalAccessException e) { - throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e); - } - } - - private void reloadAllAugmentations() { - for (final Entry augment : possibleAugmentations.entrySet()) { - final DataContainerCodecPrototype augProto = getAugmentationPrototype(augment.getValue()); - if (augProto != null) { - byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto); - byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto); - } - } - } - - @Nonnull - @SuppressWarnings("unchecked") - @Override - public DataContainerCodecContext streamChild(@Nonnull final Class childClass) { - final DataContainerCodecPrototype childProto = streamChildPrototype(childClass); - return (DataContainerCodecContext) childNonNull(childProto, childClass, " Child %s is not valid child.", - childClass).get(); - } - - private DataContainerCodecPrototype streamChildPrototype(final Class childClass) { - final DataContainerCodecPrototype childProto = byStreamClass.get(childClass); - if (childProto != null) { - return childProto; - } - if (Augmentation.class.isAssignableFrom(childClass)) { - return augmentationByClass(childClass); - } - return null; - } - - @SuppressWarnings("unchecked") - @Override - public Optional> possibleStreamChild( - @Nonnull final Class childClass) { - final DataContainerCodecPrototype childProto = streamChildPrototype(childClass); - if (childProto != null) { - return Optional.of((DataContainerCodecContext) childProto.get()); - } - return Optional.empty(); - } - - @Nonnull - @Override - public DataContainerCodecContext bindingPathArgumentChild(final TreeArgument arg, - final List builder) { - - final Class argType = (Class) arg.getType(); - DataContainerCodecPrototype ctxProto = byBindingArgClass.get(argType); - if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) { - ctxProto = augmentationByClass(argType); - } - final DataContainerCodecContext context = - childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get(); - - if (context instanceof ChoiceNodeCodecContext) { - final ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) context; - final DataContainerCodecContext caze = choice.getCaseByChildClass(argType); - // FIXME: Instance identifier should not reference choice or case as they're - // not data tree nodes. - return caze.bindingPathArgumentChild(arg, builder); - } - - context.addYangPathArgument(arg, builder); - return context; - } - - @Nonnull - @SuppressWarnings("unchecked") - @Override - public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) { - final NodeContextSupplier childSupplier; - if (arg instanceof NodeIdentifierWithPredicates) { - childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType())); - } else if (arg instanceof AugmentationIdentifier) { - childSupplier = yangAugmentationChild((AugmentationIdentifier) arg); - } else { - childSupplier = byYang.get(arg); - } - - // FIXME: Since instance identifier does not reference choice or case, - // we should search in data children of choice/case - if (childSupplier instanceof DataContainerCodecPrototype) { - final DataContainerCodecContext context = ((DataContainerCodecPrototype) childSupplier).get(); - if (context instanceof ChoiceNodeCodecContext) { - return (NodeCodecContext) childNonNull(((ChoiceNodeCodecContext) context).yangPathArgumentChild(arg), - arg, "Argument %s is not valid child of %s", arg, getSchema()); - } - } - - return (NodeCodecContext) childNonNull(childSupplier, arg, - "Argument %s is not valid child of %s", arg, getSchema()).get(); - } - - public final LeafNodeCodecContext getLeafChild(final String name) { - final LeafNodeCodecContext value = leafChild.get(name); - return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass()); - } - - public final AnyxmlNodeCodecContext getAnyxmlChild(final String name) { - final AnyxmlNodeCodecContext value = anyxmlChild.get(name); - return IncorrectNestingException.checkNonNull(value, "Anyxml %s is not valid for %s", name, getBindingClass()); - } - - private DataContainerCodecPrototype loadChildPrototype(final Class childClass) { - final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass); - // Direct instantiation or use in same module in which grouping - // was defined. - DataSchemaNode sameName; - try { - sameName = getSchema().getDataChildByName(origDef.getQName()); - } catch (final IllegalArgumentException e) { - sameName = null; - } - final DataSchemaNode childSchema; - if (sameName != null) { - // Exactly same schema node - if (origDef.equals(sameName)) { - childSchema = sameName; - // We check if instantiated node was added via uses - // statement and is instantiation of same grouping - } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) { - childSchema = sameName; - } else { - // Node has same name, but clearly is different - childSchema = null; - } - } else { - // We are looking for instantiation via uses in other module - final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName()); - final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName); - // We check if it is really instantiated from same - // definition as class was derived - if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) { - childSchema = potential; - } else { - childSchema = null; - } - } - final DataSchemaNode nonNullChild = - childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass); - return DataContainerCodecPrototype.from(childClass, nonNullChild, factory()); - } - - private DataContainerCodecPrototype yangAugmentationChild(final AugmentationIdentifier arg) { - final DataContainerCodecPrototype firstTry = byYangAugmented.get(arg); - if (firstTry != null) { - return firstTry; - } - if (possibleAugmentations.containsKey(arg)) { - reloadAllAugmentations(); - return byYangAugmented.get(arg); - } - return null; - } - - @Nullable - private DataContainerCodecPrototype augmentationByClass(@Nonnull final Class childClass) { - final DataContainerCodecPrototype firstTry = augmentationByClassOrEquivalentClass(childClass); - if (firstTry != null) { - return firstTry; - } - reloadAllAugmentations(); - return augmentationByClassOrEquivalentClass(childClass); - } - - @Nullable - private DataContainerCodecPrototype augmentationByClassOrEquivalentClass(@Nonnull final Class childClass) { - final DataContainerCodecPrototype childProto = byStreamAugmented.get(childClass); - if (childProto != null) { - return childProto; - } - - /* - * It is potentially mismatched valid augmentation - we look up equivalent augmentation - * using reflection and walk all stream child and compare augmenations classes if they are - * equivalent. - * - * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup. - */ - @SuppressWarnings("rawtypes") - final Class augTarget = BindingReflections.findAugmentationTarget((Class) childClass); - if (getBindingClass().equals(augTarget)) { - for (final DataContainerCodecPrototype realChild : byStreamAugmented.values()) { - if (Augmentation.class.isAssignableFrom(realChild.getBindingClass()) - && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) { - return realChild; - } - } - } - return null; - } - - private DataContainerCodecPrototype getAugmentationPrototype(final Type value) { - final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy(); - @SuppressWarnings("rawtypes") - final Class augClass; - try { - augClass = loader.loadClass(value); - } catch (final ClassNotFoundException e) { - LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e); - return null; - } - - @SuppressWarnings("unchecked") - final Entry augSchema = factory().getRuntimeContext() - .getResolvedAugmentationSchema(getSchema(), augClass); - return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory()); - } - - @SuppressWarnings("rawtypes") - public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) { - final NodeCodecContext childContext = byMethod.get(method).get(); - @SuppressWarnings("unchecked") - final Optional> domChild = domData.getChild(childContext.getDomPathArgument()); - if (domChild.isPresent()) { - return childContext.deserializeObject(domChild.get()); - } else if (childContext instanceof LeafNodeCodecContext) { - return ((LeafNodeCodecContext)childContext).defaultObject(); - } else { - return null; - } - } - - @SuppressWarnings("checkstyle:illegalCatch") - protected final D createBindingProxy(final NormalizedNodeContainer node) { - try { - return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node)); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - } - - @SuppressWarnings("unchecked") - public Map>, Augmentation> getAllAugmentationsFrom( - final NormalizedNodeContainer> data) { - - @SuppressWarnings("rawtypes") - final Map map = new HashMap<>(); - - for (final NormalizedNode childValue : data.getValue()) { - if (childValue instanceof AugmentationNode) { - final AugmentationNode augDomNode = (AugmentationNode) childValue; - final DataContainerCodecPrototype codecProto = yangAugmentationChild(augDomNode.getIdentifier()); - if (codecProto != null) { - final DataContainerCodecContext codec = codecProto.get(); - map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode)); - } - } - } - for (final DataContainerCodecPrototype value : byStreamAugmented.values()) { - final Optional> augData = data.getChild(value.getYangArg()); - if (augData.isPresent()) { - map.put(value.getBindingClass(), value.get().deserializeObject(augData.get())); - } - } - return map; - } - - public Collection getHashCodeAndEqualsMethods() { - return byMethod.keySet(); - } - - @Override - public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) { - Preconditions.checkArgument(getDomPathArgument().equals(arg)); - return bindingArg(); - } - - @Override - public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) { - Preconditions.checkArgument(bindingArg().equals(arg)); - return getDomPathArgument(); - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/AugmentableDispatchSerializer.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/AugmentableDispatchSerializer.java deleted file mode 100644 index 5931f489c1..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/AugmentableDispatchSerializer.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.AugmentationReader; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Dispatch serializer, which emits - * {@link BindingStreamEventWriter#startAugmentationNode(Class)} events for - * supplied augmentation node. - */ -@Beta -public class AugmentableDispatchSerializer implements TreeNodeSerializerImplementation { - - private static final Logger LOG = LoggerFactory.getLogger(AugmentableDispatchSerializer.class); - - @Override - public void serialize(final TreeNodeSerializerRegistry reg, final TreeNode obj, - final BindingStreamEventWriter stream) throws IOException { - if (obj instanceof Augmentable) { - final Map>, Augmentation> augmentations; - if (reg instanceof AugmentationReader) { - augmentations = ((AugmentationReader) reg).getAugmentations(obj); - } else if (Proxy.isProxyClass(obj.getClass())) { - augmentations = getFromProxy(obj); - } else { - augmentations = BindingReflections.getAugmentations((Augmentable) obj); - } - for (final Entry>, Augmentation> aug : augmentations.entrySet()) { - emitAugmentation(aug.getKey(), aug.getValue(), stream, reg); - } - } - } - - private Map>, Augmentation> getFromProxy(final TreeNode obj) { - final InvocationHandler proxy = Proxy.getInvocationHandler(obj); - if (proxy instanceof AugmentationReader) { - return ((AugmentationReader) proxy).getAugmentations(obj); - } - return Collections.emptyMap(); - } - - @SuppressWarnings("rawtypes") - private void emitAugmentation(final Class type, final Augmentation value, final BindingStreamEventWriter stream, - final TreeNodeSerializerRegistry registry) throws IOException { - Preconditions.checkArgument(value instanceof TreeNode); - @SuppressWarnings("unchecked") - final TreeNodeSerializer serializer = registry.getSerializer(type); - if (serializer != null) { - serializer.serialize((TreeNode) value, stream); - } else { - LOG.warn("TreeNodeSerializer is not present for {} in registry {}", type, registry); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/BindingToNormalizedStreamWriter.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/BindingToNormalizedStreamWriter.java deleted file mode 100644 index d98e6b4a98..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/BindingToNormalizedStreamWriter.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.io.IOException; -import java.util.AbstractMap; -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Map; -import java.util.Map.Entry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.CaseNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.KeyedListNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.AnyxmlNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.LeafNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.TreeNodeCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.concepts.Delegator; -import org.opendaylight.yangtools.concepts.Identifiable; -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.NodeIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; -import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; - -/** - * Stream event writer of Binding v2 representation. - */ -@Beta -public final class BindingToNormalizedStreamWriter - implements BindingStreamEventWriter, Delegator { - - private final Deque> schema = new ArrayDeque<>(); - private final NormalizedNodeStreamWriter delegate; - private final NodeCodecContext rootNodeSchema; - - private BindingToNormalizedStreamWriter(final NodeCodecContext rootNodeSchema, - final NormalizedNodeStreamWriter delegate) { - this.rootNodeSchema = requireNonNull(rootNodeSchema); - this.delegate = requireNonNull(delegate); - } - - /** - * Create instance of Binding v2 representation writer. - * - * @param schema - * - codec schema - * @param delegate - * - DOM writer delegator - * @return instance of binding writer - */ - public static BindingToNormalizedStreamWriter create(final NodeCodecContext schema, - final NormalizedNodeStreamWriter delegate) { - return new BindingToNormalizedStreamWriter(schema, delegate); - } - - private void emitSchema(final Object schemaNode) { - delegate.nextDataSchemaNode((DataSchemaNode) schemaNode); - } - - /** - * Retrieves, but does not remove, the head of the queue represented by node - * codec context. - * - * @return head of queue - */ - NodeCodecContext current() { - return schema.peek(); - } - - private NodeIdentifier duplicateSchemaEnter() { - final NodeCodecContext next; - if (current() == null) { - // Entry of first node - next = rootNodeSchema; - } else { - next = current(); - } - this.schema.push(next); - return (NodeIdentifier) current().getDomPathArgument(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private T enter(final Class name, final Class identifier) { - 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()).streamChild(name); - } - this.schema.push(next); - return (T) next.getDomPathArgument(); - } - - @SuppressWarnings("rawtypes") - private T enter(final String localName, final Class identifier) { - final NodeCodecContext current = current(); - final NodeCodecContext next = ((TreeNodeCodecContext) current).getLeafChild(localName); - this.schema.push(next); - @SuppressWarnings("unchecked") - final T arg = (T) next.getDomPathArgument(); - return arg; - } - - @Override - public NormalizedNodeStreamWriter getDelegate() { - return delegate; - } - - @Override - public void endNode() throws IOException { - final 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)) { - getDelegate().endNode(); - } - } - - private Map.Entry serializeLeaf(final String localName, final Object value) { - Preconditions.checkArgument(current() instanceof TreeNodeCodecContext); - - final TreeNodeCodecContext currentCasted = (TreeNodeCodecContext) current(); - final LeafNodeCodecContext leafContext = currentCasted.getLeafChild(localName); - - final NodeIdentifier domArg = (NodeIdentifier) leafContext.getDomPathArgument(); - final Object domValue = leafContext.getValueCodec().serialize(value); - emitSchema(leafContext.getSchema()); - return new AbstractMap.SimpleEntry<>(domArg, domValue); - } - - private Map.Entry serializeAnyxml(final String localName, final Object value) { - Preconditions.checkArgument(current() instanceof TreeNodeCodecContext); - - final TreeNodeCodecContext currentCasted = (TreeNodeCodecContext) current(); - final AnyxmlNodeCodecContext anyxmlContext = currentCasted.getAnyxmlChild(localName); - - final NodeIdentifier domArg = (NodeIdentifier) anyxmlContext.getDomPathArgument(); - final Object domValue = anyxmlContext.getValueCodec().serialize(value); - emitSchema(anyxmlContext.getSchema()); - return new AbstractMap.SimpleEntry<>(domArg, domValue); - } - - @Override - public void leafNode(final String localName, final Object value) throws IOException { - final Entry dom = serializeLeaf(localName, value); - getDelegate().leafNode(dom.getKey(), dom.getValue()); - } - - @Override - public void anyxmlNode(final String name, final Object value) throws IOException { - final Entry dom = serializeAnyxml(name, value); - getDelegate().anyxmlNode(dom.getKey(), dom.getValue()); - } - - @Override - public void leafSetEntryNode(final Object value) throws IOException { - final LeafNodeCodecContext ctx = (LeafNodeCodecContext) current(); - getDelegate().leafSetEntryNode(ctx.getSchema().getQName(), ctx.getValueCodec().serialize(value)); - } - - @Override - public void startAugmentationNode(final Class> augmentationType) throws IOException { - getDelegate().startAugmentationNode(enter(augmentationType, AugmentationIdentifier.class)); - } - - @Override - public void startCase(final Class caze, final int childSizeHint) { - enter(caze, NodeIdentifier.class); - } - - @Override - public void startChoiceNode(final Item choice, final int childSizeHint) throws IOException { - getDelegate().startChoiceNode(enter(choice.getType(), NodeIdentifier.class), childSizeHint); - } - - @Override - public void startContainerNode(final Class object, final int childSizeHint) - throws IOException { - getDelegate().startContainerNode(enter(object, NodeIdentifier.class), childSizeHint); - } - - @Override - public void startLeafSet(final String localName, final int childSizeHint) throws IOException { - final NodeIdentifier id = enter(localName, NodeIdentifier.class); - emitSchema(current().getSchema()); - getDelegate().startLeafSet(id, childSizeHint); - } - - @Override - public void startOrderedLeafSet(final String localName, final int childSizeHint) throws IOException { - getDelegate().startOrderedLeafSet(enter(localName, NodeIdentifier.class), childSizeHint); - } - - @Override - public void startMapEntryNode(final IdentifiableItem keyValues, - final int childSizeHint) throws IOException { - duplicateSchemaEnter(); - final NodeIdentifierWithPredicates identifier = ((KeyedListNodeCodecContext) current()).serialize(keyValues); - getDelegate().startMapEntryNode(identifier, childSizeHint); - } - - @Override - public > void startMapNode(final Class mapEntryType, - final int childSizeHint) throws IOException { - getDelegate().startMapNode(enter(mapEntryType, NodeIdentifier.class), childSizeHint); - } - - @Override - public > void startOrderedMapNode(final Class mapEntryType, - final int childSizeHint) throws IOException { - getDelegate().startOrderedMapNode(enter(mapEntryType, NodeIdentifier.class), childSizeHint); - } - - @Override - public void startUnkeyedList(final Class localName, final int childSizeHint) - throws IOException { - getDelegate().startUnkeyedList(enter(localName, NodeIdentifier.class), childSizeHint); - } - - @Override - public void startUnkeyedListItem(final int childSizeHint) throws IOException { - getDelegate().startUnkeyedListItem(duplicateSchemaEnter(), childSizeHint); - } - - @Override - public void flush() throws IOException { - getDelegate().flush(); - } - - @Override - public void close() throws IOException { - getDelegate().close(); - } - - @Override - public void startAnydataNode(final String name, final Object value) throws IOException { - // TODO will be done when https://bugs.opendaylight.org/show_bug.cgi?id=8516 is completed - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/CachingNormalizedNodeSerializer.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/CachingNormalizedNodeSerializer.java deleted file mode 100644 index b377e0e0e5..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/CachingNormalizedNodeSerializer.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache.AbstractBindingNormalizedNodeCacheHolder; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.cache.BindingNormalizedNodeCache; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.DataContainerCodecContext; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; - -/** - * Serializer of Binding objects to Normalized Node which uses - * {@link BindingNormalizedNodeCache} to cache already serialized values. - * - *

- * This serializer implements {@link BindingStreamEventWriter} along with - * {@link BindingSerializer}. - * - * {@link BindingSerializer} interface is used by generated implementations of - * {@link TreeNodeSerializer} to provide Binding object for inspection and to - * prevent streaming of already serialized object. - */ -@Beta -public final class CachingNormalizedNodeSerializer extends ForwardingBindingStreamEventWriter - implements BindingSerializer { - - private final NormalizedNodeResult domResult; - private final NormalizedNodeWithAddChildWriter domWriter; - private final BindingToNormalizedStreamWriter delegate; - private final AbstractBindingNormalizedNodeCacheHolder cacheHolder; - - private CachingNormalizedNodeSerializer(final AbstractBindingNormalizedNodeCacheHolder cacheHolder, - final DataContainerCodecContext subtreeRoot) { - this.cacheHolder = cacheHolder; - this.domResult = new NormalizedNodeResult(); - this.domWriter = new NormalizedNodeWithAddChildWriter(domResult); - this.delegate = BindingToNormalizedStreamWriter.create(subtreeRoot, domWriter); - } - - @Override - protected BindingStreamEventWriter delegate() { - return delegate; - } - - private NormalizedNode build() { - return domResult.getResult(); - } - - /** - * Serializes input if it is cached, returns null otherwise. - * - *

- * If input is cached it uses - * {@link NormalizedNodeWithAddChildWriter#addChild(NormalizedNode)} to - * provide already serialized value to underlying NormalizedNodeWriter in - * order to reuse value instead of creating new one using Normalized Node - * stream APIs. - * - *

- * Note that this optional is serialization of child node invoked from - * {@link TreeNodeSerializer}, which may opt-out from streaming of data when - * non-null result is returned. - */ - @Override - public NormalizedNode serialize(final TreeNode input) { - // Binding data input MUST be an instance of Instantiable too. - Preconditions.checkArgument(input instanceof Instantiable, "Input %s is not instantiable", input); - - final BindingNormalizedNodeCache cachingSerializer = - getCacheSerializer(((Instantiable) input).implementedInterface()); - if (cachingSerializer != null) { - final NormalizedNode domData = cachingSerializer.get(input); - domWriter.addChild(domData); - return domData; - } - return null; - } - - /** - * Serializes supplied data using stream writer with child cache enabled or - * using cache directly if cache is avalaible also for supplied Codec node. - * - * @param cacheHolder - * - Binding to Normalized Node Cache holder - * @param subtreeRoot - * - codec Node for provided data object - * @param data - * - data to be serialized - * @return Normalized Node representation of data - */ - public static NormalizedNode serialize(final AbstractBindingNormalizedNodeCacheHolder cacheHolder, - final DataContainerCodecContext subtreeRoot, final TreeNode data) { - final BindingNormalizedNodeCache cache = cacheHolder.getCachingSerializer(subtreeRoot); - if (cache != null) { - return cache.get(data); - } - return serializeUsingStreamWriter(cacheHolder, subtreeRoot, data); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private BindingNormalizedNodeCache getCacheSerializer(final Class type) { - if (cacheHolder.isCached(type)) { - final DataContainerCodecContext currentCtx = (DataContainerCodecContext) delegate.current(); - if (type.equals(currentCtx.getBindingClass())) { - return cacheHolder.getCachingSerializer(currentCtx); - } - return cacheHolder.getCachingSerializer(currentCtx.streamChild(type)); - } - return null; - } - - /** - * Serializes supplied data using stream writer with child cache enabled. - * - * @param cacheHolder - * - binding to Normalized Node Cache holder - * @param subtreeRoot - * - codec Node for provided data object - * @param data - * - data to be serialized - * @return Normalized Node representation of data - */ - public static NormalizedNode serializeUsingStreamWriter( - final AbstractBindingNormalizedNodeCacheHolder cacheHolder, - final DataContainerCodecContext subtreeRoot, final TreeNode data) { - final CachingNormalizedNodeSerializer writer = new CachingNormalizedNodeSerializer(cacheHolder, subtreeRoot); - try { - subtreeRoot.eventStreamSerializer().serialize(data, writer); - return writer.build(); - } catch (final IOException e) { - throw Throwables.propagate(e); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ChoiceDispatchSerializer.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ChoiceDispatchSerializer.java deleted file mode 100644 index 9605fa300f..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ChoiceDispatchSerializer.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerImplementation; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializerRegistry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Dispatch serializer, which emit DOM data from Binding v2 via stream writer. - */ -@Beta -public final class ChoiceDispatchSerializer implements TreeNodeSerializerImplementation { - - private static final Logger LOG = LoggerFactory.getLogger(ChoiceDispatchSerializer.class); - - @SuppressWarnings("rawtypes") - private final Class choiceClass; - - @SuppressWarnings("rawtypes") - private ChoiceDispatchSerializer(final Class choiceClass) { - this.choiceClass = requireNonNull(choiceClass); - } - - /** - * Prepare instance of serializer from choice class. - * - * @param choiceClass - * - class choice - * @return instance of serializer - */ - public static ChoiceDispatchSerializer from(final Class> choiceClass) { - return new ChoiceDispatchSerializer(choiceClass); - } - - @SuppressWarnings("unchecked") - @Override - public void serialize(final TreeNodeSerializerRegistry reg, final TreeNode obj, - final BindingStreamEventWriter stream) throws IOException { - @SuppressWarnings("rawtypes") - final Class cazeClass = ((Instantiable) obj).implementedInterface(); - stream.startChoiceNode(new Item<>(choiceClass), BindingStreamEventWriter.UNKNOWN_SIZE); - final TreeNodeSerializer caseSerializer = reg.getSerializer(cazeClass); - if (caseSerializer != null) { - caseSerializer.serialize(obj, stream); - } else { - LOG.warn("No serializer for case {} is available in registry {}", cazeClass, reg); - } - stream.endNode(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ForwardingBindingStreamEventWriter.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ForwardingBindingStreamEventWriter.java deleted file mode 100644 index 29bb6e9a40..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/ForwardingBindingStreamEventWriter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import com.google.common.annotations.Beta; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * Forwarding of event stream writer of Binding v2 representation. - */ -@Beta -abstract class ForwardingBindingStreamEventWriter implements BindingStreamEventWriter { - - protected abstract BindingStreamEventWriter delegate(); - - @Override - public void leafNode(final String localName, final Object value) throws IOException { - delegate().leafNode(localName, value); - } - - @Override - public void startLeafSet(final String localName, final int childSizeHint) throws IOException { - delegate().startLeafSet(localName, childSizeHint); - } - - @Override - public void startOrderedLeafSet(final String localName, final int childSizeHint) throws IOException { - delegate().startOrderedLeafSet(localName, childSizeHint); - } - - @Override - public void leafSetEntryNode(final Object value) throws IOException { - delegate().leafSetEntryNode(value); - } - - @Override - public void startContainerNode(final Class container, final int childSizeHint) - throws IOException { - delegate().startContainerNode(container, childSizeHint); - } - - @Override - public void startUnkeyedList(final Class localName, final int childSizeHint) - throws IOException { - delegate().startUnkeyedList(localName, childSizeHint); - } - - @Override - public void startUnkeyedListItem(final int childSizeHint) throws IOException { - delegate().startUnkeyedListItem(childSizeHint); - } - - @Override - public > void startMapNode(final Class mapEntryType, - final int childSizeHint) throws IOException { - delegate().startMapNode(mapEntryType, childSizeHint); - } - - @Override - public > void startOrderedMapNode(final Class mapEntryType, - final int childSizeHint) throws IOException { - delegate().startOrderedMapNode(mapEntryType, childSizeHint); - } - - @Override - public void startMapEntryNode(final IdentifiableItem keyValues, - final int childSizeHint) throws IOException { - delegate().startMapEntryNode(keyValues, childSizeHint); - } - - @Override - public void startChoiceNode(final Item choice, final int childSizeHint) throws IOException { - delegate().startChoiceNode(choice, childSizeHint); - } - - @Override - public void startCase(final Class caze, final int childSizeHint) throws IOException { - delegate().startCase(caze, childSizeHint); - } - - @Override - public void startAugmentationNode(final Class> augmentationType) throws IOException { - delegate().startAugmentationNode(augmentationType); - } - - @Override - public void anyxmlNode(final String name, final Object value) throws IOException { - delegate().anyxmlNode(name, value); - } - - @Override - public void startAnydataNode(final String name, final Object value) throws IOException { - delegate().startAnydataNode(name, value); - } - - @Override - public void endNode() throws IOException { - delegate().endNode(); - } - - @Override - public void flush() throws IOException { - delegate().flush(); - } - - @Override - public void close() throws IOException { - delegate().close(); - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/NormalizedNodeWithAddChildWriter.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/NormalizedNodeWithAddChildWriter.java deleted file mode 100644 index f7a3e5de44..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/serializer/NormalizedNodeWithAddChildWriter.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.serializer; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter; -import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult; - -/** - * Event Stream Writer based on Normalized Node tree representation with - * allowing to add children. - * - */ -@Beta -final class NormalizedNodeWithAddChildWriter extends ImmutableNormalizedNodeStreamWriter { - - /** - * Initialization writer based on {@link NormalizedNodeResult}. - * - * @param result - * - result holder for writer - */ - NormalizedNodeWithAddChildWriter(final NormalizedNodeResult result) { - super(result); - } - - void addChild(final NormalizedNode child) { - this.writeChild(child); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/BitsCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/BitsCodec.java deleted file mode 100644 index 36b870c0e9..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/BitsCodec.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.Callable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec.SchemaUnawareCodec; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit; - -@Beta -final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec { - - private static final MethodType CONSTRUCTOR_INVOKE_TYPE = MethodType.methodType(Object.class, Boolean[].class); - // Ordered by position - private final Map getters; - // Ordered by lexical name - private final Set ctorArgs; - private final MethodHandle ctor; - - private BitsCodec(final Class typeClass, final MethodHandle ctor, final Set ctorArgs, - final Map getters) { - - super(typeClass); - this.ctor = requireNonNull(ctor); - this.ctorArgs = ImmutableSet.copyOf(ctorArgs); - this.getters = ImmutableMap.copyOf(getters); - } - - static Callable loader(final Class returnType, final BitsTypeDefinition rootType) { - return () -> { - final Map getters = new LinkedHashMap<>(); - final Set ctorArgs = new TreeSet<>(); - - for (Bit bit : rootType.getBits()) { - final Method valueGetter = returnType.getMethod("is" + JavaIdentifierNormalizer - .normalizeSpecificIdentifier(bit.getName(), JavaIdentifier.CLASS)); - ctorArgs.add(bit.getName()); - getters.put(bit.getName(), valueGetter); - } - Constructor constructor = null; - for (Constructor cst : returnType.getConstructors()) { - if (!cst.getParameterTypes()[0].equals(returnType)) { - constructor = cst; - } - } - - final MethodHandle ctor = MethodHandles.publicLookup().unreflectConstructor(constructor) - .asSpreader(Boolean[].class, ctorArgs.size()).asType(CONSTRUCTOR_INVOKE_TYPE); - return new BitsCodec(returnType, ctor, ctorArgs, getters); - }; - } - - @Override - @SuppressWarnings("checkstyle:illegalCatch") - public Object deserialize(Object input) { - Preconditions.checkArgument(input instanceof Set); - @SuppressWarnings("unchecked") - final Set casted = (Set) input; - - /* - * We can do this walk based on field set sorted by name, - * since constructor arguments in Java Binding are sorted by name. - * - * This means we will construct correct array for construction - * of bits object. - */ - final Boolean[] args = new Boolean[ctorArgs.size()]; - int currentArg = 0; - for (String value : ctorArgs) { - args[currentArg++] = casted.contains(value); - } - - try { - return ctor.invokeExact(args); - } catch (Throwable e) { - throw new IllegalStateException("Failed to instantiate object for " + input, e); - } - } - - @Override - public Object serialize(Object input) { - final Collection result = new ArrayList<>(getters.size()); - for (Entry valueGet : getters.entrySet()) { - final Boolean value; - try { - value = (Boolean) valueGet.getValue().invoke(input); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new IllegalArgumentException("Failed to get bit " + valueGet.getKey(), e); - } - - if (value) { - result.add(valueGet.getKey()); - } - } - return result.size() == getters.size() ? getters.keySet() : ImmutableSet.copyOf(result); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/CompositeValueCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/CompositeValueCodec.java deleted file mode 100644 index ee8d758ebf..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/CompositeValueCodec.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.concepts.Codec; - -@Beta -final class CompositeValueCodec extends ValueTypeCodec { - - private final SchemaUnawareCodec bindingToSimpleType; - - @SuppressWarnings("rawtypes") - private final Codec bindingToDom; - - CompositeValueCodec(final SchemaUnawareCodec extractor, @SuppressWarnings("rawtypes") final Codec delegate) { - this.bindingToSimpleType = extractor; - this.bindingToDom = delegate; - } - - @SuppressWarnings("unchecked") - @Override - public Object deserialize(Object input) { - return bindingToSimpleType.deserialize(bindingToDom.deserialize(input)); - } - - @SuppressWarnings("unchecked") - @Override - public Object serialize(Object input) { - return bindingToDom.serialize(bindingToSimpleType.serialize(input)); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EncapsulatedValueCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EncapsulatedValueCodec.java deleted file mode 100644 index 8dc0b02855..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EncapsulatedValueCodec.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Throwables; -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.concurrent.Callable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec.SchemaUnawareCodec; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition; - -/** - * Derived YANG types are just immutable value holders for simple value - * types, which are same as in NormalizedNode model. - */ -@Beta -public final class EncapsulatedValueCodec extends ReflectionBasedCodec implements SchemaUnawareCodec { - - private static final Lookup LOOKUP = MethodHandles.publicLookup(); - private static final MethodType OBJ_METHOD = MethodType.methodType(Object.class, Object.class); - private final MethodHandle constructor; - private final MethodHandle getter; - private final Class valueType; - - private EncapsulatedValueCodec(final Class typeClz, final MethodHandle constructor, final MethodHandle getter, - final Class valueType) { - - super(typeClz); - this.constructor = requireNonNull(constructor); - this.getter = requireNonNull(getter); - this.valueType = requireNonNull(valueType); - } - - static Callable loader(final Class typeClz, final TypeDefinition typeDef) { - return () -> { - final Method m; - if (typeDef instanceof BooleanTypeDefinition) { - m = typeClz.getMethod("isValue"); - } else { - m = typeClz.getMethod("getValue"); - } - final MethodHandle getter = LOOKUP.unreflect(m).asType(OBJ_METHOD); - final Class valueType = m.getReturnType(); - - final MethodHandle constructor = LOOKUP.findConstructor(typeClz, - MethodType.methodType(void.class, valueType)).asType(OBJ_METHOD); - return new EncapsulatedValueCodec(typeClz, constructor, getter, valueType); - }; - } - - /** - * Quick check if a value object has a chance to deserialize using {@link #deserialize(Object)}. - * - * @param value Value to be checked - * @return True if the value can be encapsulated - */ - public boolean canAcceptObject(final Object value) { - return valueType.isInstance(value); - } - - @Override - @SuppressWarnings("checkstyle:illegalCatch") - public Object deserialize(final Object input) { - try { - return constructor.invokeExact(input); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - } - - @Override - @SuppressWarnings("checkstyle:illegalCatch") - public Object serialize(final Object input) { - try { - return getter.invokeExact(input); - } catch (final Throwable e) { - throw Throwables.propagate(e); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodec.java deleted file mode 100644 index 3918ea8c3c..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodec.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableBiMap; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Callable; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec.SchemaUnawareCodec; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair; - -@Beta -final class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec { - - private final ImmutableBiMap> yangValueToBinding; - - private EnumerationCodec(final Class> enumeration, final Map> schema) { - super(enumeration); - yangValueToBinding = ImmutableBiMap.copyOf(schema); - } - - static Callable loader(final Class returnType, final EnumTypeDefinition enumSchema) { - Preconditions.checkArgument(Enum.class.isAssignableFrom(returnType)); - @SuppressWarnings({ "rawtypes", "unchecked" }) - final Class> enumType = (Class) returnType; - return () -> { - final Map> nameToValue = new HashMap<>(); - for (final Enum enumValue : enumType.getEnumConstants()) { - nameToValue.put(enumValue.toString(), enumValue); - } - final Map> yangNameToBinding = new HashMap<>(); - for (final EnumPair yangValue : enumSchema.getValues()) { - final String bindingName = JavaIdentifierNormalizer.normalizeSpecificIdentifier(yangValue.getName(), - JavaIdentifier.ENUM_VALUE); - final Enum bindingVal = nameToValue.get(bindingName); - yangNameToBinding.put(yangValue.getName(), bindingVal); - } - return new EnumerationCodec(enumType, yangNameToBinding); - }; - } - - @Override - public Object deserialize(final Object input) { - final Enum value = yangValueToBinding.get(input); - Preconditions.checkArgument(value != null, "Invalid enumeration value %s. Valid values are %s", input, - yangValueToBinding.keySet()); - return value; - } - - @Override - public Object serialize(final Object input) { - Preconditions.checkArgument(getTypeClass().isInstance(input), "Input must be instance of %s", getTypeClass()); - return yangValueToBinding.inverse().get(input); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ReflectionBasedCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ReflectionBasedCodec.java deleted file mode 100644 index d9f1bc89aa..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ReflectionBasedCodec.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; - -@Beta -public abstract class ReflectionBasedCodec extends ValueTypeCodec { - - private final Class typeClass; - - protected ReflectionBasedCodec(final Class typeClass) { - this.typeClass = requireNonNull(typeClass); - } - - protected final Class getTypeClass() { - return typeClass; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ValueTypeCodec.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ValueTypeCodec.java deleted file mode 100644 index 5a0dbe05db..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/ValueTypeCodec.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import com.google.common.annotations.Beta; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.yangtools.concepts.Codec; -import org.opendaylight.yangtools.yang.common.Empty; -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.EmptyTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; - -/** - * Value codec, which serializes / de-serializes values from DOM simple values. - */ -@Beta -public abstract class ValueTypeCodec implements Codec { - - private static final Cache, SchemaUnawareCodec> STATIC_CODECS = CacheBuilder.newBuilder().weakKeys() - .build(); - - /** - * Marker interface for codecs, which functionality will not be - * affected by schema change (introduction of new YANG modules) - * they may have one static instance generated when - * first time needed. - */ - interface SchemaUnawareCodec extends Codec { - } - - /** - * No-op Codec, Java YANG Binding uses same types as NormalizedNode model - * for base YANG types, representing numbers, binary and strings. - */ - public static final SchemaUnawareCodec NOOP_CODEC = new SchemaUnawareCodec() { - - @Override - public Object serialize(final Object input) { - return input; - } - - @Override - public Object deserialize(final Object input) { - return input; - } - }; - - public static final SchemaUnawareCodec EMPTY_CODEC = new SchemaUnawareCodec() { - - @Override - public Object serialize(final Object arg0) { - // Empty type has null value in NormalizedNode and Composite Node - // representation - return Empty.getInstance(); - } - - @Override - public Object deserialize(final Object arg0) { - /* Empty type has Empty representation in Binding-aware world - * otherwise it is null. - * So when codec is triggered, empty leaf is present and its - * value is Empty.getInstance(), that means we are safe to - * return it directly. - */ - return arg0; - } - }; - - public static SchemaUnawareCodec getCodecFor(final Class typeClz, final TypeDefinition def) { - if (BindingReflections.isBindingClass(typeClz)) { - return getCachedSchemaUnawareCodec(typeClz, getCodecLoader(typeClz, def)); - } - return def instanceof EmptyTypeDefinition ? EMPTY_CODEC : NOOP_CODEC; - } - - private static SchemaUnawareCodec getCachedSchemaUnawareCodec(final Class typeClz, - final Callable loader) { - try { - return STATIC_CODECS.get(typeClz, loader); - } catch (final ExecutionException e) { - throw new IllegalStateException(e); - } - } - - private static Callable getCodecLoader(final Class typeClz, - final TypeDefinition def) { - TypeDefinition rootType = def; - while (rootType.getBaseType() != null) { - rootType = rootType.getBaseType(); - } - if (rootType instanceof EnumTypeDefinition) { - return EnumerationCodec.loader(typeClz, (EnumTypeDefinition) rootType); - } else if (rootType instanceof BitsTypeDefinition) { - return BitsCodec.loader(typeClz, (BitsTypeDefinition) rootType); - } - - return EncapsulatedValueCodec.loader(typeClz, def); - } - - @SuppressWarnings("rawtypes") - public static ValueTypeCodec encapsulatedValueCodecFor(final Class typeClz, final TypeDefinition typeDef, - final Codec delegate) { - final SchemaUnawareCodec extractor = getCachedSchemaUnawareCodec(typeClz, - EncapsulatedValueCodec.loader(typeClz, typeDef)); - return new CompositeValueCodec(extractor, delegate); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/BindingStructuralType.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/BindingStructuralType.java deleted file mode 100644 index 4963395d0d..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/BindingStructuralType.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.modification; - -import com.google.common.annotations.Beta; -import java.util.Optional; -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; -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.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode; - -/** - * Defines structural mapping of Normalized Node to Binding data addressable by Instance Identifier. - * - *

- * Not all binding data are addressable by instance identifier and there are some differences. - * - *

- * See {@link #NOT_ADDRESSABLE},{@link #INVISIBLE_CONTAINER},{@link #VISIBLE_CONTAINER} for more details. - */ -@Beta -enum BindingStructuralType { - - /** - * DOM Item is not addressable in Binding Instance Identifier, data is not lost, but are available only - * via parent object. - * - *

- * Such types of data are leaf-lists, leafs, list without keys or anyxml. - * - */ - NOT_ADDRESSABLE, - /** - * Data container is addressable in NormalizedNode format, but in Binding it is not represented in - * Instance Identifier. - * - *

- * This are choice / case nodes. - * - *

- * This data is still accessible using parent object and their children are addressable. - * - */ - INVISIBLE_CONTAINER, - /** - * Data container is addressable in NormalizedNode format, but in Binding it is not represented in - * Instance Identifier. - * - *

- * This are list nodes. - * - *

- * This data is still accessible using parent object and their children are addressable. - * - */ - INVISIBLE_LIST, - /** - * Data container is addressable in Binding Instance Identifier format and also YangInstanceIdentifier - * format. - * - */ - VISIBLE_CONTAINER, - /** - * Mapping algorithm was unable to detect type or was not updated after introduction of new NormalizedNode - * type. - */ - UNKNOWN; - - static BindingStructuralType from(final DataTreeCandidateNode domChildNode) { - Optional> dataBased = domChildNode.getDataAfter(); - if (!dataBased.isPresent()) { - dataBased = domChildNode.getDataBefore(); - } - if (dataBased.isPresent()) { - return from(dataBased.get()); - } - return from(domChildNode.getIdentifier()); - } - - private static BindingStructuralType from(final PathArgument identifier) { - if (identifier instanceof NodeIdentifierWithPredicates || identifier instanceof AugmentationIdentifier) { - return VISIBLE_CONTAINER; - } - if (identifier instanceof NodeWithValue) { - return NOT_ADDRESSABLE; - } - return UNKNOWN; - } - - static BindingStructuralType from(final NormalizedNode data) { - if (isNotAddressable(data)) { - return NOT_ADDRESSABLE; - } - if (data instanceof MapNode) { - return INVISIBLE_LIST; - } - if (data instanceof ChoiceNode) { - return INVISIBLE_CONTAINER; - } - if (isVisibleContainer(data)) { - return VISIBLE_CONTAINER; - } - return UNKNOWN; - } - - private static boolean isVisibleContainer(final NormalizedNode data) { - return data instanceof MapEntryNode || data instanceof ContainerNode || data instanceof AugmentationNode; - } - - private static boolean isNotAddressable(final NormalizedNode normalizedNode) { - return normalizedNode instanceof LeafNode || normalizedNode instanceof AnyXmlNode - || normalizedNode instanceof LeafSetNode || normalizedNode instanceof LeafSetEntryNode; - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModification.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModification.java deleted file mode 100644 index 6a127dfaa1..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModification.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.modification; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map.Entry; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeModification; -import org.opendaylight.mdsal.binding.javav2.api.TreeNodeModification; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate; -import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate; - -/** - * Lazily translated {@link DataTreeModification} based on {@link DataTreeCandidate}. - * - *

- * {@link DataTreeModification} represents Data tree change event, but whole tree is not translated or - * resolved eagerly, but only child nodes which are directly accessed by user of tree node modification. - * - */ -@Beta -public final class LazyDataTreeModification implements DataTreeModification { - - private final DataTreeIdentifier path; - private final TreeNodeModification rootNode; - - private LazyDataTreeModification(final DataTreeIdentifier path, final TreeNodeModification modification) { - this.path = requireNonNull(path); - this.rootNode = requireNonNull(modification); - } - - @Nonnull - @Override - public TreeNodeModification getRootNode() { - return rootNode; - } - - @Nonnull - @Override - public DataTreeIdentifier getRootPath() { - return path; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static DataTreeModification create(final BindingToNormalizedNodeCodec codec, - final DataTreeCandidate domChange, final LogicalDatastoreType datastoreType) { - final Entry, BindingTreeNodeCodec> codecCtx = - codec.getSubtreeCodec(domChange.getRootPath()); - final DataTreeIdentifier path = DataTreeIdentifier.create(datastoreType, codecCtx.getKey()); - final TreeNodeModification modification = - LazyTreeNodeModification.create(codecCtx.getValue(), domChange.getRootNode()); - return new LazyDataTreeModification(path, modification); - } - - /** - * Create instance of Binding date tree modification according to DOM candidate of changes. - * - * @param codec - * - codec for modificated data - * @param candidate - * - changted DOM data - * @return modificated data tree - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static DataTreeModification create(final BindingToNormalizedNodeCodec codec, - final DOMDataTreeCandidate candidate) { - final Entry, BindingTreeNodeCodec> codecCtx = - codec.getSubtreeCodec(candidate.getRootPath().getRootIdentifier()); - final DataTreeIdentifier path = - DataTreeIdentifier.create(candidate.getRootPath().getDatastoreType(), codecCtx.getKey()); - final TreeNodeModification modification = - LazyTreeNodeModification.create(codecCtx.getValue(), candidate.getRootNode()); - return new LazyDataTreeModification(path, modification); - } - - /** - * DOM data changes to new Binding data. - * - * @param codec - * - Binding to DOM codec - * @param domChanges - * - DOM data changes - * @param datastoreType - * - datastore type - * @return collection of new Binding data according to DOM data changes - */ - public static Collection> from( - final BindingToNormalizedNodeCodec codec, final Collection domChanges, - final LogicalDatastoreType datastoreType) { - final List> result = new ArrayList<>(domChanges.size()); - for (final DataTreeCandidate domChange : domChanges) { - result.add(LazyDataTreeModification.create(codec, domChange, datastoreType)); - } - return result; - } - -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyTreeNodeModification.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyTreeNodeModification.java deleted file mode 100644 index f22ba6f4f5..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyTreeNodeModification.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.modification; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.api.TreeNodeModification; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -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.tree.DataTreeCandidateNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Lazily translated {@link TreeNodeModification} based on {@link DataTreeCandidateNode}. - * - *

- * {@link LazyTreeNodeModification} represents Data tree change event, but whole tree is not translated or - * resolved eagerly, but only child nodes which are directly accessed by user of tree node modification. - * - * @param - * Type of Binding Tree Node - */ -@Beta -final class LazyTreeNodeModification implements TreeNodeModification { - - private static final Logger LOG = LoggerFactory.getLogger(LazyTreeNodeModification.class); - - private final BindingTreeNodeCodec codec; - private final DataTreeCandidateNode domData; - private final TreeArgument identifier; - private Collection> childNodesCache; - - private LazyTreeNodeModification(final BindingTreeNodeCodec codec, final DataTreeCandidateNode domData) { - this.codec = requireNonNull(codec); - this.domData = requireNonNull(domData); - this.identifier = codec.deserializePathArgument(domData.getIdentifier()); - } - - static TreeNodeModification create(final BindingTreeNodeCodec codec, - final DataTreeCandidateNode domData) { - return new LazyTreeNodeModification<>(codec, domData); - } - - private static Collection> from(final BindingTreeNodeCodec parentCodec, - final Collection domChildNodes) { - final List> result = new ArrayList<>(domChildNodes.size()); - populateList(result, parentCodec, domChildNodes); - return result; - } - - private static void populateList(final List> result, - final BindingTreeNodeCodec parentCodec, final Collection domChildNodes) { - for (final DataTreeCandidateNode domChildNode : domChildNodes) { - final BindingStructuralType type = BindingStructuralType.from(domChildNode); - if (type != BindingStructuralType.NOT_ADDRESSABLE) { - /* - * Even if type is UNKNOWN, from perspective of BindingStructuralType we try to load codec for - * it. We will use that type to further specify debug log. - */ - try { - final BindingTreeNodeCodec childCodec = - parentCodec.yangPathArgumentChild(domChildNode.getIdentifier()); - populateList(result, type, childCodec, domChildNode); - } catch (final IllegalArgumentException e) { - if (type == BindingStructuralType.UNKNOWN) { - LOG.debug("Unable to deserialize unknown DOM node {}", domChildNode, e); - } else { - LOG.debug("Binding representation for DOM node {} was not found", domChildNode, e); - } - } - } - } - } - - private static void populateList(final List> result, - final BindingStructuralType type, final BindingTreeNodeCodec childCodec, - final DataTreeCandidateNode domChildNode) { - switch (type) { - case INVISIBLE_LIST: - // We use parent codec intentionally. - populateListWithSingleCodec(result, childCodec, domChildNode.getChildNodes()); - break; - case INVISIBLE_CONTAINER: - populateList(result, childCodec, domChildNode.getChildNodes()); - break; - case UNKNOWN: - case VISIBLE_CONTAINER: - result.add(create(childCodec, domChildNode)); - break; - default: - } - } - - private static void populateListWithSingleCodec(final List> result, - final BindingTreeNodeCodec codec, final Collection childNodes) { - for (final DataTreeCandidateNode child : childNodes) { - result.add(create(codec, child)); - } - } - - @Nullable - @Override - public T getDataBefore() { - return deserialize(domData.getDataBefore()); - } - - @Nullable - @Override - public T getDataAfter() { - return deserialize(domData.getDataAfter()); - } - - @Nonnull - @Override - public Class getDataType() { - return codec.getBindingClass(); - } - - @Nonnull - @Override - public TreeArgument getIdentifier() { - return identifier; - } - - @Nonnull - @Override - public TreeNodeModification.ModificationType getModificationType() { - switch (domData.getModificationType()) { - case APPEARED: - case WRITE: - return TreeNodeModification.ModificationType.WRITE; - case SUBTREE_MODIFIED: - return TreeNodeModification.ModificationType.SUBTREE_MODIFIED; - case DISAPPEARED: - case DELETE: - return TreeNodeModification.ModificationType.DELETE; - - default: - // TODO: Should we lie about modification type instead of exception? - throw new IllegalStateException("Unsupported DOM Modification type " + domData.getModificationType()); - } - } - - @Nonnull - @Override - public Collection> getModifiedChildren() { - if (childNodesCache == null) { - childNodesCache = from(codec, domData.getChildNodes()); - } - return childNodesCache; - } - - @SuppressWarnings("unchecked") - @Override - public > Collection> - getModifiedChildren(@Nonnull final Class childType) { - final List> children = new ArrayList<>(); - for (final TreeNodeModification potential : getModifiedChildren()) { - if (childType.isAssignableFrom(potential.getDataType())) { - children.add((TreeNodeModification) potential); - } - } - return children; - } - - @SuppressWarnings("rawtypes") - @Nullable - @Override - public TreeNodeModification getModifiedChild(final TreeArgument childArgument) { - final List domArgumentList = new ArrayList<>(); - final BindingTreeNodeCodec childCodec = codec.bindingPathArgumentChild(childArgument, domArgumentList); - final Iterator toEnter = domArgumentList.iterator(); - DataTreeCandidateNode current = domData; - while (toEnter.hasNext() && current != null) { - current = current.getModifiedChild(toEnter.next()); - } - if (current != null) { - return create(childCodec, current); - } - return null; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public & TreeChildNode, K extends IdentifiableItem> - TreeNodeModification - getModifiedChildListItem(@Nonnull final Class listItem, @Nonnull final K listKey) { - return (TreeNodeModification) getModifiedChild(new IdentifiableItem(listItem, listKey)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Nullable - @Override - public > TreeNodeModification - getModifiedChildContainer(@Nonnull final Class child) { - return (TreeNodeModification) getModifiedChild(new Item(child)); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Nullable - @Override - public & TreeNode> TreeNodeModification - getModifiedAugmentation(@Nonnull final Class augmentation) { - return (TreeNodeModification) getModifiedChild(new Item(augmentation)); - } - - private T deserialize(final Optional> dataAfter) { - if (dataAfter.isPresent()) { - return codec.deserialize(dataAfter.get()); - } - return null; - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedContainerNode.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedContainerNode.java deleted file mode 100644 index 0338a80fd4..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedContainerNode.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.serialized; - -import java.util.Collection; -import java.util.Map; -import java.util.Optional; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -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.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; -import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -/** - * Serialize operation from binding to DOM. - */ -public class LazySerializedContainerNode implements ContainerNode { - - private final NodeIdentifier identifier; - private final TreeNode bindingData; - - private BindingNormalizedNodeCodecRegistry registry; - private ContainerNode domData; - - private LazySerializedContainerNode(final QName identifier, final TreeNode binding, - final BindingNormalizedNodeCodecRegistry registry) { - this.identifier = NodeIdentifier.create(identifier); - this.bindingData = binding; - this.registry = registry; - this.domData = null; - } - - /** - * Prepare serializer of binding data with specific codec. - * - * @param operationName - * - qname of operation - * @param data - * - binding operation - * @param codec - * - specifc codec for operation - * @return instance of lazy serialized container node - */ - public static NormalizedNode create(final SchemaPath operationName, final TreeNode data, - final BindingNormalizedNodeCodecRegistry codec) { - return new LazySerializedContainerNode(operationName.getLastComponent(), data, codec); - } - - /** - * Prepare serializer of binding data with specific codec and pre-cached serialized leaf holding routing - * information. - * - * @param operationName - * - operation name - * @param data - * - Binding data - * @param contextRef - * - leaf context reference - * @param codec - * - specific codec - * @return insntance of lazy serialized container node with pre-cached serialized leaf - */ - public static NormalizedNode withContextRef(final SchemaPath operationName, final TreeNode data, - final LeafNode contextRef, final BindingNormalizedNodeCodecRegistry codec) { - return new WithContextRef(operationName.getLastComponent(), data, contextRef, codec); - } - - @Override - public Map getAttributes() { - return delegate().getAttributes(); - } - - private ContainerNode delegate() { - if (domData == null) { - domData = registry.toNormalizedNodeOperationData(bindingData); - registry = null; - } - return domData; - } - - @Override - public final QName getNodeType() { - return identifier.getNodeType(); - } - - @Override - public final Collection> getValue() { - return delegate().getValue(); - } - - @Nonnull - @Override - public final NodeIdentifier getIdentifier() { - return identifier; - } - - @Override - public Optional> getChild(final PathArgument child) { - return delegate().getChild(child); - } - - @Override - public final Object getAttributeValue(final QName name) { - return delegate().getAttributeValue(name); - } - - /** - * Get binding data. - * - * @return binding data. - */ - public final TreeNode bindingData() { - return bindingData; - } - - /** - * Lazy Serialized Node with pre-cached serialized leaf holding routing information. - * - */ - private static final class WithContextRef extends LazySerializedContainerNode { - - private final LeafNode contextRef; - - private WithContextRef(final QName identifier, final TreeNode binding, final LeafNode contextRef, - final BindingNormalizedNodeCodecRegistry registry) { - super(identifier, binding, registry); - this.contextRef = contextRef; - } - - @Override - public Optional> getChild(final PathArgument child) { - /* - * Use precached value of routing field and do not run full serialization if we are accessing it. - */ - if (contextRef.getIdentifier().equals(child)) { - return Optional.of(contextRef); - } - return super.getChild(child); - } - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedDOMNotification.java b/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedDOMNotification.java deleted file mode 100644 index ace09cffc4..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/main/java/org/opendaylight/mdsal/binding/javav2/dom/codec/serialized/LazySerializedDOMNotification.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.serialized; - -import com.google.common.annotations.Beta; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.dom.api.DOMNotification; -import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; - -/** - * Lazy serialized implementation of DOM Notification. - * - *

- * This implementation performs serialization of data, only if receiver of notification actually accessed data - * from notification. - * - */ -@Beta -public final class LazySerializedDOMNotification implements DOMNotification { - - private final BindingNormalizedNodeSerializer codec; - private final Notification data; - private final SchemaPath type; - - private ContainerNode domBody; - - private LazySerializedDOMNotification(final BindingNormalizedNodeSerializer codec, final Notification data, - final SchemaPath type) { - this.codec = codec; - this.data = data; - this.type = type; - } - - /** - * Create serializer of Binding notification data to DOM notification with specific codec. - * - * @param codec - * - specific codec - * @param data - * - binding notification data - * @return DOM notification serializer - */ - public static DOMNotification create(final BindingNormalizedNodeSerializer codec, final Notification data) { - final SchemaPath type = SchemaPath.create(true, BindingReflections.findQName(data.getClass())); - return new LazySerializedDOMNotification(codec, data, type); - } - - @Nonnull - @Override - public SchemaPath getType() { - return type; - } - - @Nonnull - @Override - public ContainerNode getBody() { - if (domBody == null) { - domBody = codec.toNormalizedNodeNotification(data); - } - return domBody; - } - - /** - * Get binding notification data. - * - * @return binding notification data - */ - public Notification getBindingData() { - return data; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AbstractBindingRuntimeTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AbstractBindingRuntimeTest.java deleted file mode 100644 index dc94e5b6c1..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/AbstractBindingRuntimeTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import org.junit.Before; -import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext; -import org.opendaylight.mdsal.binding.javav2.runtime.context.ModuleInfoBackedContext; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -public abstract class AbstractBindingRuntimeTest { - - private SchemaContext schemaContext; - private BindingRuntimeContext runtimeContext; - - @Before - public void setup() { - final ModuleInfoBackedContext ctx = ModuleInfoBackedContext.create(); - ctx.addModuleInfos(BindingReflections.loadModuleInfos()); - schemaContext = ctx.tryToCreateSchemaContext().get(); - runtimeContext = BindingRuntimeContext.create(ctx, schemaContext); - - } - - public SchemaContext getSchemaContext() { - return schemaContext; - } - - public BindingRuntimeContext getRuntimeContext() { - return runtimeContext; - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierSerializeDeserializeTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierSerializeDeserializeTest.java deleted file mode 100644 index bc09a072f7..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierSerializeDeserializeTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.junit.Assert.assertEquals; - -import javassist.ClassPool; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.ChoiceContainer; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.choice_container.identifier.simple.SimpleId; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; - -public class InstanceIdentifierSerializeDeserializeTest extends AbstractBindingRuntimeTest { - private static final InstanceIdentifier BA_SIMPLE_ID = InstanceIdentifier - .builder(ChoiceContainer.class).child(SimpleId.class).build(); - - private static final QName CHOICE_CONTAINER_QNAME = ChoiceContainer.QNAME; - private static final QName SIMPLE_ID_QNAME = SimpleId.QNAME; - - - private static final YangInstanceIdentifier BI_SIMPLE_ID_PATH = YangInstanceIdentifier - .of(CHOICE_CONTAINER_QNAME).node(SIMPLE_ID_QNAME); - - private BindingNormalizedNodeCodecRegistry registry; - - @Override - @Before - public void setup() { - super.setup(); - final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault()); - registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils)); - registry.onBindingRuntimeContextUpdated(getRuntimeContext()); - } - - @Test - public void testYangIIToBindingAwareII() { - final InstanceIdentifier instanceIdentifier = registry.fromYangInstanceIdentifier(BI_SIMPLE_ID_PATH); - assertEquals(BA_SIMPLE_ID, instanceIdentifier); - } - - @Test - public void testBindingAwareIIToYangIContainer() { - final YangInstanceIdentifier yangInstanceIdentifier = registry.toYangInstanceIdentifier(BA_SIMPLE_ID); - assertEquals(BI_SIMPLE_ID_PATH, yangInstanceIdentifier); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierTest.java deleted file mode 100644 index c8febc9984..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/InstanceIdentifierTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.junit.Assert.assertTrue; - -import javassist.ClassPool; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.ChoiceContainer; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.Top; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.choice_container.identifier.extended.ExtendedId; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.top.TopLevelList; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.key.top.top_level_list.TopLevelListKey; - -public class InstanceIdentifierTest extends AbstractBindingRuntimeTest { - private static final InstanceIdentifier BA_TOP = InstanceIdentifier.builder(Top.class).build(); - private static final TopLevelListKey TOP_FOO_KEY = new TopLevelListKey("foo"); - private static final InstanceIdentifier BA_TOP_LEVEL_LIST = InstanceIdentifier.builder(Top.class) - .child(TopLevelList.class, TOP_FOO_KEY).build(); - private static final InstanceIdentifier BA_EXTEND_ID = InstanceIdentifier.builder(ChoiceContainer.class) - .child(ExtendedId.class).build(); - - private BindingNormalizedNodeCodecRegistry registry; - - @Override - public void setup() { - super.setup(); - final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault()); - registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils)); - registry.onBindingRuntimeContextUpdated(getRuntimeContext()); - } - - @Test - public void testInstanceIdentifierNormal() { - assertTrue(Top.getInstanceIdentifier().equals(BA_TOP)); - } - - @Test - public void testInstanceIdentifierOfList() { - assertTrue(TopLevelList.getInstanceIdentifier(TOP_FOO_KEY).equals(BA_TOP_LEVEL_LIST)); - } - - @Test - public void testInstanceIdentifierOfCase() { - assertTrue(ExtendedId.getInstanceIdentifier().equals(BA_EXTEND_ID)); - } - -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/LeafrefSerializeDeserializeTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/LeafrefSerializeDeserializeTest.java deleted file mode 100644 index 11d4f94937..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/LeafrefSerializeDeserializeTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.Map.Entry; -import javassist.ClassPool; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.Cont; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.Cont.Ref; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.ContInt32; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.ContInt32.RefUnionInt32; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.dto.ContBuilder; -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.dto.ContInt32Builder; -import org.opendaylight.yangtools.yang.common.Uint32; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; - -public class LeafrefSerializeDeserializeTest extends AbstractBindingRuntimeTest { - - private BindingNormalizedNodeCodecRegistry registry; - - @Override - @Before - public void setup() { - super.setup(); - final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault()); - this.registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils)); - this.registry.onBindingRuntimeContextUpdated(getRuntimeContext()); - } - - @Test - public void listReferenceTest() { - final YangInstanceIdentifier contYII = YangInstanceIdentifier.builder().node(Cont.QNAME).build(); - final InstanceIdentifier fromYangInstanceIdentifier = this.registry.fromYangInstanceIdentifier(contYII); - assertNotNull(fromYangInstanceIdentifier); - - final InstanceIdentifier BA_II_CONT = InstanceIdentifier.builder(Cont.class).build(); - final Ref refVal = new Ref("myvalue"); - final Cont data = new ContBuilder().setRef(refVal).build(); - final Entry> normalizedNode = - this.registry.toNormalizedNode(BA_II_CONT, data); - assertNotNull(normalizedNode); - - final Entry, TreeNode> fromNormalizedNode = - this.registry.fromNormalizedNode(contYII, normalizedNode.getValue()); - assertNotNull(fromNormalizedNode); - final Cont value = (Cont) fromNormalizedNode.getValue(); - assertEquals(refVal, value.getRef()); - } - - @Test - public void uint32LeafrefTest() { - final YangInstanceIdentifier contYII = YangInstanceIdentifier.builder().node(ContInt32.QNAME).build(); - final InstanceIdentifier fromYangInstanceIdentifier = this.registry.fromYangInstanceIdentifier(contYII); - assertNotNull(fromYangInstanceIdentifier); - - final InstanceIdentifier BA_II_CONT = InstanceIdentifier.builder(ContInt32.class).build(); - final RefUnionInt32 refVal = new RefUnionInt32(Uint32.valueOf(5L)); - final ContInt32 data = new ContInt32Builder().setRefUnionInt32(refVal).build(); - final Entry> normalizedNode = - this.registry.toNormalizedNode(BA_II_CONT, data); - assertNotNull(normalizedNode); - - final Entry, TreeNode> fromNormalizedNode = - this.registry.fromNormalizedNode(contYII, normalizedNode.getValue()); - assertNotNull(fromNormalizedNode); - final ContInt32 value = (ContInt32) fromNormalizedNode.getValue(); - assertEquals(refVal, value.getRefUnionInt32()); - } -} - diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodecTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodecTest.java deleted file mode 100644 index ce27f75b0e..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NonCachingCodecTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingNormalizedNodeCodec; - -public class NonCachingCodecTest { - - @SuppressWarnings({ "rawtypes", "unchecked", "resource" }) - @Test - public void basicTest() throws Exception { - final BindingNormalizedNodeCodec codec = mock(BindingNormalizedNodeCodec.class); - doReturn(null).when(codec).serialize(null); - doReturn(null).when(codec).deserialize(null); - final NonCachingCodec nonCachingCodec = new NonCachingCodec<>(codec); - nonCachingCodec.serialize(null); - verify(codec).serialize(null); - nonCachingCodec.deserialize(null); - verify(codec).deserialize(null); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NormalizedNodeSerializeDeserializeTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NormalizedNodeSerializeDeserializeTest.java deleted file mode 100644 index 531ff349d6..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/NormalizedNodeSerializeDeserializeTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.junit.Assert.assertEquals; -import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode; - -import com.google.common.collect.ImmutableList; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import javassist.ClassPool; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.augment.rev140709.data.TreeLeafOnlyUsesAugment; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.augment.rev140709.dto.TreeLeafOnlyUsesAugmentBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.augment.rev140709.grp.LeafFromGrouping; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.ChoiceContainer; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.Top; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.choice_container.identifier.simple.SimpleId; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.data.top.TopLevelList; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.dto.TopBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.dto.choice_container.identifier.simple.SimpleIdBuilder; -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.schema.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAugmentationNodeBuilder; -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.ImmutableMapNodeBuilder; - -public class NormalizedNodeSerializeDeserializeTest extends AbstractBindingRuntimeTest { - private BindingNormalizedNodeCodecRegistry registry; - private static final QName TOP_LEVEL_LIST_NAME_QNAME = QName.create(TopLevelList.QNAME, "name"); - private static final QName AUGMENTED_STRING_QNAME = QName.create(TopLevelList.QNAME, "augmented-string"); - private static final QName AUGMENTED_INT_QNAME = QName.create(TopLevelList.QNAME, "augmented-int"); - private static final QName SIMPLE_VALUE_QNAME = QName.create(LeafFromGrouping.QNAME, "simple-value"); - private static final QName SIMPLE_TYPE_QNAME = QName.create(LeafFromGrouping.QNAME, "simple-type"); - private static final QName CHOICE_CONTAINER_QNAME = ChoiceContainer.QNAME; - private static final QName SIMPLE_ID_QNAME = SimpleId.QNAME; - private static final QName SIMPLE_LEAF_ID_QNAME = QName.create(SimpleId.QNAME, "id"); - - private static final InstanceIdentifier BA_SIMPLE_ID = InstanceIdentifier - .builder(ChoiceContainer.class).child(SimpleId.class).build(); - private static final YangInstanceIdentifier BI_SIMPLE_ID_PATH = YangInstanceIdentifier - .of(CHOICE_CONTAINER_QNAME).node(SIMPLE_ID_QNAME); - - @Before - public void setup() { - super.setup(); - final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault()); - registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils)); - registry.onBindingRuntimeContextUpdated(getRuntimeContext()); - } - - private static Top topBindingData() { - final TopBuilder tb = new TopBuilder(); - tb.setTopLevelList(ImmutableList.of(new org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang - .mdsal.test.binding.rev140701.dto.top.TopLevelListBuilder() - .setIdentifier(new org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding - .rev140701.key.top.top_level_list.TopLevelListKey("test")) - .setName("test") - .addAugmentation(TreeLeafOnlyUsesAugment.class, - new TreeLeafOnlyUsesAugmentBuilder().setSimpleType(16).setSimpleValue("simple-value").build()) - .build())) - .setAugmentedInt(32) - .setAugmentedString("aug-string"); - return tb.build(); - } - - private static AugmentationIdentifier getTopLevelListAugId() { - Set qnames = new HashSet<>(); - qnames.add(QName.create(LeafFromGrouping.QNAME, "simple-value")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "simple-type")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "second-simple-value")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "list-via-uses")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "container-with-uses")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "leaf-from-grouping")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "identity")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "schema-unaware-union")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "simple-type-ref")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "identity-ref")); - qnames.add(QName.create(LeafFromGrouping.QNAME, "schema-unaware-union-ref")); - - return new AugmentationIdentifier(qnames); - } - - private static ContainerNode topNormailziedData() { - return ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Top.QNAME)) - .withChild(ImmutableMapNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TopLevelList.QNAME)) - .withChild(ImmutableMapEntryNodeBuilder.create() - .withNodeIdentifier(new NodeIdentifierWithPredicates(TopLevelList.QNAME, - TOP_LEVEL_LIST_NAME_QNAME, "test")) - .withChild(leafNode(TOP_LEVEL_LIST_NAME_QNAME, "test")) - .withChild(ImmutableAugmentationNodeBuilder.create() - .withNodeIdentifier(getTopLevelListAugId()) - .withChild(leafNode(SIMPLE_VALUE_QNAME, "simple-value")) - .withChild(leafNode(SIMPLE_TYPE_QNAME, 16)) - .build()) - .build()) - .build()) - .withChild(leafNode(AUGMENTED_INT_QNAME, 32)) - .withChild(leafNode(AUGMENTED_STRING_QNAME, "aug-string")) - .build(); - } - - @Test - public void topToNormalizedNode() { - final Map.Entry> entry = - registry.toNormalizedNode(InstanceIdentifier.create(Top.class), topBindingData()); - assertEquals(topNormailziedData(), entry.getValue()); - } - - @Test - public void topFromNormalizedNode() { - final Entry, TreeNode> entry = - registry.fromNormalizedNode(YangInstanceIdentifier.of(Top.QNAME), topNormailziedData()); - assertEquals(topBindingData(), entry.getValue()); - } - - private static SimpleId simpleIdBindingData() { - return new SimpleIdBuilder().setId(10).build(); - } - - private static ContainerNode simpleIdNormailziedData() { - return ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(SIMPLE_ID_QNAME)) - .withChild(leafNode(SIMPLE_LEAF_ID_QNAME, 10)) - .build(); - } - - @Test - public void testChoiceDataToNormalizedNode() { - final Map.Entry> entry = - registry.toNormalizedNode(BA_SIMPLE_ID, simpleIdBindingData()); - assertEquals(simpleIdNormailziedData(), entry.getValue()); - } - - @Test - public void testChoiceDataFromNormalizedNode() { - final Entry, TreeNode> entry = - registry.fromNormalizedNode(BI_SIMPLE_ID_PATH, simpleIdNormailziedData()); - assertEquals(simpleIdBindingData(), entry.getValue()); - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/TypedefTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/TypedefTest.java deleted file mode 100644 index 11ea47fd7e..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/TypedefTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl; - -import static org.junit.Assert.assertEquals; -import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode; - -import java.util.Map.Entry; -import javassist.ClassPool; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.generator.impl.StreamWriterGenerator; -import org.opendaylight.mdsal.binding.javav2.runtime.javassist.JavassistUtils; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.data.DefaultPolicy; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.data.TestCont; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.dto.DefaultPolicyBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.dto.TestContBuilder; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.type.PolicyLoggingFlag; -import org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.typedef.rev170829.type.TypedefEmpty; -import org.opendaylight.yangtools.yang.common.Empty; -import org.opendaylight.yangtools.yang.common.QName; -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.ContainerNode; -import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; -import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder; - - -public class TypedefTest extends AbstractBindingRuntimeTest { - - private static final InstanceIdentifier BA_DEFAULT_POLICY = - InstanceIdentifier.builder(DefaultPolicy.class).build(); - private static final InstanceIdentifier BA_TEST_CONT = - InstanceIdentifier.builder(TestCont.class).build(); - - private static final QName EMPTY_LEAF = QName.create(TestCont.QNAME, "empty-leaf"); - private static final QName EMPTY_LEAF2 = QName.create(TestCont.QNAME, "empty-leaf2"); - private static final QName EMPTY_LEAF3 = QName.create(TestCont.QNAME, "empty-leaf3"); - private static final YangInstanceIdentifier BI_TESTCONT_PATH = YangInstanceIdentifier.of(TestCont.QNAME); - - private BindingNormalizedNodeCodecRegistry registry; - - @Override - public void setup() { - super.setup(); - final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault()); - registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils)); - registry.onBindingRuntimeContextUpdated(getRuntimeContext()); - } - - @Test - public void testTypedef() { - DefaultPolicy binding = new DefaultPolicyBuilder() - .setAction(true) - .setAction2(new PolicyLoggingFlag(false)) - .setAction3(true) - .build(); - final Entry> dom = - registry.toNormalizedNode(BA_DEFAULT_POLICY, binding); - final Entry, TreeNode> readed = - registry.fromNormalizedNode(dom.getKey(),dom.getValue()); - - assertEquals(binding,readed.getValue()); - - } - - private static TestCont getTypedefEmptyTypeBindingData() { - return new TestContBuilder() - .setEmptyLeaf(Empty.getInstance()) - .setEmptyLeaf2(TypedefEmpty.getDefaultInstance()) - .setEmptyLeaf3(Empty.getInstance()) - .build(); - } - - private static ContainerNode getTypedefEmptyTypeNormalizedData() { - return ImmutableContainerNodeBuilder.create() - .withNodeIdentifier(new NodeIdentifier(TestCont.QNAME)) - .withChild(leafNode(EMPTY_LEAF, Empty.getInstance())) - .withChild(leafNode(EMPTY_LEAF2, Empty.getInstance())) - .withChild(leafNode(EMPTY_LEAF3, Empty.getInstance())) - .build(); - } - - @Test - public void testTypedefEmptyTypeToNormalizedData() { - final Entry> dom = - registry.toNormalizedNode(BA_TEST_CONT, getTypedefEmptyTypeBindingData()); - - assertEquals(getTypedefEmptyTypeNormalizedData(), dom.getValue()); - } - - @Test - public void testTypedefEmptyTypeFromNormalizedData() { - final Entry, TreeNode> readed = - registry.fromNormalizedNode(BI_TESTCONT_PATH, getTypedefEmptyTypeNormalizedData()); - - assertEquals(getTypedefEmptyTypeBindingData(), readed.getValue()); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContextTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContextTest.java deleted file mode 100644 index b0f6ebb98f..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/context/UnionValueOptionContextTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec; - -public class UnionValueOptionContextTest { - - private static UnionValueOptionContext TEST_UVOC_1; - private static UnionValueOptionContext TEST_UVOC_2; - - @Before - public void setUp() throws Exception { - final Method methodFoo1 = TestDataObject1.class.getMethod("foo"); - final Method methodFoo2 = TestDataObject2.class.getMethod("foo"); - TEST_UVOC_1 = new UnionValueOptionContext(TestUnion.class, TestDataObject1.class, methodFoo1, - ValueTypeCodec.EMPTY_CODEC); - TEST_UVOC_2 = new UnionValueOptionContext(TestUnion.class, TestDataObject2.class, methodFoo2, - ValueTypeCodec.EMPTY_CODEC); - } - - @Test - public void hashCodeTest() throws Exception { - final Method methodFoo1 = TestDataObject1.class.getMethod("foo"); - final UnionValueOptionContext test_uvoc = new UnionValueOptionContext(TestUnion.class, TestDataObject1.class, - methodFoo1, ValueTypeCodec.EMPTY_CODEC); - - assertEquals("HashCode", test_uvoc.hashCode(), TEST_UVOC_1.hashCode()); - assertNotEquals("HashCode", TEST_UVOC_1.hashCode(), TEST_UVOC_2.hashCode()); - } - - @Test - public void equalsTest() throws Exception { - final Method methodFoo1 = TestDataObject1.class.getMethod("foo"); - final UnionValueOptionContext test_uvoc = new UnionValueOptionContext(TestUnion.class, TestDataObject1.class, - methodFoo1, ValueTypeCodec.EMPTY_CODEC); - - assertTrue("Equals", TEST_UVOC_1.equals(test_uvoc)); - assertFalse("Not equals", TEST_UVOC_1.equals(TEST_UVOC_2)); - } - - protected static final class TestDataObject1 { - public void foo() { - } - } - - protected static final class TestDataObject2 { - public void foo() { - } - } - - public static final class TestUnion { - public TestUnion(final TestDataObject1 arg) { - } - - public TestUnion(final TestDataObject2 arg) { - } - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodecTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodecTest.java deleted file mode 100644 index 0b77111cf9..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/impl/value/EnumerationCodecTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import com.google.common.collect.ImmutableList; -import org.junit.Test; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair; - -public class EnumerationCodecTest { - - private enum TestEnum { - TEST - } - - @Test - public void basicTest() throws Exception { - final EnumPair pair = mock(EnumPair.class); - doReturn(TestEnum.TEST.name()).when(pair).getName(); - doReturn(0).when(pair).getValue(); - final EnumTypeDefinition definition = mock(EnumTypeDefinition.class); - doReturn(ImmutableList.of(pair)).when(definition).getValues(); - - final EnumerationCodec codec = EnumerationCodec.loader(TestEnum.class, definition).call(); - assertEquals(codec.deserialize(codec.serialize(TestEnum.TEST)), TestEnum.TEST); - assertEquals(codec.serialize(codec.deserialize(TestEnum.TEST.name())), TestEnum.TEST.name()); - } -} diff --git a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModificationTest.java b/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModificationTest.java deleted file mode 100644 index e5c87e0d9c..0000000000 --- a/binding2/mdsal-binding2-dom-codec/src/test/java/org/opendaylight/mdsal/binding/javav2/dom/codec/modification/LazyDataTreeModificationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.dom.codec.modification; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry; -import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingToNormalizedNodeCodec; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate; -import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier; -import org.opendaylight.yangtools.yang.common.QName; -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.tree.DataTreeCandidateNode; - -public class LazyDataTreeModificationTest { - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void basicTest() throws Exception { - final BindingNormalizedNodeCodecRegistry registry = mock(BindingNormalizedNodeCodecRegistry.class); - final BindingToNormalizedNodeCodec codec = - new BindingToNormalizedNodeCodec( - (GeneratedClassLoadingStrategy) GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), - registry); - final DOMDataTreeCandidate domDataTreeCandidate = mock(DOMDataTreeCandidate.class); - final DOMDataTreeIdentifier domDataTreeIdentifier = - new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.EMPTY); - doReturn(InstanceIdentifier.create(TreeNode.class)).when(registry).fromYangInstanceIdentifier(any()); - final BindingTreeCodec bindingCodecTree = mock(BindingTreeCodec.class); - final BindingTreeNodeCodec bindingCodecTreeNode = mock(BindingTreeNodeCodec.class); - doReturn(bindingCodecTreeNode).when(bindingCodecTree).getSubtreeCodec(any(InstanceIdentifier.class)); - final PathArgument identifier = - new YangInstanceIdentifier.NodeIdentifier(QName.create("test", "2017-06-13", "test-l")); - - doReturn(mock(TreeArgument.class)).when(bindingCodecTreeNode).deserializePathArgument(identifier); - doReturn(bindingCodecTree).when(registry).getCodecContext(); - doReturn(domDataTreeIdentifier).when(domDataTreeCandidate).getRootPath(); - final DataTreeCandidateNode dataTreeCandidate = mock(DataTreeCandidateNode.class); - doReturn(dataTreeCandidate).when(domDataTreeCandidate).getRootNode(); - doReturn(identifier).when(dataTreeCandidate).getIdentifier(); - assertNotNull(LazyDataTreeModification.create(codec, domDataTreeCandidate)); - } -} diff --git a/binding2/mdsal-binding2-generator-api/pom.xml b/binding2/mdsal-binding2-generator-api/pom.xml deleted file mode 100644 index aea7fb468a..0000000000 --- a/binding2/mdsal-binding2-generator-api/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-generator-api - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.yangtools - yang-model-api - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/BindingGenerator.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/BindingGenerator.java deleted file mode 100644 index aa97a8c451..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/BindingGenerator.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; - -/** - * - * Transforms Schema Context to Generated types. - * - */ -@Beta -public interface BindingGenerator { - - /** - * Generate Types from whole Schema Context.
- * The method will return List of All Generated Types that could be - * Generated from Schema Context. - * - * - * @param context - * Schema Context - * @return List of Generated Types - * - * @see SchemaContext - */ - List generateTypes(SchemaContext context); - - /** - * Generate Types from Schema Context restricted by sub set of specified - * Modules. The Schema Context MUST contain all of the sub modules otherwise - * there is no guarantee that result List of Generated Types will - * contain correct Generated Types. - * - * @param context - * Schema Context - * @param modules - * Sub Set of Modules - * @return List of Generated Types restricted by sub set of Modules - * - * @see Module - * @see SchemaContext - */ - List generateTypes(SchemaContext context, Set modules); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ClassLoadingStrategy.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ClassLoadingStrategy.java deleted file mode 100644 index 1c53dd4ea8..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ClassLoadingStrategy.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * - * Part of the Binding runtime context that dynamically loads Java classes into the Java - * Virtual Machine. Usually classes are only loaded on demand. - * - */ -@Beta -public interface ClassLoadingStrategy { - - /** - * - * @param type Generated Type - * @return instance of class - * @throws ClassNotFoundException - */ - Class loadClass(Type type) throws ClassNotFoundException; - - /** - * - * @param fqcn fully qualified Java class name - * @return instance of class - * @throws ClassNotFoundException - */ - Class loadClass(String fqcn) throws ClassNotFoundException; -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ModuleInfoRegistry.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ModuleInfoRegistry.java deleted file mode 100644 index 089285e025..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/api/ModuleInfoRegistry.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -/** - * Provides mechanism for YangModuleInfo registration - */ -@Beta -public interface ModuleInfoRegistry { - - /** - * - * @param yangModuleInfo YANG module info instance - * @return reference to registered YANG module info - */ - ObjectRegistration registerModuleInfo(YangModuleInfo yangModuleInfo); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/context/ModuleContext.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/context/ModuleContext.java deleted file mode 100644 index 25e0eed5ae..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/context/ModuleContext.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.context; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.common.collect.Streams; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus; -import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -/** - * This class holds information about generated entities in context of YANG module - */ -@Beta -public final class ModuleContext { - private GeneratedTypeBuilder moduleNode; - private final Map genTOs = new HashMap<>(); - private final Map typedefs = new HashMap<>(); - private final Map childNodes = new HashMap<>(); - private final BiMap dataTypes = HashBiMap.create(); - private final Map groupings = new HashMap<>(); - private final Map cases = new HashMap<>(); - private final Map identities = new HashMap<>(); - private final Set topLevelNodes = new HashSet<>(); - private final List augmentations = new ArrayList<>(); - private final Multimap typeToAugmentations = HashMultimap.create(); - private final BiMap targetToAugmentation = HashBiMap.create(); - private final Map typeToSchema = new HashMap<>(); - private final Multimap choiceToCases = HashMultimap.create(); - private final BiMap caseTypeToSchema = HashBiMap.create(); - private final Map innerTypes = new HashMap<>(); - private final Map keyTypes = new HashMap<>(); - //map is getting manipulated based on unique YANG module namespace rule - private final ListMultimap packagesMap = Multimaps.synchronizedListMultimap - (ArrayListMultimap.create()); - - public List getGeneratedTypes() { - final List result = new ArrayList<>(); - - if (this.moduleNode != null) { - result.add(this.moduleNode.toInstance()); - } - - Streams.concat( - this.genTOs.values().stream().map(GeneratedTOBuilder::toInstance), - this.typedefs.values().stream().filter(Objects::nonNull), - this.dataTypes.values().stream().map(GeneratedTypeBuilder::toInstance), - this.groupings.values().stream().map(GeneratedTypeBuilder::toInstance), - this.cases.values().stream().map(GeneratedTypeBuilder::toInstance), - this.identities.values().stream().map(GeneratedTypeBuilder::toInstance), - this.topLevelNodes.stream().map(GeneratedTypeBuilder::toInstance), - this.augmentations.stream().map(GeneratedTypeBuilder::toInstance), - this.keyTypes.values().stream().map(GeneratedTypeBuilder::toInstance)) - .forEach(result::add); - return ImmutableList.copyOf(result); - } - - public Multimap getChoiceToCases() { - return Multimaps.unmodifiableMultimap(this.choiceToCases); - } - - public GeneratedTypeBuilder getModuleNode() { - return this.moduleNode; - } - - public GeneratedTypeBuilder getChildNode(final SchemaPath p) { - return this.childNodes.get(p); - } - - public GeneratedTypeBuilder getGrouping(final SchemaPath p) { - return this.groupings.get(p); - } - - public GeneratedTypeBuilder getCase(final SchemaPath p) { - return this.cases.get(p); - } - - public void addModuleNode(final GeneratedTypeBuilder moduleNode) { - this.moduleNode = moduleNode; - } - - public void addGeneratedTOBuilder(final SchemaPath schemaPath, final GeneratedTOBuilder b) { - this.genTOs.put(schemaPath, b); - } - - public void addChildNodeType(final SchemaNode p, final GeneratedTypeBuilder b) { - this.childNodes.put(p.getPath(), b); - this.typeToSchema.put(b,p); - this.dataTypes.put(b.getFullyQualifiedName(), b); - } - - public void addGroupingType(final GroupingDefinition p, final GeneratedTypeBuilder b) { - this.groupings.put(p.getPath(), b); - this.typeToSchema.put(b, p); - } - - public void addTypedefType(final SchemaPath p, final Type t) { - this.typedefs.put(p, t); - } - - public void addCaseType(final SchemaPath p, final GeneratedTypeBuilder b) { - this.cases.put(p, b); - } - - public void addIdentityType(final QName name,final GeneratedTypeBuilder b) { - this.identities.put(name,b); - } - - public void addTopLevelNodeType(final GeneratedTypeBuilder b) { - this.topLevelNodes.add(b); - } - - public void addAugmentType(final GeneratedTypeBuilder b) { - this.augmentations.add(b); - } - - public Map getTypedefs() { - return this.typedefs; - } - - public Map getChildNodes() { - return Collections.unmodifiableMap(this.childNodes); - } - - public Map getGroupings() { - return Collections.unmodifiableMap(this.groupings); - } - - public Map getCases() { - return Collections.unmodifiableMap(this.cases); - } - - public Map getIdentities() { - return Collections.unmodifiableMap(this.identities); - } - - public Set getTopLevelNodes() { - return Collections.unmodifiableSet(this.topLevelNodes); - } - - public List getAugmentations() { - return Collections.unmodifiableList(this.augmentations); - } - - public Multimap getTypeToAugmentations() { - return Multimaps.unmodifiableMultimap(this.typeToAugmentations); - } - - public BiMap getTargetToAugmentation() { - return Maps.unmodifiableBiMap(this.targetToAugmentation); - } - - public void addTypeToAugmentations(final GeneratedTypeBuilder builder, - final List schemaList) { - schemaList.forEach(augmentNode -> this.typeToAugmentations.put(builder, augmentNode)); - } - - public void addTargetToAugmentation(final GeneratedTypeBuilder builder, final SchemaPath augmentTarget) { - this.targetToAugmentation.put(augmentTarget, builder); - } - - public void addChoiceToCaseMapping(final Type choiceType, final Type caseType, final CaseSchemaNode schema) { - this.choiceToCases.put(choiceType, caseType); - this.caseTypeToSchema.put(caseType, schema); - this.typeToSchema.put(caseType, schema); - } - - public BiMap getCaseTypeToSchemas() { - return Maps.unmodifiableBiMap(this.caseTypeToSchema); - } - - /** - * - * Returns mapping of type to its schema. - * - * Valid values are only instances of {@link DataSchemaNode} or {@link AugmentationSchemaNode} - * - * @return Mapping from type to corresponding schema - */ - public Map getTypeToSchema() { - return Collections.unmodifiableMap(this.typeToSchema); - } - - public void addTypeToSchema(final Type type, final WithStatus schema) { - this.typeToSchema.put(type, schema); - } - - /** - * Adds mapping between schema path and inner enum, inner union, inner bits. - * - * @param path - * @param builder - */ - public void addInnerTypedefType(final SchemaPath path, final Type builder) { - this.innerTypes.put(path, builder); - } - - public Type getInnerType(final SchemaPath path) { - return this.innerTypes.get(path); - } - - - public void addKeyType(final SchemaPath path, final GeneratedTypeBuilder genType) { - this.keyTypes.put(path, genType); - } - - public GeneratedTypeBuilder getKeyType(final SchemaPath path) { - return this.keyTypes.get(path); - } - - public GeneratedTOBuilder getKeyGenTO(final SchemaPath path) { - return this.genTOs.get(path); - } - - public ListMultimap getPackagesMap() { - return Multimaps.unmodifiableListMultimap(packagesMap); - } - - public void putToPackagesMap(final String packageName, final String actualClassName) { - this.packagesMap.put(packageName, actualClassName); - } - - public void cleanPackagesMap() { - this.packagesMap.clear(); - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/spi/TypeProvider.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/spi/TypeProvider.java deleted file mode 100644 index 6989c3e8ed..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/spi/TypeProvider.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.spi; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -/** - * Service provider interface that defines contract for generated types. - */ -@Beta -public interface TypeProvider { - - /** - * Resolve of yang Type Definition to its java counter part. - * If the Type Definition contains one of yang primitive types the method - * will return java.lang. counterpart. (For example if yang type is int32 - * the java counterpart is java.lang.Integer). In case that Type - * Definition contains extended type defined via yang typedef statement - * the method SHOULD return Generated Type or Generated Transfer Object - * if that Type is correctly referenced to resolved imported yang module. - * The method will return null value in situations that - * TypeDefinition can't be resolved (either due missing yang import or - * incorrectly specified type). - * - * - * @param type Type Definition to resolve from - * @param parentNode parent node - * @return Resolved Type - */ - Type javaTypeForSchemaDefinitionType(TypeDefinition type, SchemaNode parentNode, ModuleContext context); - - /** - * - * @param type Type Definition to resolve from - * @param parentNode parent node - * @param restrictions restrictions applied to given type definition - * @return Resolved Type - */ - Type javaTypeForSchemaDefinitionType(TypeDefinition type, SchemaNode parentNode, Restrictions restrictions, - ModuleContext context); - - /** - * Returns string containing code for creation of new type instance. - * - * @param node Schema node to resolve from - * @return String representing default construction - */ - String getTypeDefaultConstruction(LeafSchemaNode node); - - /** - * - * @param node Schema node to resolve from - * @return String representing constructor property name - */ - String getConstructorPropertyName(SchemaNode node); - - /** - * - * @param type Type Definition to resolve from - * @return String representing parameter name - */ - String getParamNameFromType(TypeDefinition type); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AccessModifier.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AccessModifier.java deleted file mode 100644 index 4851f31f1e..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AccessModifier.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.lang.reflect.Member; -import java.lang.reflect.Modifier; - -/** - * - * Enum definition which provides access modifiers that are described - * in Java programming language - * - */ -@Beta -public enum AccessModifier { - DEFAULT { - @Override - boolean matchesMember(Member member) { - return member.getModifiers() == 0; //no modifiers, package-private in fact - } - }, - - PRIVATE { - @Override - boolean matchesMember(Member member) { - return Modifier.isPrivate(member.getModifiers()); - } - }, - - PUBLIC { - @Override - boolean matchesMember(Member member) { - return Modifier.isPublic(member.getModifiers()); - } - }, - - PROTECTED { - @Override - boolean matchesMember(Member member) { - return Modifier.isProtected(member.getModifiers()); - } - }; - - /** - * - * @param member reflects identifying information about a single member (a field or a method) or a - * constructor. - * @return Return {@code true} if the integer argument includes the - * {@code public} modifier, {@code false} otherwise. - */ - abstract boolean matchesMember(Member member); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AnnotationType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AnnotationType.java deleted file mode 100644 index caa5a2ad5e..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/AnnotationType.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * The Annotation Type interface is designed to hold information about - * annotation for any type that could be annotated in Java.
- * For sake of simplicity the Annotation Type is not designed to model exact - * behaviour of annotation mechanism, but just to hold information needed to - * model annotation over java Type definition. - * By using in collections, implementations are expected - * to implement {@link #hashCode()} and {@link #equals(Object)} methods. - * - */ -@Beta -public interface AnnotationType extends Type, Comparable { - - /** - * Returns the List of Annotations.
- * Each Annotation Type MAY have defined multiple Annotations. - * - * @return the List of Annotations. - */ - List getAnnotations(); - - /** - * Returns Parameter Definition assigned for given parameter name.
- * If Annotation does not contain parameter with specified param name, the - * method MAY return null value. - * - * @param paramName - * Parameter Name - * @return Parameter Definition assigned for given parameter name. - */ - Parameter getParameter(final String paramName); - - /** - * Returns List of all parameters assigned to Annotation Type. - * - * @return List of all parameters assigned to Annotation Type. - */ - List getParameters(); - - /** - * Returns List of parameter names. - * - * @return List of parameter names. - */ - List getParameterNames(); - - /** - * Returns true if annotation contains parameters. - * - * @return true if annotation contains parameters. - */ - default boolean containsParameters() { - return !getParameters().isEmpty(); - } - - @Override - boolean equals(Object o); - - @Override - int hashCode(); - - @Override - int compareTo(AnnotationType o); - - /** - * Annotation Type parameter interface. For simplicity the Parameter - * contains values and value types as Strings. Every annotation which - * contains parameters could contain either single parameter or array of - * parameters. To model this purposes the by contract if the parameter - * contains single parameter the {@link #getValues()} method will return - * empty List and {@link #getSingleValue()} MUST always return non- - * null parameter. If the Parameter holds List of values the - * singular {@link #getSingleValue()} parameter MAY return null - * value. - */ - - @Beta - interface Parameter { - - /** - * Returns the Name of the parameter. - * - * @return the Name of the parameter. - */ - String getName(); - - /** - * Returns value in String format if Parameter contains singular value, - * otherwise should return first value only. Implementation should throw - * exception if there is no value to return. - * - * @return value in String format. - * @throws NoSuchElementException If such value not found - */ - String getSingleValue(); - - /** - * Returns List of Parameter assigned values in order in which they were - * assigned for given parameter name.
- * If there are multiple values assigned for given parameter name the - * method MUST NOT return empty List. - * As we consider getSingleValue() as a primary method, default - * implementation of getValues() is provided here. - * - * @return List of Parameter assigned values in order in which they were - * assigned for given parameter name. - */ - default List getValues() { - return ImmutableList.of(getSingleValue()); - } - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/BaseTypeWithRestrictions.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/BaseTypeWithRestrictions.java deleted file mode 100644 index 9d72a9f55b..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/BaseTypeWithRestrictions.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * The BaseTypeWithRestrictions is marker interface that encapsulates definition of java - * concrete type only with changed restriction values. - */ -@Beta -public interface BaseTypeWithRestrictions extends ConcreteType { - - /** - * @return changed restriction values - */ - Restrictions getRestrictions(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/CodeGenerator.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/CodeGenerator.java deleted file mode 100644 index f2b462cb9c..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/CodeGenerator.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * - * Transforms virtual data to the concrete code in programming language. - * - */ -@Beta -public interface CodeGenerator { - - /** - * Generates code for type. - * - * @param type - * Input type to be processed - * @return generated JAVA code - */ - String generate(Type type); - - /** - * Checks if the concrete instance of type fit to concrete - * implementation of this interface. - * - * (e. g. method return true if in EnumGenerator (which - * implements this interface) has input parameter of type Enumeration (which - * is subtype of Type) - * - * @param type - * Input type to be processed - * @return true if type is acceptable for processing, otherwise false - */ - boolean isAcceptable(Type type); - - /** - * Returns name of type parameter. - * - * @param type - * Input type to be processed - * @return generated unit - */ - Identifier getUnitName(Type type); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ConcreteType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ConcreteType.java deleted file mode 100644 index 9b3dbcdf49..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ConcreteType.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * The Concrete Type is marker interface that encapsulates definition of Java - * concrete type. - */ -@Beta -public interface ConcreteType extends Type { - Restrictions getRestrictions(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Constant.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Constant.java deleted file mode 100644 index b830474391..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Constant.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * Interface Contact is designed to hold and model java constant. In Java there - * are no constant keywords instead of the constant is defined as static final - * field with assigned value. For this purpose the Constant interface contains - * methods {@link #getType()} to provide wrapped return Type of Constant, - * {@link #getName()} the Name of constant and the {@link #getValue()} for - * providing of value assigned to Constant. To determine of which type the - * constant value is it is recommended firstly to retrieve Type from constant. - * The Type interface holds base information like java package name and java - * type name (e.g. fully qualified name). From this string user should be able - * to determine to which type can be {@link #getValue()} type typecasted to - * unbox and provide value assigned to constant. - */ -@Beta -public interface Constant { - - /** - * Returns the Type that declares constant. - * - * @return the Type that declares constant. - */ - Type getDefiningType(); - - /** - * Returns the return Type (or just Type) of the Constant. - * - * @return the return Type (or just Type) of the Constant. - */ - Type getType(); - - /** - * Returns the name of constant.
- * By conventions the name SHOULD be in CAPITALS separated with underscores. - * - * @return the name of constant. - */ - String getName(); - - /** - * Returns boxed value that is assigned for context. - * - * @return boxed value that is assigned for context. - */ - Object getValue(); - - /** - * Returns Constant definition in formatted string.
- *
- * The expected string SHOULD be in format: public final - * static [Type] CONSTANT_NAME = [value]; - * - * @return Constant definition in formatted string. - */ - default String toFormattedString() { - StringBuilder builder = new StringBuilder(); - builder.append("public static final"); - builder.append(" "); - builder.append(getType()); - builder.append(" "); - builder.append(getName()); - builder.append(" = "); - builder.append(getValue()); - builder.append(";"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/DocumentedType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/DocumentedType.java deleted file mode 100644 index 8776b19b60..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/DocumentedType.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Optional; -import org.opendaylight.yangtools.yang.common.QName; - -/** - * Implementing this interface allows an object to hold information which are - * essential for generating java doc from type definition. - */ -@Beta -public interface DocumentedType { - - /** - * Returns a string that contains a human-readable textual description of - * type definition. - * - * @return a human-readable textual description of type definition. - */ - Optional getDescription(); - - /** - * Returns a string that is used to specify a textual cross-reference to an - * external document, either another module that defines related management - * information, or a document that provides additional information relevant - * to this definition. - * - * @return a textual cross-reference to an external document. - */ - Optional getReference(); - - /** - * Returns a list of QNames which represent schema path in schema tree from - * actual concrete type to the root. - * - * @return a schema path in schema tree from actual concrete schema node - * identifier to the root. - */ - List getSchemaPath(); - - /** - * Returns the name of the module, in which generated type was specified. - * - * @return the name of the module, in which generated type was specified. - */ - String getModuleName(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Enumeration.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Enumeration.java deleted file mode 100644 index 10a3176b09..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Enumeration.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode; - -/** - * - * Interface provide methods for reading data of enumeration class. - * - */ -@Beta -public interface Enumeration extends GeneratedType { - /** - * - * Returns list of annotation definitions associated with enumeration type. - * - * @return list of annotation definitions associated with enumeration type. - * - */ - @Override - List getAnnotations(); - - @Override - Type getParentType(); - - /** - * Returns list of the couples - name and value. - * - * @return list of the enumeration pairs. - */ - List getValues(); - - /** - * Formats enumeration according to rules of the programming language. - * - * @return string with source code in some programming language - */ - String toFormattedString(); - - /** - * Interface is used for reading enumeration item. It means item's name and - * its value. - */ - interface Pair extends DocumentedNode.WithStatus { - - /** - * Returns the name of the enumeration item. - * - * @return the name of the enumeration item. - */ - String getName(); - - /** - * Returns the binding representation for the name of the enumeration item. - * - * @return the binding representation for the name of the enumeration item. - */ - String getMappedName(); - - /** - * Returns value of the enumeration item. - * - * @return the value of the enumeration item. - */ - int getValue(); - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedProperty.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedProperty.java deleted file mode 100644 index 97b7671562..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedProperty.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * Generated Property extends interface {@link TypeMember} interface.
- * The Generated Property interface is designed to store information of fields - * (or members) declared in Java Transfer Objects (or any java classes) and - * their access counterparts (getters and setters). - * - * @see MethodSignature - */ -@Beta -public interface GeneratedProperty extends TypeMember { - - /** - * @return String format of generated property value - */ - String getValue(); - - /** - * Returns true if the property si declared as read-only.
- * If the property has flag isReadOnly == true the property - * SHOULD be generated as getter only. - * - * @return true if the property si declared as read-only. - */ - boolean isReadOnly(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTransferObject.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTransferObject.java deleted file mode 100644 index 053ff46041..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTransferObject.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -/** - * Generated Transfer Object extends {@link GeneratedType} and is designed to - * represent Java Class. The Generated Transfer Object contains declarations of - * member fields stored in List of Properties. The Generated Transfer Object can - * be extended by exactly ONE Generated Transfer Object as Java don't allow - * multiple inheritance. For retrieval of implementing Generated Types use - * {@link #getImplements()} method.
- * Every transfer object SHOULD contain equals, hashCode and toString - * definitions. For this purpose retrieve definitions through - * {@link #getEqualsIdentifiers ()}, {@link #getHashCodeIdentifiers()} and - * {@link #getToStringIdentifiers ()}. - * - */ -@Beta -public interface GeneratedTransferObject extends GeneratedType { - - GeneratedProperty getSUID(); - - /** - * Returns the Generated Transfer Object from which this GTO is derived, or - * null if this GTO is not derived from a GTO -- e.g. it is either an union - * or it is derived from a concrete type. - * - * @return Generated Transfer Object or null if this GTO is - * not derived from another GTO. - */ - GeneratedTransferObject getSuperType(); - - /** - * Returns List of Properties that are designated to define equality for - * Generated Transfer Object. - * - * @return List of Properties that are designated to define equality for - * Generated Transfer Object. - */ - List getEqualsIdentifiers(); - - /** - * Returns List of Properties that are designated to define identity for - * Generated Transfer Object. - * - * @return List of Properties that are designated to define identity for - * Generated Transfer Object. - */ - List getHashCodeIdentifiers(); - - /** - * Returns List of Properties that will be members of toString definition - * for Generated Transfer Object. - * - * @return List of Properties that will be members of toString definition - * for Generated Transfer Object. - */ - List getToStringIdentifiers(); - - boolean isTypedef(); - - /** - * Returns Base type of Java representation of YANG typedef if set, otherwise it returns null - * - * @return Base type of Java representation of YANG typedef if set, otherwise it returns null - */ - TypeDefinition getBaseType(); - - /** - * Return boolean value which describe whether Generated Transfer Object - * was/wasn't created from union YANG type. - * - * @return true value if Generated Transfer Object was created from union - * YANG type. - */ - boolean isUnionType(); - - boolean isUnionTypeBuilder(); - - Restrictions getRestrictions(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedType.java deleted file mode 100755 index 0293d63388..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedType.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; - -/** - * Every Java interface has to be specified with: - *

    - *
  • package that belongs into
  • - *
  • interface name (with commentary that SHOULD be - * present to proper define interface and base contracts specified for - * interface)
  • - *
  • Each Generated Type can define list of types that Generated Type can - * implement to extend it's definition (i.e. interface extends list of - * interfaces or java class implements list of interfaces)
  • - *
  • Each Generated Type can contain multiple enclosed definitions of - * Generated Types (i.e. interface can contain N enclosed interface definitions - * or enclosed classes)
  • - *
  • enum and constant definitions (i.e. each - * constant definition is by default defined as public static final - * + type (either primitive or object) and constant name
  • - *
  • method definitions with specified input parameters (with - * types) and return values
  • - *
- * - * By the definition of the interface constant, enum, enclosed types and method - * definitions MUST be public, so there is no need to specify the scope of - * visibility. - */ -@Beta -public interface GeneratedType extends Type, DocumentedType { - - /** - * Returns the parent type if Generated Type is defined as enclosing type, - * otherwise returns null - * - * @return the parent type if Generated Type is defined as enclosing type, - * otherwise returns null - */ - Type getParentType(); - - /** - * Returns comment string associated with Generated Type. - * - * @return comment string associated with Generated Type. - */ - TypeComment getComment(); - - /** - * Returns List of annotation definitions associated with generated type. - * - * @return List of annotation definitions associated with generated type. - */ - List getAnnotations(); - - /** - * Returns true if The Generated Type is defined as abstract. - * - * @return true if The Generated Type is defined as abstract. - */ - boolean isAbstract(); - - /** - * Returns List of Types that Generated Type will implement. - * - * @return List of Types that Generated Type will implement. - */ - List getImplements(); - - /** - * Returns List of enclosing Generated Types. - * - * @return List of enclosing Generated Types. - */ - List getEnclosedTypes(); - - /** - * Returns List of all Enumerator definitions associated with Generated - * Type. - * - * @return List of all Enumerator definitions associated with Generated - * Type. - */ - List getEnumerations(); - - /** - * Returns List of Constant definitions associated with Generated Type. - * - * @return List of Constant definitions associated with Generated Type. - */ - List getConstantDefinitions(); - - /** - * Returns List of Method Definitions associated with Generated Type. - * - * List does not contains getters and setters for properties. - * - * @return List of Method Definitions associated with Generated Type. - */ - List getMethodDefinitions(); - - /** - * Returns List of Properties that are declared for Generated Transfer - * Object. - * - * @return List of Properties that are declared for Generated Transfer - * Object. - */ - List getProperties(); - - /** - * Returns parent type for data schema node builder - */ - Type getParentTypeForBuilder(); - - /** - * Returns the YANG definition of this type, if available. - * - * @return YANG source definition, or empty when unavailable. - */ - Optional getYangSourceDefinition(); - - /** - * Get the BindingNamespaceType. - * - * @return BindingNamespaceType which type belongs to. - */ - BindingNamespaceType getBindingNamespaceType(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTypeForBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTypeForBuilder.java deleted file mode 100644 index 4f68bf017b..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/GeneratedTypeForBuilder.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * Java interface for builders to get package name and so on. - */ -@Beta -public interface GeneratedTypeForBuilder { - /** - * Returns name of the package that builder class belongs to. - * - * @return name of the package that builder class belongs to - */ - String getPackageNameForBuilder(); - - /** - * Returns base package name that builder class belongs to. - * - * @return base package name that builder class belongs to - */ - String getBasePackageName(); - - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/MethodSignature.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/MethodSignature.java deleted file mode 100644 index 73358af43f..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/MethodSignature.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; - -/** - * The Method Signature interface contains simplified meta model for java method - * definition. Each method MUST be defined by name, return type, parameters and - * access modifier.
- * Additionally method MAY contain associated annotations and comment. By - * contract if method does not contain any comments or annotation definitions - * the {@link #getComment()} SHOULD rather return empty string and - * {@link #getAnnotations()} SHOULD rather return empty list than - * null values.
- * The defining Type contains the reference to Generated Type that declares - * Method Signature. - */ -@Beta -public interface MethodSignature extends TypeMember { - - /** - * Returns true if the method signature is defined as abstract.
- * By default in java all method declarations in interface are defined as - * abstract, but the user don't need necessary to declare abstract keyword - * in front of each method.
- * The abstract methods are allowed in Class definitions but only when the - * class is declared as abstract. - * - * @return true if the method signature is defined as abstract. - */ - boolean isAbstract(); - - /** - * Returns the List of parameters that method declare. If the method does - * not contain any parameters, the method will return empty List. - * - * @return the List of parameters that method declare. - */ - List getParameters(); - - /** - * The Parameter interface is designed to hold the information of method - * Parameter(s). The parameter is defined by his Name which MUST be unique - * as java does not allow multiple parameters with same names for one method - * and Type that is associated with parameter. - */ - interface Parameter { - - /** - * Returns the parameter name. - * - * @return the parameter name. - */ - String getName(); - - /** - * Returns Type that is bounded to parameter name. - * - * @return Type that is bounded to parameter name. - */ - Type getType(); - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ParameterizedType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ParameterizedType.java deleted file mode 100644 index 0b3dbd405f..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/ParameterizedType.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * Represents an instance of simple parametrized type such as List<String>. - * - * The parametrized Type is designed to be used to store information of Java - * Generic Type. The array of {@link #getActualTypeArguments()} holds - * information of all generic parameters defined for Parameterized Type. - */ -@Beta -public interface ParameterizedType extends Type { - - /** - * Returns array of Types that are defined for Parameterized Type. - *
- * (for example if ParameterizedType encapsulates java generic Map that - * specifies two parameters Map<K,V> and the K is java.lang.Integer and V - * is defined as GeneratedType the array will contain two Types to store - * the information of generic parameters.) - * - * @return array of Types that are defined for Parameterized Type. - */ - Type[] getActualTypeArguments(); - - /** - * Returns the Raw Type definition of Parameterized Type. - * - * @return the Raw Type definition of Parameterized Type. - */ - Type getRawType(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Restrictions.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Restrictions.java deleted file mode 100644 index 4c3436bbf6..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Restrictions.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Optional; -import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; -import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; - -@Beta -public interface Restrictions { - - Optional getLengthConstraint(); - List getPatternConstraints(); - Optional> getRangeConstraint(); - boolean isEmpty(); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Type.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Type.java deleted file mode 100644 index a206820d2c..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/Type.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * - * The Type interface defines the base type for all types defined in java. Each - * Type defined in java MUST contain name and package name, except of primitive - * types like int, byte etc. In case of mapping of primitive type the package - * name MUST be left as empty string. - * - */ -@Beta -public interface Type { - - /** - * Returns name of the package that interface belongs to. - * - * @return name of the package that interface belongs to - */ - String getPackageName(); - - /** - * Returns name of the interface. - * - * @return name of the interface. - */ - String getName(); - - /** - * Returns fully qualified name of Type.
- * The fully qualified name of Type MUST be returned in following format: - *
    - *
  • If does not contains package name: [type name] (e.g. int, byte, - * byte[],...)
  • - *
  • If Type contains package name: [package name].[type name] (e.g - * java.lang.Byte, org.opendaylight.controller.gen.GenType)
  • - *
- * - * @return fully qualified name of Type. - */ - String getFullyQualifiedName(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeComment.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeComment.java deleted file mode 100644 index d292f299fe..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeComment.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import org.eclipse.jdt.annotation.NonNullByDefault; - -/** - * Dedicated type for holding a class comment. It exposes a javadoc-encoded string. - * - * @author Robert Varga - */ -@Beta -@FunctionalInterface -@NonNullByDefault -public interface TypeComment { - - /** - * Return a javadoc snippet. This snippet is guaranteed to be safe for direct inclusion in a Java block comment. - * - * @return Javadoc snippet. - */ - String getJavadoc(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeMember.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeMember.java deleted file mode 100644 index ff9f4b7d36..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/TypeMember.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import java.util.List; - -/** - * - * Common interface for variables and methods in class. - * - */ -@Beta -public interface TypeMember { - - /** - * Returns comment string associated with member. - * - * @return comment string associated with member. - */ - String getComment(); - - /** - * Returns List of annotation definitions associated with generated type. - * - * @return List of annotation definitions associated with generated type. - */ - List getAnnotations(); - - /** - * Returns the access modifier of member. - * - * @return the access modifier of member. - */ - AccessModifier getAccessModifier(); - - /** - * Returns true if member is declared as static. - * - * @return true if member is declared as static. - */ - boolean isStatic(); - - /** - * Returns true if member is declared as final. - * - * @return true if member is declared as final. - */ - boolean isFinal(); - - /** - * Get the returning Type of member. - * - * @return the returning Type of member. - */ - Type getReturnType(); - - /** - * Returns the name of member. - * - * @return the name of member. - */ - String getName(); - - /** - * Returns the Type that declares member. - * - * @return the Type that declares member. - */ - Type getDefiningType(); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/UnitName.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/UnitName.java deleted file mode 100644 index e0d9bf0534..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/UnitName.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.util.AbstractStringIdentifier; - -@Beta -public class UnitName extends AbstractStringIdentifier { - - public UnitName(final String string) { - super(string); - } - - String getString() { - return getValue(); - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/WildcardType.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/WildcardType.java deleted file mode 100644 index 5e5b786e99..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/WildcardType.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api; - -import com.google.common.annotations.Beta; - -/** - * - * Marker interface which assign to object property that it is bounded wildcard - * type. - * - */ -@Beta -public interface WildcardType extends Type { - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/YangSourceDefinition.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/YangSourceDefinition.java deleted file mode 100644 index ce1c8eabae..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/YangSourceDefinition.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.model.api; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; -import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; -import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement; -import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement; - -/** - * DTO capturing the YANG source definition which lead to a {@link GeneratedType} being emitted. - * - * @author Robert Varga - */ -@Beta -@NonNullByDefault -public abstract class YangSourceDefinition { - public static final class Multiple extends YangSourceDefinition { - private final List nodes; - - Multiple(final ModuleEffectiveStatement module, final Collection nodes) { - super(module); - this.nodes = ImmutableList.copyOf(nodes); - } - - /** - * Return the defining SchemaNodes. Each node is guaranteed to implement {@link EffectiveStatement} and have - * a corresponding declared statement. - * - * @return defining SchemaNodes, guaranteed to be non-empty - */ - public List getNodes() { - return nodes.stream().filter(node -> node instanceof EffectiveStatement - && ((EffectiveStatement) node).getDeclared() != null).collect(Collectors.toList()); - } - } - - public static final class Single extends YangSourceDefinition { - private final DocumentedNode node; - - Single(final ModuleEffectiveStatement module, final DocumentedNode node) { - super(module); - this.node = requireNonNull(node); - } - - /** - * Return the defining DocumentedNode. The node is guaranteed to implement {@link EffectiveStatement} and have - * a corresponding declared statement. - * - * @return defining SchemaNodes, guaranteed to be non-empty - */ - public DocumentedNode getNode() { - return node; - } - } - - private final ModuleEffectiveStatement module; - - private YangSourceDefinition(final ModuleEffectiveStatement module) { - this.module = requireNonNull(module); - } - - public static Optional of(final Module module) { - if (module instanceof ModuleEffectiveStatement) { - final ModuleEffectiveStatement effective = (ModuleEffectiveStatement) module; - final ModuleStatement declared = effective.getDeclared(); - if (declared != null) { - return Optional.of(new Single(effective, module)); - } - } - return Optional.empty(); - } - - public static Optional of(final Module module, final SchemaNode node) { - if (module instanceof ModuleEffectiveStatement) { - final ModuleEffectiveStatement effective = (ModuleEffectiveStatement) module; - if (node instanceof EffectiveStatement) { - final DeclaredStatement declared = ((EffectiveStatement) node).getDeclared(); - if (declared != null) { - return Optional.of(new Single(effective, node)); - } - } - } - return Optional.empty(); - } - - public static Optional of(final Module module, final Collection nodes) { - checkArgument(!nodes.isEmpty()); - - if (module instanceof ModuleEffectiveStatement) { - final ModuleEffectiveStatement effective = (ModuleEffectiveStatement) module; - final boolean anyDeclared = nodes.stream().anyMatch(node -> - node instanceof EffectiveStatement && ((EffectiveStatement) node).getDeclared() != null); - if (anyDeclared) { - return Optional.of(new Multiple(effective, nodes)); - } - } - return Optional.empty(); - } - - /** - * Return the defining YANG module. - * - * @return Defining YANG module. - */ - public final ModuleEffectiveStatement getModule() { - return module; - } -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/AnnotationTypeBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/AnnotationTypeBuilder.java deleted file mode 100644 index 1e1bda9760..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/AnnotationTypeBuilder.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * Annotation Type Builder Interface serves for creation and instantiation of - * immutable copy of Annotation Type. The Annotation Type Builder extends from - * {@link Type} interface. The Annotation Type contains set of methods which are - * capable to provide information about other Annotation Types and Annotation - * Parameters. - * - * @see AnnotationType - */ -@Beta -public interface AnnotationTypeBuilder extends Type { - /** - * The method creates new AnnotationTypeBuilder containing specified package - * name an annotation name.
- * Neither the package name or annotation name can contain null - * references. In case that any of parameters contains null the - * method SHOULD thrown {@link IllegalArgumentException} - * - * @param packageName - * Package Name of Annotation Type - * @param name - * Name of Annotation Type - * @return new instance of Annotation Type Builder. - * @throws IllegalArgumentException if packageName and/or name is null - */ - AnnotationTypeBuilder addAnnotation(final String packageName, final String name); - - /** - * Adds the parameter into List of parameters for Annotation Type.
- * If there is already stored parameter with the same name as the new - * parameter, the value of the old one will be simply overwritten by the - * newer parameter.
- * Neither the param name or value can contain null references. - * In case that any of parameters contains null the method - * SHOULD thrown {@link IllegalArgumentException} - * - * @param paramName - * Parameter Name - * @param value - * Parameter Value - * @return true if the parameter has been successfully assigned - * for Annotation Type - * @throws IllegalArgumentException if paramName and/or value is null - */ - boolean addParameter(final String paramName, String value); - - /** - * Adds the parameter with specified List of parameter values into List of - * parameters for Annotation Type.
- * If there is already stored parameter with the same name as the new - * parameter, the value of the old one will be simply overwritten by the - * newer parameter.
- * Neither the param name or value can contain null references. - * In case that any of parameters contains null the method - * SHOULD thrown {@link IllegalArgumentException} - * - * @param paramName - * Parameter Name - * @param values - * List of Values bounded to Parameter Name - * @return true if the parameter has been successfully assigned - * for Annotation Type - * @throws IllegalArgumentException if paramName and/or any of values is null - */ - boolean addParameters(final String paramName, List values); - - /** - * Returns new immutable instance of Annotation Type - * with values assigned in current instance of Annotation Type Builder.
- * The return Annotation Type instance is immutable thus no additional - * modification to Annotation Type Builder will have an impact to - * instantiated Annotation Type.
- * For this purpose call this method after all additions are complete. - * - * @return new immutable instance of Annotation Type. - */ - AnnotationType toInstance(); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/EnumBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/EnumBuilder.java deleted file mode 100644 index 09fd5bccf4..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/EnumBuilder.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.Status; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; - -/** - * Enum Builder is interface that contains methods to build and instantiate - * Enumeration definition. - * - * @see Enumeration - */ -@Beta -public interface EnumBuilder extends Type { - /** - * The method creates new AnnotationTypeBuilder containing specified package - * name and annotation name.
- * Neither the package name or annotation name can contain null - * references. In case that any of parameters contains null the - * method SHOULD throw {@link IllegalArgumentException} - * - * @param packageName - * Package Name of Annotation Type - * @param name - * Name of Annotation Type - * @return new instance of Annotation Type Builder. - */ - AnnotationTypeBuilder addAnnotation(final String packageName, final String name); - - /** - * - * @param name - * assigned name - * @param value - * as optionally defined in YANG model - * @param description - * as optionally defined in YANG model - * @param reference - * as optionally defined in YANG model - * @param status - * as optionally defined in YANG model - */ - void addValue(final String name, final int value, final String description, - final String reference, final Status status); - - /** - * - * @param definingType - * Type - * @return Enumeration - */ - Enumeration toInstance(final Type definingType); - - /** - * Updates this builder with data from enumTypeDef. - * Specifically this data represents list of value-name pairs. - * - * @param enumTypeDef - * enum type definition as source of enum data for - * enumBuilder - */ - void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef); - - /** - * @param description - */ - void setDescription(final String description); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedPropertyBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedPropertyBuilder.java deleted file mode 100644 index 136e4cddbd..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedPropertyBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * Generated Property Builder is interface that contains methods to build and - * instantiate Generated Property definition. - * - * @see GeneratedProperty - */ -@Beta -public interface GeneratedPropertyBuilder extends TypeMemberBuilder { - - GeneratedPropertyBuilder setValue(String value); - - /** - * Sets isReadOnly flag for property. If property is marked as read only it - * is the same as set property in java as final. - * - * @param isReadOnly - * Read Only property flag. - */ - GeneratedPropertyBuilder setReadOnly(final boolean isReadOnly); - - /** - * Returns new immutable instance of Generated Property.
- * The definingType param cannot be null. The - * every member in Java MUST be declared and defined inside the scope of - * class definition. In case that defining Type will be passed - * as null reference the method SHOULD thrown - * {@link IllegalArgumentException}. - * - * @param definingType - * Defining Type of Generated Property - * @return new immutable instance of Generated Property. - */ - GeneratedProperty toInstance(final Type definingType); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTOBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTOBuilder.java deleted file mode 100644 index 359b3855d4..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTOBuilder.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -/** - * Generated Transfer Object Builder is interface that contains methods to build - * and instantiate Generated Transfer Object definition. - * - * @see GeneratedTransferObject - */ -@Beta -public interface GeneratedTOBuilder extends GeneratedTypeBuilderBase { - /** - * Add Generated Transfer Object from which will be extended current - * Generated Transfer Object.
- * By definition Java does not allow multiple inheritance, hence if there is - * already definition of Generated Transfer Object the extending object will - * be overwritten by lastly added Generated Transfer Object.
- * If Generated Transfer Object is null the method SHOULD throw - * {@link IllegalArgumentException} - * - * @param genTransObj - * Generated Transfer Object - * @return This instance of builder - */ - GeneratedTOBuilder setExtendsType(final GeneratedTransferObject genTransObj); - - /** - * Add Property that will be part of equals definition.
- * If Generated Property Builder is null the method SHOULD - * throw {@link IllegalArgumentException} - * - * @param property - * Generated Property Builder - * @return This instance of builder - */ - GeneratedTOBuilder addEqualsIdentity(final GeneratedPropertyBuilder property); - - /** - * Add Property that will be part of hashCode definition.
- * If Generated Property Builder is null the method SHOULD - * throw {@link IllegalArgumentException} - * - * @param property - * Generated Property Builder - * @return This instance of builder - */ - GeneratedTOBuilder addHashIdentity(final GeneratedPropertyBuilder property); - - /** - * Add Property that will be part of toString definition.
- * If Generated Property Builder is null the method SHOULD - * throw {@link IllegalArgumentException} - * - * @param property - * Generated Property Builder - * @return This instance of builder - */ - GeneratedTOBuilder addToStringProperty(final GeneratedPropertyBuilder property); - - void setRestrictions(Restrictions restrictions); - - /** - * Returns instance of GeneratedTransferObject which data are - * build from the data of this builder - * - * @return generated transfer object instance - */ - GeneratedTransferObject toInstance(); - - void setTypedef(boolean isTypedef); - - /** - * Sets the base type for Java representation of YANG typedef - * - * @param typeDef - * Type Definition - */ - void setBaseType(TypeDefinition typeDef); - - /** - * - * @param isUnion - */ - void setIsUnion(boolean isUnion); - - void setIsUnionBuilder(boolean isUnionTypeBuilder); - - void setSUID(GeneratedPropertyBuilder suid); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilder.java deleted file mode 100644 index 96b2161597..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilder.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; - -/** - * Generated Type Builder interface is helper interface for building and - * defining the GeneratedType. - * - * @see GeneratedType - */ -@Beta -public interface GeneratedTypeBuilder extends GeneratedTypeBuilderBase { - - /** - * Returns the new immutable instance of Generated Type. - * - * @return the new immutable instance of Generated Type. - */ - GeneratedType toInstance(); - -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilderBase.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilderBase.java deleted file mode 100644 index 9060ec1e66..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/GeneratedTypeBuilderBase.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Optional; -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; - -@Beta -public interface GeneratedTypeBuilderBase> extends Type { - - /** - * Adds new Enclosing Transfer Object into definition of Generated Type and - * returns new Instance of Generated TO Builder.
- * There is no need of specifying of Package Name because enclosing Type is - * already defined inside Generated Type with specific package name.
- * The name of enclosing Type cannot be same as Name of parent type and if - * there is already defined enclosing type with the same name, the new - * enclosing type will simply overwrite the older definition.
- * If the name of enclosing type is null the method SHOULD - * throw {@link IllegalArgumentException} - * - * @param name - * Name of Enclosing Type - * @return new Instance of Generated Type Builder. - */ - GeneratedTOBuilder addEnclosingTransferObject(String name); - - /** - * Adds new Enclosing Transfer Object genTOBuilder into - * definition of Generated Type - * - *
- * There is no need of specifying of Package Name because enclosing Type is - * already defined inside Generated Type with specific package name.
- * The name of enclosing Type cannot be same as Name of parent type and if - * there is already defined enclosing type with the same name, the new - * enclosing type will simply overwrite the older definition.
- * If the parameter genTOBuilder of enclosing type is - * null the method SHOULD throw - * {@link IllegalArgumentException} - * - * @param genTOBuilder - * Name of Enclosing Type - */ - T addEnclosingTransferObject(GeneratedTOBuilder genTOBuilder); - - /** - * Adds String definition of comment into Method Signature definition.
- * The comment String MUST NOT contain anny comment specific chars (i.e. - * "/**" or "//") just plain String text description. - * - * @param comment - * Comment String. - */ - T addComment(TypeComment comment); - - /** - * The method creates new AnnotationTypeBuilder containing specified package - * name an annotation name.
- * Neither the package name or annotation name can contain null - * references. In case that any of parameters contains null the - * method SHOULD thrown {@link IllegalArgumentException} - * - * @param packageName - * Package Name of Annotation Type - * @param name - * Name of Annotation Type - * @return new instance of Annotation Type Builder. - */ - AnnotationTypeBuilder addAnnotation(String packageName, String name); - - boolean isAbstract(); - - /** - * Sets the abstract flag to define Generated Type as - * abstract type. - * - * @param isAbstract - * abstract flag - */ - T setAbstract(boolean isAbstract); - - List getImplementsTypes(); - - /** - * Add Type to implements. - * - * @param genType - * Type to implement - * @return true if the addition of type is successful. - */ - T addImplementsType(Type genType); - - /** - * Adds Constant definition and returns new Constant instance.
- * By definition Constant MUST be defined by return Type, Name and assigned - * value. The name SHOULD be defined with capital letters. Neither of method - * parameters can be null and the method SHOULD throw - * {@link IllegalArgumentException} if the contract is broken. - * - * @param type - * Constant Type - * @param name - * Name of Constant - * @param value - * Assigned Value - * @return new Constant instance. - */ - Constant addConstant(Type type, String name, Object value); - - /** - * Adds new Enumeration definition for Generated Type Builder and returns - * Enum Builder for specifying all Enum parameters.
- * If there is already Enumeration stored with the same name, the old enum - * will be simply overwritten byt new enum definition.
- * Name of Enumeration cannot be null, if it is - * null the method SHOULD throw - * {@link IllegalArgumentException} - * - * @param name - * Enumeration Name - * @return new instance of Enumeration Builder. - */ - EnumBuilder addEnumeration(String name, ModuleContext context); - - /** - * Gets parent type for data schema node builder, the parent - * MUST be a data tree node. - * - * @return parent generated type of tree node - */ - Type getParentTypeForBuilder(); - - /** - * Sets parent type for data schema node builder, the parent - * MUST be a data tree node. - * - * @param type parent generated type of tree node - * @return parent generated type - */ - Type setParentTypeForBuilder(Type type); - - /** - * Get the BindingNamespaceType. - * - * @return BindingNamespaceType which type belongs to. - */ - BindingNamespaceType getBindingNamespaceType(); - - List getMethodDefinitions(); - - /** - * Add new Method Signature definition for Generated Type Builder and - * returns Method Signature Builder for specifying all Method parameters.
- * Name of Method cannot be null, if it is null - * the method SHOULD throw {@link IllegalArgumentException}
- * By Default the MethodSignatureBuilder SHOULD be pre-set as - * {@link MethodSignatureBuilder#setAbstract(boolean)}, - * {TypeMemberBuilder#setFinal(boolean)} and - * {TypeMemberBuilder#setAccessModifier(boolean)} - * - * @param name - * Name of Method - * @return new instance of Method Signature Builder. - */ - MethodSignatureBuilder addMethod(String name); - - /** - * Checks if GeneratedTypeBuilder contains method with name - * methodName - * - * @param methodName - * is method name - */ - boolean containsMethod(String methodName); - - List getProperties(); - - /** - * Returns the YANG definition of this type, if available. - * - * @return YANG source definition, or empty when unavailable. - */ - Optional getYangSourceDefinition(); - - /** - * Add new Generated Property definition for Generated Transfer Object - * Builder and returns Generated Property Builder for specifying Property.
- * Name of Property cannot be null, if it is null - * the method SHOULD throw {@link IllegalArgumentException} - * - * @param name - * Name of Property - * @return new instance of Generated Property Builder. - */ - GeneratedPropertyBuilder addProperty(String name); - - /** - * Check whether GeneratedTOBuilder contains property with name - * name - * - * @param name - * of property which existance is checked - * @return true if property name exists in list of properties. - */ - boolean containsProperty(String name); - - /** - * Set a string that contains a human-readable textual description of type - * definition. - * - * @param description - * a string that contains a human-readable textual description of - * type definition. - */ - void setDescription(String description); - - /** - * Set the name of the module, in which generated type was specified. - * - * @param moduleName - * the name of the module - */ - void setModuleName(String moduleName); - - /** - * Set a list of QNames which represent schema path in schema tree from - * actual concrete type to the root. - * - * @param schemaPath - * a list of QNames which represent schema path in schema tree - */ - void setSchemaPath(List schemaPath); - - /** - * Set a string that is used to specify a textual cross-reference to an - * external document, either another module that defines related management - * information, or a document that provides additional information relevant - * to this definition. - * - * @param reference - * a textual cross-reference to an external document. - */ - void setReference(String reference); - - /** - * Set the YANG source definition. - * - * @param definition YANG source definition, must not be null - */ - void setYangSourceDefinition(@NonNull YangSourceDefinition definition); - - /** - * Set the BindingNamespaceType. - * - * @param namespaceType BindingNamespaceType which type belongs to, must not be null - */ - void setBindingNamespaceType(@NonNull BindingNamespaceType namespaceType); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/MethodSignatureBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/MethodSignatureBuilder.java deleted file mode 100644 index d75114007a..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/MethodSignatureBuilder.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * Method Signature Builder serves solely for building Method Signature and - * returning the new instance of Method Signature.
- * By definition of {@link MethodSignature} the Method in java MUST contain - * Name, Return Type and Access Modifier. By default the Access Modifier can be - * set to public. The Method Signature builder does not contain method for - * addName due to enforce reason that MethodSignatureBuilder SHOULD be - * instantiated only once with defined method name.
- * The methods as {@link #addAnnotation(String, String)} and - * {@link #setComment(String)} can be used as optional because not all methods - * MUST contain annotation or comment definitions. - * - * - * @see MethodSignature - */ -@Beta -public interface MethodSignatureBuilder extends TypeMemberBuilder { - - /** - * Sets the flag for declaration of method as abstract or non abstract. If - * the flag isAbstract == true The instantiated Method - * Signature MUST have return value for {@link MethodSignature#isAbstract()} - * also equals to true. - * - * @param isAbstract - * is abstract flag - */ - MethodSignatureBuilder setAbstract(boolean isAbstract); - - /** - * Adds Parameter into the List of method parameters. Neither the Name or - * Type of parameter can be null. - * - *
- * In case that any of parameters are defined as null the - * method SHOULD throw an {@link IllegalArgumentException} - * - * @param type - * Parameter Type - * @param name - * Parameter Name - */ - MethodSignatureBuilder addParameter(final Type type, final String name); - - /** - * Returns new immutable instance of Method Signature.
- * The definingType param cannot be null. The - * every method in Java MUST be declared and defined inside the scope of - * class or interface definition. In case that - * defining Type will be passed as null reference the method - * SHOULD thrown {@link IllegalArgumentException}. - * - * @param definingType - * Defining Type of Method Signature - * @return new immutable instance of Method Signature. - */ - MethodSignature toInstance(final Type definingType); -} diff --git a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/TypeMemberBuilder.java b/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/TypeMemberBuilder.java deleted file mode 100644 index 80367bca27..0000000000 --- a/binding2/mdsal-binding2-generator-api/src/main/java/org/opendaylight/mdsal/binding/javav2/model/api/type/builder/TypeMemberBuilder.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.model.api.type.builder; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * - */ -@Beta -public interface TypeMemberBuilder> { - /** - * The method creates new AnnotationTypeBuilder containing specified package - * name an annotation name.
- * Neither the package name or annotation name can contain null - * references. In case that any of parameters contains null the - * method SHOULD thrown {@link IllegalArgumentException} - * - * @param packageName - * Package Name of Annotation Type - * @param name - * Name of Annotation Type - * @return new instance of Annotation Type Builder. - */ - AnnotationTypeBuilder addAnnotation(final String packageName, final String name); - - /** - * Returns the name of property. - * - * @return the name of property. - */ - String getName(); - - /** - * Adds return Type into Builder definition for Generated Property.
- * The return Type MUST NOT be null, otherwise the method - * SHOULD throw {@link IllegalArgumentException} - * - * @param returnType - * Return Type of property. - */ - T setReturnType(final Type returnType); - - AccessModifier getAccessModifier(); - - /** - * Sets the access modifier of property. - * - * @param modifier - * Access Modifier value. - */ - T setAccessModifier(final AccessModifier modifier); - - /** - * Adds String definition of comment into Method Signature definition.
- * The comment String MUST NOT contain anny comment specific chars (i.e. - * "/**" or "//") just plain String text description. - * - * @param comment - * Comment String. - */ - T setComment(final String comment); - - /** - * Sets the flag final for method signature. If this is set the method will - * be prohibited from overriding.
- * This setting is irrelevant for methods designated to be defined in - * interface definitions because interface can't have final method. - * - * @param isFinal - * Is Final - */ - T setFinal(final boolean isFinal); - - T setStatic(final boolean isStatic); -} diff --git a/binding2/mdsal-binding2-generator-impl/pom.xml b/binding2/mdsal-binding2-generator-impl/pom.xml deleted file mode 100644 index b6068ee266..0000000000 --- a/binding2/mdsal-binding2-generator-impl/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-generator-impl - 0.16.0-SNAPSHOT - bundle - - - - org.javassist - javassist - - - - org.opendaylight.yangtools - yang-parser-impl - - - org.opendaylight.yangtools - yang-data-impl - - - org.opendaylight.yangtools - yang-test-util - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - - - org.opendaylight.mdsal - mdsal-binding2-generator-util - - - org.opendaylight.mdsal - mdsal-binding2-util - - - com.google.guava - guava - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.groupId}.${project.artifactId} - - {local-packages}, - org.opendaylight.mdsal.binding2.generator.impl, - ;-split-package:=error - - - !javax.annotation, - * - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenType.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenType.java deleted file mode 100644 index efd19c3b43..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenType.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.processUsesImplements; - -import com.google.common.annotations.Beta; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.stream.Collectors; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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.DerivableSchemaNode; -import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; -import org.opendaylight.yangtools.yang.model.api.Module; -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.UsesNode; -import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; - -@Beta -final class AugmentToGenType { - - /** - * Comparator based on augment target path. - */ - private static final Comparator AUGMENT_COMP = (o1, o2) -> { - final Iterator thisIt = o1.getTargetPath().getPathFromRoot().iterator(); - final Iterator otherIt = o2.getTargetPath().getPathFromRoot().iterator(); - - while (thisIt.hasNext()) { - if (!otherIt.hasNext()) { - return 1; - } - - final int comp = thisIt.next().compareTo(otherIt.next()); - if (comp != 0) { - return comp; - } - } - - return otherIt.hasNext() ? -1 : 0; - }; - - /** - * Comparator based on augment target path. - */ - private static final Comparator>> AUGMENTS_COMP = (o1, o2) -> { - final Iterator thisIt = o1.getKey().getPathFromRoot().iterator(); - final Iterator otherIt = o2.getKey().getPathFromRoot().iterator(); - - while (thisIt.hasNext()) { - if (!otherIt.hasNext()) { - return 1; - } - - final int comp = thisIt.next().compareTo(otherIt.next()); - if (comp != 0) { - return comp; - } - } - - return otherIt.hasNext() ? -1 : 0; - }; - - private AugmentToGenType() { - throw new UnsupportedOperationException("Utility class"); - } - - /** - * Converts all augmentation of the module to the list - * Type objects. - * - * @param module - * module from which is obtained list of all augmentation objects - * to iterate over them - * @param schemaContext actual schema context - * @param typeProvider actual type provider instance - * @param genCtx generated input context - * @param genTypeBuilders auxiliary type builders map - * @param verboseClassComments verbosity switch - * - * @throws IllegalArgumentException - *
    - *
  • if the module is null
  • - *
  • if the name of module is null
  • - *
- * @throws IllegalStateException - * if set of augmentations from module is null - */ - static Map generate(final Module module, final SchemaContext schemaContext, - final TypeProvider typeProvider, final Map genCtx, - final Map> genTypeBuilders, final boolean verboseClassComments) { - - Preconditions.checkArgument(module != null, "Module reference cannot be NULL."); - Preconditions.checkArgument(module.getName() != null, "Module name cannot be NULL."); - Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL."); - - final String basePackageName = BindingMapping.getRootPackageName(module); - final List augmentations = resolveAugmentations(module, schemaContext); - Map resultCtx = genCtx; - - //let's group augments by target path - Map> augmentationsGrouped = - augmentations.stream().collect(Collectors.groupingBy(AugmentationSchemaNode::getTargetPath)); - - List>> sortedAugmentationsGrouped = - new ArrayList<>(augmentationsGrouped.entrySet()); - sortedAugmentationsGrouped.sort(AUGMENTS_COMP); - - //process child nodes of grouped augment entries - for (Map.Entry> schemaPathAugmentListEntry - : sortedAugmentationsGrouped) { - resultCtx = augmentationToGenTypes(basePackageName, schemaPathAugmentListEntry, module, schemaContext, - verboseClassComments, resultCtx, genTypeBuilders, typeProvider); - - for (AugmentationSchemaNode augSchema : schemaPathAugmentListEntry.getValue()) { - processUsesImplements(augSchema, module, schemaContext, genCtx, BindingNamespaceType.Data); - } - - } - - return resultCtx; - } - - /** - * Returns list of AugmentationSchema objects. The objects are - * sorted according to the length of their target path from the shortest to - * the longest. - * - * @param module - * module from which is obtained list of all augmentation objects - * @return list of sorted AugmentationSchema objects obtained - * from module - * @throws IllegalArgumentException - * if module is null - * @throws IllegalStateException - * if set of module augmentations is null - */ - @VisibleForTesting - static List resolveAugmentations(final Module module, - final SchemaContext schemaContext) { - Preconditions.checkArgument(module != null, "Module reference cannot be NULL."); - Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL."); - - final List sortedAugmentations = module.getAugmentations().stream() - .filter(aug -> !module.equals(findAugmentTargetModule(schemaContext, aug))) - .collect(Collectors.toList()); - sortedAugmentations.sort(AUGMENT_COMP); - return sortedAugmentations; - } - - public static Module findAugmentTargetModule(final SchemaContext schemaContext, - final AugmentationSchemaNode aug) { - requireNonNull(aug, "Augmentation schema can not be null."); - final QName first = aug.getTargetPath().getPathFromRoot().iterator().next(); - return schemaContext.findModule(first.getModule()).orElse(null); - } - - /** - * Converts augSchema to list of Type which - * contains generated type for augmentation. In addition there are also - * generated types for all containers, list and choices which are child of - * augSchema node or a generated types for cases are added if - * augmented node is choice. - * - * @param basePackageName - * string with the name of the package to which the augmentation - * belongs - * @param schemaPathAugmentListEntry - * list of AugmentationSchema nodes grouped by target path - * @param module current module - * @param schemaContext actual schema context - * @param verboseClassComments verbosity switch - * @param genCtx generated input context - * @param genTypeBuilders auxiliary type builders map - * @param typeProvider actual type provider instance - * @throws IllegalArgumentException - * if augmentPackageName equals null - * @throws IllegalStateException - * if augment target path is null - * @return generated context - */ - @VisibleForTesting - static Map augmentationToGenTypes(final String basePackageName, - final Entry> schemaPathAugmentListEntry, final Module module, - final SchemaContext schemaContext, final boolean verboseClassComments, - Map genCtx, final Map> genTypeBuilders, - final TypeProvider typeProvider) { - Preconditions.checkArgument(basePackageName != null, "Package Name cannot be NULL."); - Preconditions.checkArgument(schemaPathAugmentListEntry != null, "Augmentation List Entry cannot be NULL."); - final SchemaPath targetPath = schemaPathAugmentListEntry.getKey(); - Preconditions.checkState(targetPath != null, - "Augmentation List Entry does not contain Target Path (Target Path is NULL)."); - - final List augmentationSchemaList = schemaPathAugmentListEntry.getValue(); - Preconditions.checkState(!augmentationSchemaList.isEmpty(), - "Augmentation List cannot be empty."); - - SchemaNode targetSchemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, targetPath); - if (targetSchemaNode == null) { - throw new IllegalArgumentException("augment target not found: " + targetPath); - } - - GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(), - genCtx); - if (targetTypeBuilder == null) { - targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), genCtx); - } - if (targetTypeBuilder == null) { - throw new NullPointerException("Target type not yet generated: " + targetSchemaNode); - } - - final String augmentPackageName = - BindingGeneratorUtil.packageNameWithNamespacePrefix(basePackageName, BindingNamespaceType.Data); - - if (!(targetSchemaNode instanceof ChoiceSchemaNode)) { - genCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, augmentPackageName, - targetTypeBuilder, targetSchemaNode, schemaPathAugmentListEntry.getValue(), - genTypeBuilders, genCtx, schemaContext, verboseClassComments, typeProvider, - targetTypeBuilder.getBindingNamespaceType()); - } else { - genCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, basePackageName, - targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode, - schemaPathAugmentListEntry.getValue(),genCtx, verboseClassComments, genTypeBuilders, typeProvider, - targetTypeBuilder.getBindingNamespaceType()); - } - return genCtx; - } - - /** - * Convenient method to find node added by uses statement. - * @param schemaContext - * actual schema context - * @param targetPath - * node path - * @param parentUsesNode - * parent of uses node - * @return node from its original location in grouping - */ - @VisibleForTesting - static DataSchemaNode findOriginalTargetFromGrouping(final SchemaContext schemaContext, - final SchemaPath targetPath, final UsesNode parentUsesNode) { - SchemaNode targetGrouping = null; - QName current = parentUsesNode.getGroupingPath().getPathFromRoot().iterator().next(); - Module module = schemaContext.findModule(current.getModule()).orElse(null); - if (module == null) { - throw new IllegalArgumentException("Fialed to find module for grouping in: " + parentUsesNode); - } - for (GroupingDefinition group : module.getGroupings()) { - if (group.getQName().equals(current)) { - targetGrouping = group; - break; - } - } - - if (targetGrouping == null) { - throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode); - } - - SchemaNode result = targetGrouping; - for (final QName node : targetPath.getPathFromRoot()) { - if (result instanceof DataNodeContainer) { - final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName()); - result = ((DataNodeContainer) result).getDataChildByName(resultNode); - } else if (result instanceof ChoiceSchemaNode) { - result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName()); - } - } - if (result == null) { - return null; - } - - if (result instanceof DerivableSchemaNode) { - DerivableSchemaNode castedResult = (DerivableSchemaNode) result; - Optional originalNode = castedResult - .getOriginal(); - if (castedResult.isAddedByUses() && originalNode.isPresent()) { - result = originalNode.get(); - } - } - - if (result instanceof DataSchemaNode) { - DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result; - if (resultDataSchemaNode.isAddedByUses()) { - // The original node is required, but we have only the copy of - // the original node. - // Maybe this indicates a bug in Yang parser. - throw new IllegalStateException( - "Failed to generate code for augment in " - + parentUsesNode); - } else { - return resultDataSchemaNode; - } - } else { - throw new IllegalStateException( - "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in " - + parentUsesNode); - } - } - - /** - * Generates list of generated types for all the cases of a choice which are - * added to the choice through the augment. - * - * @param schemaContext - * actual schema context - * @param module - * current module - * @param basePackageName - * string contains name of package to which augment belongs. If - * an augmented choice is from an other package (pcg1) than an - * augmenting choice (pcg2) then case's of the augmenting choice - * will belong to pcg2. - * @param targetType - * Type which represents target choice - * @param targetNode - * node which represents target choice - * @param schemaPathAugmentListEntry - * list of AugmentationSchema nodes grouped by target path - * @return list of generated types which represents augmented cases of - * choice refChoiceType - * @throws IllegalArgumentException - *
    - *
  • if basePackageName is null
  • - *
  • if targetType is null
  • - *
  • if augmentedNodes is null
  • - *
- */ - @VisibleForTesting - static Map generateTypesFromAugmentedChoiceCases( - final SchemaContext schemaContext, final Module module, - final String basePackageName, final GeneratedType targetType, final ChoiceSchemaNode targetNode, - final List schemaPathAugmentListEntry, - final Map genCtx, final boolean verboseClassComments, - final Map> genTypeBuilders, final TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL."); - Preconditions.checkArgument(targetType != null, "Referenced Choice Type cannot be NULL."); - Preconditions.checkArgument(schemaPathAugmentListEntry != null, "Set of Choice Case Nodes cannot be NULL."); - - - for (final AugmentationSchemaNode augmentationSchema : schemaPathAugmentListEntry) { - for (final DataSchemaNode childNode : augmentationSchema.getChildNodes()) { - if (childNode != null) { - final GeneratedTypeBuilder caseTypeBuilder = - GenHelperUtil.addDefaultInterfaceDefinition(basePackageName, childNode, null, module, - genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - caseTypeBuilder.addImplementsType(targetType); - caseTypeBuilder.setParentTypeForBuilder(targetType.getParentTypeForBuilder()); - - //Since uses augment nodes has been processed as inline nodes, - //we just take two situations below. - final CaseSchemaNode caseNode; - if (childNode instanceof CaseSchemaNode) { - caseNode = (CaseSchemaNode) childNode; - } else { - caseNode = findNamedCase(targetNode, childNode.getQName().getLocalName()); - if (caseNode == null) { - throw new IllegalArgumentException("Failed to find case node " + childNode); - } - } - - final Collection childNodes = caseNode.getChildNodes(); - if (!childNodes.isEmpty()) { - GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, - (GeneratedTypeBuilder) targetType.getParentTypeForBuilder(), childNodes, genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - processUsesImplements(caseNode, module, schemaContext, genCtx, namespaceType); - } - genCtx.get(module).addCaseType(childNode.getPath(), caseTypeBuilder); - genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, caseNode); - } - } - } - return genCtx; - } - - private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) { - final List cases = choice.findCaseNodes(caseName); - return cases.isEmpty() ? null : cases.get(0); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtils.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtils.java deleted file mode 100755 index f67342b5aa..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtils.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN; - -import com.google.common.annotations.Beta; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Splitter; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.generator.util.TypeComments; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -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.Status; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; -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; - -/** - * Auxiliary util class for {@link GenHelperUtil} class. - */ -@Beta -final class AuxiliaryGenUtils { - - private static final Splitter BSDOT_SPLITTER = Splitter.on("."); - private static final char NEW_LINE = '\n'; - private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u"); - - /** - * Constant with the concrete name of identifier. - */ - private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier"; - - /** - * Constant with the concrete name of namespace. - */ - private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext"; - - private AuxiliaryGenUtils() { - throw new UnsupportedOperationException("Util class"); - } - - static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) { - if (status == Status.DEPRECATED) { - builder.addAnnotation("", "Deprecated"); - } - } - - static Constant qNameConstant(final GeneratedTypeBuilderBase toBuilder, final String constantName, - final QName name) { - return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name); - } - - /** - * Created a method signature builder as part of - * interfaceBuilder. - * - *

- * The method signature builder is created for the getter method of - * schemaNodeName. Also comment and - * returnType information are added to the builder. - * - * @param interfaceBuilder generated type builder for which the getter method should be - * created - * @param schemaNodeName string with schema node name. The name will be the part of the - * getter method name. - * @param comment string with comment for the getter method - * @param returnType type which represents the return type of the getter method - * @param status status from yang file, for deprecated annotation - * @return method signature builder which represents the getter method of - * interfaceBuilder - */ - static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, - final String schemaNodeName, final String comment, final Type - returnType, final Status status) { - - final MethodSignatureBuilder getMethod = interfaceBuilder - .addMethod(getterMethodName(schemaNodeName, returnType)); - if (status == Status.DEPRECATED) { - getMethod.addAnnotation("", "Deprecated"); - } - getMethod.setComment(encodeAngleBrackets(comment)); - getMethod.setReturnType(returnType); - return getMethod; - } - - /** - * Creates the name of the getter method name from localName. - * - * @param localName string with the name of the getter method - * @param returnType return type - * @return string with the name of the getter method for - * methodName in JAVA method format - */ - @VisibleForTesting - static String getterMethodName(final String localName, final Type returnType) { - final StringBuilder method = new StringBuilder(); - if (BOOLEAN.equals(returnType)) { - method.append("is"); - } else { - method.append("get"); - } - return method.append(JavaIdentifierNormalizer.normalizeSpecificIdentifier(localName, JavaIdentifier.CLASS)) - .toString(); - } - - public static boolean hasBuilderClass(final SchemaNode schemaNode, final BindingNamespaceType namespaceType) { - return (BindingNamespaceType.isData(namespaceType) - && (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode - || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition - || schemaNode instanceof CaseSchemaNode)); - } - - @VisibleForTesting - static boolean isNullOrEmpty(final Collection list) { - return list == null || list.isEmpty(); - } - - /** - * Returns first unique name for the augment generated type builder. The - * generated type builder name for augment consists from name of augmented - * node and serial number of its augmentation. - * - * @param builders map of builders which were created in the package to which the - * augmentation belongs - * @param genTypeName string with name of augmented node - * @return string with unique name for augmentation builder - */ - static String augGenTypeName(final Map builders, final String genTypeName) { - int index = 1; - if (builders != null) { - while (builders.containsKey(genTypeName + index)) { - index = index + 1; - } - } - return genTypeName + index; - } - - /** - * Return augment identifier. - * - * @param unknownSchemaNodes unknown schema nodes - * @return nodeParameter of UnknownSchemaNode - */ - static String getAugmentIdentifier(final List 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())) { - return unknownSchemaNode.getNodeParameter(); - } - } - return null; - } - - /** - * Adds enumeration builder created from enumTypeDef to - * typeBuilder. - * - *

- * Each enumTypeDef item is added to builder with its name and - * value. - * - * @param enumTypeDef EnumTypeDefinition contains enum data - * @param enumName string contains name which will be assigned to enumeration - * 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 - * enumTypeDef - */ - static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName, - final Map genCtx, final - GeneratedTypeBuilder typeBuilder, final Module module) { - if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) { - final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName(), genCtx.get(module)); - final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null)); - enumBuilder.setDescription(enumTypedefDescription); - enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef); - final ModuleContext ctx = genCtx.get(module); - ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder); - return enumBuilder; - } - return null; - } - - - /** - * Builds generated TO builders for typeDef of type - * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are - * also added to typeBuilder as enclosing transfer object. - * - *

- * If more then one generated TO builder is created for enclosing then all - * of the generated TO builders are added to typeBuilder as - * enclosing transfer objects. - * - * @param typeDef type definition which can be of type UnionType or - * BitsTypeDefinition - * @param typeBuilder generated type builder to which is added generated TO created - * from typeDef - * @param leaf string with name for generated TO builder - * @param parentModule parent module - * @return generated TO builder for typeDef - */ - static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition typeDef, final GeneratedTypeBuilder - typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider, - final SchemaContext schemaContext, ModuleContext context, final - Map genCtx) { - final String classNameFromLeaf = leaf.getQName().getLocalName(); - GeneratedTOBuilder genTOBuilder = null; - final String packageName = typeBuilder.getFullyQualifiedName(); - if (typeDef instanceof UnionTypeDefinition) { - genTOBuilder = ((TypeProviderImpl) typeProvider) - .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef), - classNameFromLeaf, leaf, context); - } else if (typeDef instanceof BitsTypeDefinition) { - genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition( - packageName, typeDef, classNameFromLeaf, parentModule.getName(), context); - } - if (genTOBuilder != null) { - typeBuilder.addEnclosingTransferObject(genTOBuilder); - genCtx.get(parentModule).addInnerTypedefType(typeDef.getPath(), genTOBuilder); - return genTOBuilder; - } - return null; - - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition typeDef, - final GeneratedTypeBuilder typeBuilder, final Module parentModule, final - TypeProvider typeProvider, - final boolean verboseClassComments) { - final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder; - - if (verboseClassComments) { - YangSourceDefinition.of(parentModule, typeDef).ifPresent(returnType::setYangSourceDefinition); - TypeComments.description(typeDef).ifPresent(returnType::addComment); - typeDef.getDescription().ifPresent(returnType::setDescription); - typeDef.getReference().ifPresent(returnType::setReference); - } - returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot()); - returnType.setModuleName(parentModule.getName()); - - genTOBuilder.setTypedef(true); - genTOBuilder.setIsUnion(true); - TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null)); - - return returnType.toInstance(); - } - - static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition type) { - return leaf.getPath().equals(type.getPath()) || leaf.getPath().equals(type.getPath().getParent()); - - } - - /** - * Generates for the list which contains any list keys special - * generated TO builder. - * - * @param packageName string with package name to which the list belongs - * @param list schema node of list - * @return generated TO builder which represents the keys of the - * list or empty TO builder if list is null or list of - * key definitions is null or empty. - */ - static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list, - ModuleContext context) { - GeneratedTOBuilder genTOBuilder = null; - if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) { - // underscore used as separator for distinction of class name parts - final String genTOName = - new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key) - .toString(); - genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName, context); - } - return genTOBuilder; - } - - static GeneratedTypeBuilder resolveListKeyTypeBuilder(final String packageName, final ListSchemaNode list, - ModuleContext context) { - GeneratedTypeBuilder genTypeBuilder = null; - if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) { - // underscore used as separator for distinction of class name parts - final String genTOName = - new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key) - .toString(); - genTypeBuilder = new GeneratedTypeBuilderImpl(packageName, genTOName, context); - } - return genTypeBuilder; - } - - /** - * Converts leaf schema node to property of generated TO - * builder. - * - * @param toBuilder generated TO builder to which is leaf added as - * property - * @param leaf leaf schema node which is added to toBuilder as - * property - * @param returnType property type - * @param isReadOnly boolean value which says if leaf property is|isn't read only - * @return boolean value - *

    - *
  • false - if leaf, toBuilder or leaf - * name equals null or if leaf is added by uses.
  • - *
  • true - other cases
  • - *
- */ - static boolean resolveLeafSchemaNodeAsProperty(final String nodeName, final GeneratedTOBuilder toBuilder, - final LeafSchemaNode leaf, final Type returnType, final boolean - isReadOnly) { - - if (returnType == null) { - return false; - } - final String leafName = leaf.getQName().getLocalName(); - final String leafGetterName; - - if ("key".equals(leafName.toLowerCase())) { - StringBuilder sb = new StringBuilder(leafName) - .append('_').append("RESERVED_WORD"); - leafGetterName = sb.toString(); - } else { - leafGetterName = leafName; - } - - final String leafDesc = encodeAngleBrackets(leaf.getDescription().orElse(null)); - final GeneratedPropertyBuilder propBuilder = - toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafGetterName, - JavaIdentifier.METHOD)); - propBuilder.setReadOnly(isReadOnly); - propBuilder.setReturnType(returnType); - propBuilder.setComment(leafDesc); - toBuilder.addEqualsIdentity(propBuilder); - toBuilder.addHashIdentity(propBuilder); - toBuilder.addToStringProperty(propBuilder); - return true; - } - - static void checkModuleAndModuleName(final Module module) { - checkArgument(module != null, "Module reference cannot be NULL."); - checkArgument(module.getName() != null, "Module name cannot be NULL."); - } - - @VisibleForTesting - public static String replaceAllIllegalChars(final StringBuilder stringBuilder) { - final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u"); - return ret.isEmpty() ? "" : ret; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImpl.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImpl.java deleted file mode 100644 index 9b30a35957..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImpl.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort; - -/** - * Main class for Binding generator v2. Provides transformation of Schema Context to - * generated transfer objects. Process is accompanied with Twirl templates to generate - * particular Javadoc for related YANG elements. - */ -@Beta -public class BindingGeneratorImpl implements BindingGenerator { - - /** - * When set to true, generated classes will include Javadoc comments - * which are useful for users. - */ - private final boolean verboseClassComments; - - /** - * Outer key represents the package name. Outer value represents map of all - * builders in the same package. Inner key represents the schema node name - * (in JAVA class/interface name format). Inner value represents instance of - * builder for schema node specified in key part. - */ - //TODO: convert it to local variable eventually - private Map> genTypeBuilders = new HashMap<>(); - - private Map genCtx = new HashMap<>(); - - /** - * Provide methods for converting YANG types to JAVA types. - */ - private TypeProvider typeProvider; - - /** - * Creates a new binding generator v2. - * - * @param verboseClassComments generate verbose comments - */ - public BindingGeneratorImpl(final boolean verboseClassComments) { - this.verboseClassComments = verboseClassComments; - } - - /** - * Resolves generated types from context schema nodes of all modules. - * - *

- * Generated types are created for modules, groupings, types, containers, lists, choices, augments, rpcs, - * notification, identities. - * - * @param context schema context which contains data about all schema nodes saved in modules - * @return list of types (usually GeneratedType GeneratedTransferObjectwhich are generated - * from context data. - * @throws IllegalArgumentException if arg context is null - * @throws IllegalStateException if context contain no modules - */ - @Override - public List generateTypes(final SchemaContext context) { - Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL."); - Preconditions.checkState(context.getModules() != null, "Schema Context does not contain defined modules."); - final Set modules = context.getModules(); - return generateTypes(context, modules); - } - - /** - * Resolves generated types from context schema nodes only for - * modules specified in modules - * - *

- * Generated types are created for modules, groupings, types, containers, - * lists, choices, augments, rpcs, notification, identities. - * - * @param context - * schema context which contains data about all schema nodes - * saved in modules - * @param modules - * set of modules for which schema nodes should be generated - * types - * @return list of types (usually GeneratedType or - * GeneratedTransferObject) which: - *

    - *
  • are generated from context schema nodes and
  • - *
  • are also part of some of the module in modules - * set.
  • - *
- * @throws IllegalArgumentException - *
    - *
  • if arg context is null or
  • - *
  • if arg modules is null
  • - *
- * @throws IllegalStateException - * if context contain no modules - */ - @Override - public List generateTypes(final SchemaContext context, final Set modules) { - Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL."); - Preconditions.checkState(context.getModules() != null, "Schema Context does not contain defined modules."); - Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL."); - - this.typeProvider = new TypeProviderImpl(context); - final List contextModules = ModuleDependencySort.sort(context.getModules()); - this.genTypeBuilders = new HashMap<>(); - - for (final Module contextModule : contextModules) { - this.genCtx = ModuleToGenType.generate(contextModule, this.genTypeBuilders, context, this.typeProvider, - this.genCtx, this.verboseClassComments); - this.genCtx.get(contextModule).cleanPackagesMap(); - } - for (final Module contextModule : contextModules) { - this.genCtx = AugmentToGenType.generate(contextModule, context, this.typeProvider, this.genCtx, - this.genTypeBuilders, this.verboseClassComments); - this.genCtx.get(contextModule).cleanPackagesMap(); - } - - final List filteredGenTypes = new ArrayList<>(); - for (final Module m : modules) { - final ModuleContext ctx = requireNonNull(this.genCtx.get(m), - () -> "Module context not found for module " + m); - filteredGenTypes.addAll(ctx.getGeneratedTypes()); - final Set additionalTypes = ((TypeProviderImpl) this.typeProvider).getAdditionalTypes().get(m); - if (additionalTypes != null) { - filteredGenTypes.addAll(additionalTypes); - } - } - - return filteredGenTypes; - } - - /** - * Return module contexts from generated types according to context. - * - * @param schemaContext - * - for generating types - * @return module contexts - */ - public Map getModuleContexts(final SchemaContext schemaContext) { - generateTypes(schemaContext); - return this.genCtx; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GenHelperUtil.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GenHelperUtil.java deleted file mode 100755 index 9dc44c119e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GenHelperUtil.java +++ /dev/null @@ -1,1438 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.addTOToTypeBuilder; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.annotateDeprecatedIfNecessary; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.constructGetter; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.createReturnTypeForUnion; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.getAugmentIdentifier; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.isInnerType; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.qNameConstant; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.resolveListKeyTOBuilder; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.resolveListKeyTypeBuilder; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.computeDefaultSUID; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.packageNameForGeneratedType; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.IDENTIFIABLE; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.IDENTIFIER; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.NOTIFICATION; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.parameterizedTypeFor; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.wildcardTypeFor; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.resolveRegExpressions; -import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.TypeComments; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.BaseYangTypes; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.GroupingDefinitionDependencySort; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AnyDataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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.DerivableSchemaNode; -import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; -import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; -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.Status; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -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.PatternConstraint; -import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; -import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils; - -/** - * Helper util class used for generation of types in Binding spec v2. - */ -@Beta -final class GenHelperUtil { - - private GenHelperUtil() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Create GeneratedTypeBuilder object from module argument. - * - * @param module Module object from which builder will be created - * @param genCtx generated context - * @param verboseClassComments verbosity switch - * @return GeneratedTypeBuilder which is internal - * representation of the module - * @throws IllegalArgumentException if module is null - */ - static GeneratedTypeBuilder moduleToDataType(final Module module, final Map genCtx, - final boolean verboseClassComments) { - Preconditions.checkArgument(module != null, "Module reference cannot be NULL."); - - final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data", verboseClassComments, - genCtx.get(module)); - addImplementedInterfaceFromUses(module, moduleDataTypeBuilder, genCtx); - moduleDataTypeBuilder.addImplementsType(BindingTypes.TREE_ROOT); - - if (verboseClassComments) { - YangSourceDefinition.of(module).ifPresent(moduleDataTypeBuilder::setYangSourceDefinition); - TypeComments.description(module).ifPresent(moduleDataTypeBuilder::addComment); - module.getDescription().ifPresent(moduleDataTypeBuilder::setDescription); - module.getReference().ifPresent(moduleDataTypeBuilder::setReference); - } - - return moduleDataTypeBuilder; - } - - /** - * Generates type builder for module. - * - * @param module Module which is source of package name for generated type - * builder - * @param postfix string which is added to the module class name representation - * as suffix - * @param verboseClassComments verbosity switch - * @return instance of GeneratedTypeBuilder which represents - * module. - * @throws IllegalArgumentException if module is null - */ - static GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix, final boolean - verboseClassComments, final ModuleContext context) { - Preconditions.checkArgument(module != null, "Module reference cannot be NULL."); - final String packageName = BindingMapping.getRootPackageName(module); - // underscore used as separator for distinction of module name parts - final String moduleName = new StringBuilder(module.getName()).append('_').append(postfix).toString(); - - final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName, context); - if (verboseClassComments) { - YangSourceDefinition.of(module).ifPresent(moduleBuilder::setYangSourceDefinition); - TypeComments.description(module).ifPresent(moduleBuilder::addComment); - module.getDescription().ifPresent(moduleBuilder::setDescription); - module.getReference().ifPresent(moduleBuilder::setReference); - } - moduleBuilder.setModuleName(moduleName); - return moduleBuilder; - } - - /** - * Adds the implemented types to type builder. - * - *

- * The method passes through the list of uses in - * {@code dataNodeContainer}. For every use is obtained corresponding - * generated type from all groupings - * allGroupings} which is added as implements type to - * builder - * - * @param dataNodeContainer element which contains the list of used YANG groupings - * @param builder builder to which are added implemented types according to - * dataNodeContainer - * @param genCtx generated context - * @return generated type builder with all implemented types - */ - static GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer, - final GeneratedTypeBuilder builder, final Map genCtx) { - for (final UsesNode usesNode : dataNodeContainer.getUses()) { - final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath(), genCtx).toInstance(); - if (genType == null) { - throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for " - + builder.getName()); - } - builder.addImplementsType(genType); - } - return builder; - } - - static GeneratedTypeBuilder findGroupingByPath(final SchemaPath path, final Map genCtx) { - for (final ModuleContext ctx : genCtx.values()) { - final GeneratedTypeBuilder result = ctx.getGrouping(path); - if (result != null) { - return result; - } - } - return null; - } - - static GeneratedTypeBuilder findIdentityByQname(final QName qname, final Map genCtx) { - for (final ModuleContext ctx : genCtx.values()) { - final GeneratedTypeBuilder result = ctx.getIdentities().get(qname); - if (result != null) { - return result; - } - } - return null; - } - - /** - * Adds the methods to typeBuilder which represent subnodes of - * node for which typeBuilder was created. - * - *

- * The subnodes aren't mapped to the methods if they are part of grouping or - * augment (in this case are already part of them). - * - * @param module current module - * @param basePackageName string contains the module package name - * @param parent generated type builder which represents any node. The subnodes - * of this node are added to the typeBuilder as - * methods. The subnode can be of type leaf, leaf-list, list, - * container, choice. - * @param childOf parent type - * @param schemaNodes set of data schema nodes which are the children of the node - * for which typeBuilder was created - * @return generated type builder which is the same builder as input - * parameter. The getter methods (representing child nodes) could be - * added to it. - */ - static GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName, - final GeneratedTypeBuilder parent, final GeneratedTypeBuilder - childOf, - final Iterable schemaNodes, final Map genCtx, - final SchemaContext schemaContext, final boolean - verboseClassComments, - final Map> - genTypeBuilders, - final TypeProvider typeProvider, final BindingNamespaceType - namespaceType) { - - if (schemaNodes != null && parent != null) { - for (final DataSchemaNode schemaNode : schemaNodes) { - if (resolveDataSchemaNodesCheck(module, schemaContext, schemaNode)) { - addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module, genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - } - } - } - return parent; - } - - static boolean resolveDataSchemaNodesCheck(final Module module, final SchemaContext schemaContext, - final DataSchemaNode schemaNode) { - if (!schemaNode.isAugmenting()) { - return true; - } - - final QName qname = schemaNode.getPath().getLastComponent(); - final Module originalModule = schemaContext.findModule(qname.getModule()).get(); - return module.equals(originalModule); - } - - private static QName createQNameFromSuperNode(final Module module, final Object node, final SchemaNode - superChildNode) { - QName childNodeQName = null; - if (node instanceof Module) { - childNodeQName = QName.create(((Module) node).getQNameModule(), superChildNode.getQName().getLocalName()); - } else if (node instanceof SchemaNode) { - childNodeQName = QName.create(((SchemaNode) node).getQName(), superChildNode.getQName().getLocalName()); - } else if (node instanceof AugmentationSchemaNode) { - childNodeQName = QName.create(module.getQNameModule(), superChildNode.getQName().getLocalName()); - } else { - throw new IllegalArgumentException("Not support node type:" + node); - } - - return childNodeQName; - } - - private static void addUsesImplements(final SchemaNode superNode, final Module superModule, - final Object node, final Module module, final SchemaContext schemaContext, - final Map genCtx, final BindingNamespaceType - namespaceType) { - if (superNode instanceof DataNodeContainer) { - for (DataSchemaNode superChildNode : ((DataNodeContainer) superNode).getChildNodes()) { - if (superChildNode instanceof DataNodeContainer || superChildNode instanceof ChoiceSchemaNode) { - final QName childQName = createQNameFromSuperNode(module, node, superChildNode); - DataSchemaNode childNode = ((DataNodeContainer) node).getDataChildByName(childQName); - requireNonNull(childNode, () -> node + "->" + childQName); - - final GeneratedTypeBuilder type = genCtx.get(module).getChildNode(childNode.getPath()); - final GeneratedTypeBuilder superType = genCtx.get(superModule).getChildNode(superChildNode - .getPath()); - - requireNonNull(type, () -> module + "->" + childNode.getPath()); - requireNonNull(superType, () -> superModule + "->" + superChildNode.getPath()); - type.addImplementsType(superType); - if (superChildNode instanceof ListSchemaNode - && !((ListSchemaNode) superChildNode).getKeyDefinition().isEmpty()) { - if (BindingNamespaceType.isGrouping(namespaceType)) { - genCtx.get(module).getKeyType(childNode.getPath()) - .addImplementsType(genCtx.get(superModule).getKeyType(superChildNode.getPath())); - } else if (BindingNamespaceType.isData(namespaceType)) { - genCtx.get(module).getKeyGenTO(childNode.getPath()) - .addImplementsType(genCtx.get(superModule).getKeyType(superChildNode.getPath())); - } - } - addUsesImplements(superChildNode, superModule, childNode, module, schemaContext, genCtx, - namespaceType); - } - } - } else if (superNode instanceof ChoiceSchemaNode) { - for (CaseSchemaNode superCaseNode : ((ChoiceSchemaNode) superNode).getCases().values()) { - final QName childQName = createQNameFromSuperNode(module, node, superCaseNode); - CaseSchemaNode caseNode = ((ChoiceSchemaNode) node).getCaseNodeByName(childQName); - requireNonNull(caseNode, () -> node + "->" + childQName); - - final GeneratedTypeBuilder type = genCtx.get(module).getCase(caseNode.getPath()); - final GeneratedTypeBuilder superType = genCtx.get(superModule).getCase(superCaseNode.getPath()); - requireNonNull(type, () -> module + "->" + caseNode.getPath()); - requireNonNull(superType, () -> superModule + "->" + superCaseNode.getPath()); - type.addImplementsType(superType); - addUsesImplements(superCaseNode, superModule, caseNode, module, schemaContext, genCtx, namespaceType); - } - } else { - throw new IllegalArgumentException("Not support super node :" + superNode); - } - } - - private static GroupingDefinition findGroupingNodeFromUses(final Module module, final SchemaContext schemaContext, - final Object parentNode, final UsesNode usesNode) { - SchemaNode groupingNode; - if (parentNode instanceof Module) { - final Module superModule = schemaContext.findModule( - usesNode.getGroupingPath().getLastComponent().getModule()).get(); - groupingNode = superModule.getGroupings() - .stream().filter(grouping -> grouping.getPath().equals(usesNode.getGroupingPath())) - .findFirst().orElse(null); - } else { - //FIXME: Schema path is not unique for Yang 1.1, findDataSchemaNode always does search from data node first. - final Iterable prefixedPath = usesNode.getGroupingPath().getPathFromRoot(); - final QName current = prefixedPath.iterator().next(); - final Module targetModule = schemaContext.findModule(current.getModule()).orElse(null); - Preconditions.checkArgument(targetModule != null, "Cannot find target module for %s and %s.", - current.getNamespace(), current.getRevision()); - groupingNode = targetModule.getGroupings().stream() - .filter(grouping -> grouping.getPath().equals(usesNode.getGroupingPath())) - .collect(Collectors.toList()).get(0); - if (groupingNode == null) { - groupingNode = SchemaContextUtil.findDataSchemaNode(schemaContext, usesNode.getGroupingPath()); - } - } - - requireNonNull(groupingNode, () -> module + "->" + usesNode.getGroupingPath()); - Preconditions.checkState(groupingNode instanceof GroupingDefinition, "%s->%s", module, - usesNode.getGroupingPath()); - return (GroupingDefinition) groupingNode; - } - - static Map processUsesImplements(final Object node, final Module module, - final SchemaContext schemaContext, final Map genCtx, final BindingNamespaceType namespaceType) { - if (node instanceof DataNodeContainer) { - for (final UsesNode usesNode : ((DataNodeContainer) node).getUses()) { - final GroupingDefinition grouping = findGroupingNodeFromUses(module, schemaContext, node, usesNode); - final Module superModule = SchemaContextUtil.findParentModule(schemaContext, grouping); - addUsesImplements(grouping, superModule, node, module, schemaContext, genCtx, namespaceType); - } - } - return genCtx; - } - - static GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path, final Map genCtx) { - for (final ModuleContext ctx : genCtx.values()) { - final GeneratedTypeBuilder result = ctx.getChildNode(path); - if (result != null) { - return result; - } - } - return null; - } - - static GeneratedTypeBuilder findCaseByPath(final SchemaPath path, final Map genCtx) { - for (final ModuleContext ctx : genCtx.values()) { - final GeneratedTypeBuilder result = ctx.getCase(path); - if (result != null) { - return result; - } - } - return null; - } - - static Map addRawAugmentGenTypeDefinition(final Module module, - final String augmentPackageName, final GeneratedTypeBuilder targetTypeBuilder, final SchemaNode targetNode, - final List schemaPathAugmentListEntry, final Map> genTypeBuilders, final Map genCtx, - final SchemaContext schemaContext, final boolean verboseClassComments, final TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - - //pick augmentation grouped by augmentation target, there is always at least one - final AugmentationSchemaNode augSchema = schemaPathAugmentListEntry.get(0); - - //this requires valid semantics in YANG model - String augIdentifier = null; - for (AugmentationSchemaNode aug : schemaPathAugmentListEntry) { - // FIXME: when there're multiple augment identifiers for augmentations of same target, - // it would pick the first identifier. - augIdentifier = getAugmentIdentifier(aug.getUnknownSchemaNodes()); - break; - } - - if (augIdentifier == null) { - augIdentifier = new StringBuilder(module.getName()) - .append('_').append(targetNode.getQName().getLocalName()).toString(); - } - - GeneratedTypeBuilderImpl augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augIdentifier, - true, false, genCtx.get(module)); - - augTypeBuilder.addImplementsType(BindingTypes.TREE_NODE); - augTypeBuilder.addImplementsType(parameterizedTypeFor(BindingTypes.INSTANTIABLE, augTypeBuilder)); - augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeBuilder.toInstance())); - augTypeBuilder.setBasePackageName(BindingMapping.getRootPackageName(module)); - augTypeBuilder.setWithBuilder(true); - augTypeBuilder.setBindingNamespaceType(namespaceType); - annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder); - - //If target is case node then pass down parent type (the closest ancestor) to children data nodes. - final GeneratedTypeBuilder childOf; - if (targetNode instanceof CaseSchemaNode) { - childOf = (GeneratedTypeBuilder) targetTypeBuilder.getParentTypeForBuilder(); - } else { - augTypeBuilder.setParentTypeForBuilder(targetTypeBuilder); - childOf = targetTypeBuilder; - } - - //produces getters for augTypeBuilder eventually - for (AugmentationSchemaNode aug : schemaPathAugmentListEntry) { - //apply all uses - addImplementedInterfaceFromUses(aug, augTypeBuilder, genCtx); - augSchemaNodeToMethods(module, BindingMapping.getRootPackageName(module), augTypeBuilder, childOf, - aug.getChildNodes(), genCtx, schemaContext, verboseClassComments, typeProvider, genTypeBuilders, - targetTypeBuilder.getBindingNamespaceType()); - } - - final Map augmentBuilders = genTypeBuilders.computeIfAbsent( - augmentPackageName, k -> new HashMap<>()); - - augmentBuilders.put(augTypeBuilder.getName(), augTypeBuilder); - - if (!augSchema.getChildNodes().isEmpty()) { - genCtx.get(module).addTargetToAugmentation(augTypeBuilder, augSchema.getTargetPath()); - } - genCtx.get(module).addAugmentType(augTypeBuilder); - genCtx.get(module).addTypeToAugmentations(augTypeBuilder, schemaPathAugmentListEntry); - return genCtx; - } - - /** - * Adds the methods to typeBuilder what represents subnodes of - * node for which typeBuilder was created. - * - * @param module current module - * @param basePackageName string contains the module package name - * @param typeBuilder generated type builder which represents any node. The subnodes - * of this node are added to the typeBuilder as - * methods. The subnode can be of type leaf, leaf-list, list, - * container, choice. - * @param childOf parent type - * @param schemaNodes set of data schema nodes which are the children of the node - * for which typeBuilder was created - * @return generated type builder which is the same object as the input added to it. - */ - private static GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName, - final GeneratedTypeBuilder typeBuilder, final - GeneratedTypeBuilder childOf, final - Iterable schemaNodes, - final Map genCtx, final - SchemaContext schemaContext, final boolean - verboseClassComments, final TypeProvider - typeProvider, final Map> genTypeBuilders, final BindingNamespaceType namespaceType) { - if (schemaNodes != null && typeBuilder != null) { - for (final DataSchemaNode schemaNode : schemaNodes) { - if (!schemaNode.isAugmenting()) { - addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module, genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - } - } - } - return typeBuilder; - } - - /** - * Instantiates generated type builder with packageName and - * schemaNode. - * - *

- * The new builder always implements - * {@link TreeNode TreeNode}.
- * If schemaNode is instance of GroupingDefinition it also - * implements {@link Augmentable - * Augmentable}.
- * If schemaNode is instance of - * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer - * DataNodeContainer} it can also implement nodes which are specified in - * uses. - * - * @param basePackageName string contains the module package name - * @param schemaNode schema node for which is created generated type builder - * @param childOf parent generated type of data tree node, which should be - * set null if current schema node is not a data tree node. - * @param schemaContext schema context - * @return generated type builder schemaNode - */ - public static GeneratedTypeBuilder addDefaultInterfaceDefinition(final String basePackageName, final SchemaNode - schemaNode, @Nullable final Type childOf, final Module module, final Map genCtx, - final SchemaContext schemaContext, final boolean - verboseClassComments, final Map> genTypeBuilders, final TypeProvider typeProvider, final BindingNamespaceType - namespaceType) { - - GeneratedTypeBuilder it = addRawInterfaceDefinition(basePackageName, schemaNode, schemaContext, "", "", - verboseClassComments, genTypeBuilders, namespaceType, genCtx.get(module)); - if (BindingNamespaceType.isData(namespaceType)) { - if (childOf == null) { - it.addImplementsType(BindingTypes.TREE_NODE); - } else { - if (!(schemaNode instanceof ListSchemaNode) - || ((ListSchemaNode) schemaNode).getKeyDefinition().isEmpty()) { - it.addImplementsType(parameterizedTypeFor(BindingTypes.TREE_CHILD_NODE, childOf, - parameterizedTypeFor(BindingTypes.ITEM, it))); - } - } - - if (!(schemaNode instanceof CaseSchemaNode)) { - it.addImplementsType(parameterizedTypeFor(BindingTypes.INSTANTIABLE, it)); - } - - it.addImplementsType(BindingTypes.augmentable(it)); - } - - if (schemaNode instanceof DataNodeContainer) { - groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings(), genCtx, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider); - it = addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it, genCtx); - } - - return it; - } - - static GeneratedTypeBuilder resolveNotification(final GeneratedTypeBuilder listenerInterface, final String - parentName, final String basePackageName, final NotificationDefinition notification, final Module module, - final SchemaContext schemaContext, final boolean - verboseClassComments, final Map> - genTypeBuilders, final TypeProvider typeProvider, final - Map genCtx) { - final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(basePackageName, notification, - null, module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, - BindingNamespaceType.Notification); - annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface); - notificationInterface.addImplementsType(NOTIFICATION); - genCtx.get(module).addChildNodeType(notification, notificationInterface); - - // Notification object - resolveDataSchemaNodes(module, basePackageName, notificationInterface, - notificationInterface, notification.getChildNodes(), genCtx, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider, BindingNamespaceType.Notification); - - //in case of tied notification, incorporate parent's localName - final StringBuilder sb = new StringBuilder("on_"); - if (parentName != null) { - sb.append(parentName).append('_'); - } - sb.append(notificationInterface.getName()); - - listenerInterface.addMethod(JavaIdentifierNormalizer.normalizeSpecificIdentifier(sb.toString(), - JavaIdentifier.METHOD)) - .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification") - .setComment(encodeAngleBrackets(notification.getDescription().orElse(null))).setReturnType(Types.VOID); - return listenerInterface; - } - - /** - * Returns reference to generated type builder for specified - * schemaNode with packageName. - * - *

- * Firstly the generated type builder is searched in - * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't - * found it is created and added to genTypeBuilders. - * - * @param basePackageName string contains the module package name - * @param schemaNode schema node which provide data about the schema node name - * @param schemaContext schema context - * @param prefix return type name prefix - * @return generated type builder for schemaNode - * @throws IllegalArgumentException

    - *
  • if schemaNode is null
  • - *
  • if packageName is null
  • - *
  • if QName of schema node is null
  • - *
  • if schemaNode name is null
  • - *
- */ - static GeneratedTypeBuilder addRawInterfaceDefinition(final String basePackageName, final SchemaNode schemaNode, - final SchemaContext schemaContext, final String prefix, - final String suffix, - final boolean verboseClassComments, final Map> genTypeBuilders, - final BindingNamespaceType namespaceType, final - ModuleContext context) { - - Preconditions.checkArgument(schemaNode != null, "Data Schema Node cannot be NULL."); - Preconditions.checkArgument(basePackageName != null, "Base package Name for Generated Type cannot be NULL."); - String schemaNodeName = schemaNode.getQName().getLocalName(); - Preconditions.checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL."); - - if (prefix != null && !prefix.isEmpty()) { - // underscore used as separator for distinction of class name parts - schemaNodeName = new StringBuilder(prefix).append('_').append(schemaNodeName).toString(); - } - - if (suffix != null && !suffix.isEmpty()) { - // underscore used as separator for distinction of class name parts - schemaNodeName = new StringBuilder(schemaNodeName).append('_').append(suffix).toString(); - } - - final String packageName = packageNameForGeneratedType(basePackageName, schemaNode.getPath(), namespaceType); - final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, schemaNodeName, context); - final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode); - qNameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName()); - if (verboseClassComments) { - YangSourceDefinition.of(module, schemaNode).ifPresent(newType::setYangSourceDefinition); - TypeComments.description(schemaNode).ifPresent(newType::addComment); - schemaNode.getDescription().ifPresent(newType::setDescription); - schemaNode.getReference().ifPresent(newType::setReference); - } - newType.setSchemaPath((List) schemaNode.getPath().getPathFromRoot()); - newType.setModuleName(module.getName()); - newType.setBasePackageName(BindingMapping.getRootPackageName(module)); - newType.setWithBuilder(AuxiliaryGenUtils.hasBuilderClass(schemaNode, namespaceType)); - newType.setBindingNamespaceType(namespaceType); - - if (!genTypeBuilders.containsKey(packageName)) { - final Map builders = new HashMap<>(); - builders.put(newType.getName(), newType); - genTypeBuilders.put(packageName, builders); - } else { - final Map builders = genTypeBuilders.get(packageName); - if (!builders.containsKey(newType.getName())) { - builders.put(newType.getName(), newType); - } - } - return newType; - - } - - private static void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node, - final GeneratedTypeBuilder typeBuilder, final - GeneratedTypeBuilder childOf, final Module module, - final Map genCtx, final SchemaContext - schemaContext, final boolean verboseClassComments, - final Map> - genTypeBuilders, final TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - - if (node != null && typeBuilder != null) { - if (node instanceof ContainerSchemaNode) { - containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (node instanceof LeafListSchemaNode) { - resolveLeafListSchemaNode(schemaContext, typeBuilder, (LeafListSchemaNode) node, module, - typeProvider, genCtx, verboseClassComments); - } else if (node instanceof LeafSchemaNode) { - resolveLeafSchemaNodeAsMethod("", schemaContext, typeBuilder, genCtx, (LeafSchemaNode) node, module, - typeProvider, verboseClassComments); - } else if (node instanceof ListSchemaNode) { - listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node, schemaContext, - verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (node instanceof ChoiceSchemaNode) { - choiceToGenType(module, schemaContext, verboseClassComments, basePackageName, typeBuilder, childOf, - (ChoiceSchemaNode) node, genTypeBuilders, genCtx, typeProvider, namespaceType); - } else if (node instanceof AnyXmlSchemaNode || node instanceof AnyDataSchemaNode) { - resolveAnyNodeAsMethod(schemaContext, typeBuilder, genCtx, node, module, typeProvider); - } - } - } - - /** - * Converts choiceNode to the list of generated types for - * choice and its cases. - * - *

- * The package names for choice and for its cases are created as - * concatenation of the module package (basePackageName) and - * names of all parents node. - * - * @param module current module - * @param basePackageName string with the module package name - * @param parent parent type - * @param choiceNode choice node which is mapped to generated type. Also child - * nodes - cases are mapped to generated types. - * @throws IllegalArgumentException

    - *
  • if basePackageName is null
  • - *
  • if choiceNode is null
  • - *
- */ - private static void choiceToGenType(final Module module, final SchemaContext schemaContext, final boolean - verboseClasssComments, final String basePackageName, final GeneratedTypeBuilder parent, - final GeneratedTypeBuilder childOf, final ChoiceSchemaNode choiceNode, - final Map> genTypeBuilders, - final Map genCtx, final TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - checkArgument(basePackageName != null, "Base Package Name cannot be NULL."); - checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL."); - - final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(basePackageName, choiceNode, - schemaContext, "", "", verboseClasssComments, genTypeBuilders, namespaceType, genCtx.get(module)); - constructGetter(parent, choiceNode.getQName().getLocalName(), - choiceNode.getDescription().orElse(null), choiceTypeBuilder, choiceNode.getStatus()); - choiceTypeBuilder.setParentTypeForBuilder(childOf); - if (BindingNamespaceType.isData(namespaceType)) { - choiceTypeBuilder.addImplementsType(parameterizedTypeFor(BindingTypes.INSTANTIABLE, choiceTypeBuilder)); - } - annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder); - genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder); - generateTypesFromChoiceCases(module, schemaContext, genCtx, basePackageName, choiceTypeBuilder.toInstance(), - choiceNode, verboseClasssComments, typeProvider, genTypeBuilders, namespaceType); - } - - private static void containerToGenType(final Module module, final String basePackageName, - final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, - final ContainerSchemaNode node, - final SchemaContext schemaContext, final boolean verboseClassComments, - final Map genCtx, - final Map> genTypeBuilders, - final TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - - final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - if (genType != null) { - StringBuilder getterName = new StringBuilder(node.getQName().getLocalName()); - constructGetter(parent, getterName.toString(), node.getDescription().orElse(null), genType, node - .getStatus()); - resolveDataSchemaNodes(module, basePackageName, genType, genType, node.getChildNodes(), genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - processUsesImplements(node, module, schemaContext, genCtx, namespaceType); - } - } - - private static void listToGenType(final Module module, final String basePackageName, final GeneratedTypeBuilder - parent, final GeneratedTypeBuilder childOf, final ListSchemaNode node, final SchemaContext schemaContext, - final boolean verboseClassComments, final Map genCtx, - final Map> genTypeBuilders, final - TypeProvider typeProvider, - final BindingNamespaceType namespaceType) { - - final GeneratedTypeBuilder genType = processDataSchemaNode(module, basePackageName, childOf, node, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - if (genType != null) { - final String nodeName = node.getQName().getLocalName(); - - Type getterReturnType = Types.listTypeFor(genType); - if (BindingNamespaceType.isGrouping(namespaceType)) { - getterReturnType = Types.listTypeFor(wildcardTypeFor(genType.getPackageName(), genType.getName(), - true, true, null)); - } - constructGetter(parent, nodeName, node.getDescription().orElse(null), getterReturnType, node.getStatus()); - - final List listKeys = node.getKeyDefinition(); - final String packageName = new StringBuilder(packageNameForGeneratedType(basePackageName, node.getPath(), - BindingNamespaceType.Key)).append('.').append(nodeName).toString(); - //FIXME: Is it neccessary to generate interface of key and implemented by class? - if (BindingNamespaceType.isGrouping(namespaceType)) { - final GeneratedTypeBuilder genTypeBuilder = resolveListKeyTypeBuilder(packageName, node, - genCtx.get(module)); - for (final DataSchemaNode schemaNode : node.getChildNodes()) { - if (resolveDataSchemaNodesCheck(module, schemaContext, schemaNode)) { - addSchemaNodeToListTypeBuilders(nodeName, basePackageName, schemaNode, genType, - genTypeBuilder, listKeys, - module, typeProvider, schemaContext, genCtx, genTypeBuilders, verboseClassComments, - namespaceType); - } - } - if (genTypeBuilder != null) { - typeBuildersToGenTypes(module, genType, genTypeBuilder.toInstance(), genCtx, namespaceType); - genCtx.get(module).addKeyType(node.getPath(), genTypeBuilder); - } - processUsesImplements(node, module, schemaContext, genCtx, namespaceType); - } else { - final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(packageName, node, genCtx.get(module)); - if (genTOBuilder != null) { - final Type identifiableMarker = Types.parameterizedTypeFor(IDENTIFIABLE, genTOBuilder); - genTOBuilder.addImplementsType(IDENTIFIER); - genType.addImplementsType(identifiableMarker); - if (BindingNamespaceType.isData(namespaceType)) { - genType.addImplementsType(parameterizedTypeFor(BindingTypes.TREE_CHILD_NODE, childOf, - parameterizedTypeFor(BindingTypes.IDENTIFIABLE_ITEM, genType, genTOBuilder))); - } - } - - for (final DataSchemaNode schemaNode : node.getChildNodes()) { - if (resolveDataSchemaNodesCheck(module, schemaContext, schemaNode)) { - addSchemaNodeToListBuilders(nodeName, basePackageName, schemaNode, genType, genTOBuilder, - listKeys, - module, typeProvider, schemaContext, genCtx, genTypeBuilders, verboseClassComments, - namespaceType); - } - } - processUsesImplements(node, module, schemaContext, genCtx, namespaceType); - - // serialVersionUID - if (genTOBuilder != null) { - final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID"); - prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder))); - genTOBuilder.setSUID(prop); - typeBuildersToGenTypes(module, genType, genTOBuilder.toInstance(), genCtx, namespaceType); - genCtx.get(module).addGeneratedTOBuilder(node.getPath(), genTOBuilder); - } - } - } - } - - private static void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder, - final Type keyType, final Map genCtx, - final BindingNamespaceType namespaceType) { - checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL."); - if (keyType != null) { - Type returnKeyType = keyType; - if (BindingNamespaceType.isGrouping(namespaceType)) { - returnKeyType = wildcardTypeFor(keyType.getPackageName(), keyType.getName(), - true, true, null); - } - constructGetter(typeBuilder, "identifier", "Returns Primary Key of Yang List Type", returnKeyType, Status - .CURRENT); - - } - } - - private static void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName, - final List patternConstraints) { - if (!patternConstraints.isEmpty()) { - final StringBuilder field = new StringBuilder(); - field.append(BindingMapping.PATTERN_CONSTANT_NAME).append("_") - .append(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafName, JavaIdentifier.METHOD)); - typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(), - resolveRegExpressions(patternConstraints)); - } - } - - /** - * Converts leaf to the getter method which is added to - * typeBuilder. - * - * @param typeBuilder generated type builder to which is added getter method as - * leaf mapping - * @param leaf leaf schema node which is mapped as getter method which is - * added to typeBuilder - * @param module Module in which type was defined - * @return boolean value - *
    - *
  • false - if leaf or typeBuilder are - * null
  • - *
  • true - in other cases
  • - *
- */ - private static Type resolveLeafSchemaNodeAsMethod(final String nodeName, final SchemaContext schemaContext, - final GeneratedTypeBuilder typeBuilder, final Map genCtx, final LeafSchemaNode leaf, - final Module module, final TypeProvider typeProvider, final - boolean verboseClassComments) { - if (leaf == null || typeBuilder == null) { - return null; - } - - final String leafName = leaf.getQName().getLocalName(); - if (leafName == null) { - return null; - } - - final Module parentModule = findParentModule(schemaContext, leaf); - Type returnType = null; - - final TypeDefinition typeDef = leaf.getType(); - - if (leaf.isAddedByUses()) { - Preconditions.checkState(leaf instanceof DerivableSchemaNode); - if (isInnerType(leaf, typeDef)) { - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf, - restrictions, genCtx.get(module)); - } else { - if (typeDef.getBaseType() == null && (typeDef instanceof EnumTypeDefinition - || typeDef instanceof UnionTypeDefinition || typeDef instanceof BitsTypeDefinition)) { - LeafSchemaNode originalLeaf = (LeafSchemaNode) ((DerivableSchemaNode) leaf).getOriginal() - .orElse(null); - requireNonNull(originalLeaf); - returnType = genCtx.get(findParentModule(schemaContext, originalLeaf)).getInnerType(typeDef - .getPath()); - } else { - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, - genCtx.get(module)); - } - } - } else if (isInnerType(leaf, typeDef)) { - if (typeDef instanceof EnumTypeDefinition) { - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, genCtx.get(module)); - final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef; - final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), - genCtx, typeBuilder, module); - if (enumBuilder != null) { - returnType = enumBuilder.toInstance(typeBuilder); - } - ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType); - } else if (typeDef instanceof UnionTypeDefinition) { - final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule, - typeProvider, schemaContext, genCtx.get(module), genCtx); - if (genTOBuilder != null) { - //TODO: https://bugs.opendaylight.org/show_bug.cgi?id=2289 - returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule, - typeProvider, verboseClassComments); - } - } else if (typeDef instanceof BitsTypeDefinition) { - final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule, - typeProvider, schemaContext, genCtx.get(module), genCtx); - if (genTOBuilder != null) { - returnType = genTOBuilder.toInstance(); - } - } else { - // It is constrained version of already declared type (inner declared type exists, - // onlyfor special cases (Enum, Union, Bits), which were already checked. - // In order to get proper class we need to look up closest derived type - // and apply restrictions from leaf type - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf, - restrictions, genCtx.get(module)); - addPatternConstant(typeBuilder, leafName, restrictions.getPatternConstraints()); - } - } else { - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, genCtx.get(module)); - addPatternConstant(typeBuilder, leafName, restrictions.getPatternConstraints()); - } - - if (returnType == null) { - return null; - } - - if (typeDef instanceof EnumTypeDefinition) { - ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType); - } - - final String leafGetterName; - if ("key".equals(leafName.toLowerCase())) { - StringBuilder sb = new StringBuilder(leafName) - .append('_').append("RESERVED_WORD"); - leafGetterName = sb.toString(); - } else { - leafGetterName = leafName; - } - constructGetter(typeBuilder, leafGetterName, leaf.getDescription().orElse(""), returnType, leaf.getStatus()); - return returnType; - } - - /** - * Converts node leaf list schema node to getter method of - * typeBuilder. - * - * @param typeBuilder generated type builder to which is node added as - * getter method - * @param node leaf list schema node which is added to - * typeBuilder as getter method - * @param module module - * @param typeProvider type provider instance - * @param genCtx actual generated context - * @return boolean value - *
    - *
  • true - if node, typeBuilder, - * nodeName equal null or node is added by uses
  • - *
  • false - other cases
  • - *
- */ - private static boolean resolveLeafListSchemaNode(final SchemaContext schemaContext, final GeneratedTypeBuilder - typeBuilder, final LeafListSchemaNode node, final Module module, final TypeProvider typeProvider, - final Map genCtx, final boolean - verboseClassComments) { - if (node == null || typeBuilder == null) { - return false; - } - - final QName nodeName = node.getQName(); - - final TypeDefinition typeDef = node.getType(); - final Module parentModule = findParentModule(schemaContext, node); - - Type returnType = null; - if (typeDef.getBaseType() == null) { - if (typeDef instanceof EnumTypeDefinition) { - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, genCtx.get(module)); - final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef; - final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, - genCtx, typeBuilder, module); - returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName(), true, - null); - ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType); - } else if (typeDef instanceof UnionTypeDefinition) { - final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule, - typeProvider, schemaContext, genCtx.get(module), genCtx); - if (genTOBuilder != null) { - returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule, - typeProvider, verboseClassComments); - } - } else if (typeDef instanceof BitsTypeDefinition) { - final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule, - typeProvider, schemaContext, genCtx.get(module), genCtx); - returnType = genTOBuilder.toInstance(); - } else { - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, - genCtx.get(module)); - - addPatternConstant(typeBuilder, nodeName.getLocalName(), restrictions.getPatternConstraints()); - } - } else { - final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef); - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, genCtx.get(module)); - - addPatternConstant(typeBuilder, nodeName.getLocalName(), restrictions.getPatternConstraints()); - } - - final ParameterizedType listType = Types.listTypeFor(returnType); - constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription().orElse(null), listType, node - .getStatus()); - return true; - } - - /** - * Converts caseNodes set to list of corresponding generated - * types. - * - *

- * For every case which isn't added through augment or uses is - * created generated type builder. The package names for the builder is - * created as concatenation of the module package ( - * basePackageName) and names of all parents nodes of the - * concrete case. There is also relation "implements type" - * between every case builder and choice type - * - * @param module current module - * @param schemaContext current schema context - * @param genCtx actual generated context - * @param basePackageName string with the module package name - * @param refChoiceType type which represents superior case - * @param choiceNode choice case node which is mapped to generated type - * @param verboseClassComments Javadoc verbosity switch - * @throws IllegalArgumentException

    - *
  • if basePackageName equals null
  • - *
  • if refChoiceType equals null
  • - *
  • if caseNodes equals null
  • - *
- */ - private static void generateTypesFromChoiceCases(final Module module, final SchemaContext schemaContext, - final Map genCtx, final String - basePackageName, final GeneratedType refChoiceType, - final ChoiceSchemaNode choiceNode, final boolean - verboseClassComments, - final TypeProvider typeProvider, final Map> genTypeBuilders, - final BindingNamespaceType namespaceType) { - 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."); - - for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) { - if (caseNode != null && resolveDataSchemaNodesCheck(module, schemaContext, caseNode)) { - final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(basePackageName, caseNode, - null, module, genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider, namespaceType); - caseTypeBuilder.addImplementsType(refChoiceType); - caseTypeBuilder.setParentTypeForBuilder(refChoiceType.getParentTypeForBuilder()); - annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder); - genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder); - if (BindingNamespaceType.isData(namespaceType)) { - genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode); - } - - resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, - (GeneratedTypeBuilder) refChoiceType.getParentTypeForBuilder(), caseNode.getChildNodes(), - genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - processUsesImplements(caseNode, module, schemaContext, genCtx, namespaceType); - } - } - } - - private static Type resolveAnyNodeAsMethod(final SchemaContext schemaContext, final GeneratedTypeBuilder - typeBuilder, final Map genCtx, final DataSchemaNode node, final Module module, - final TypeProvider typeProvider) { - - final String anyName = node.getQName().getLocalName(); - if (anyName == null) { - return null; - } - - Type returnType = Types.DOCUMENT; - constructGetter(typeBuilder, anyName, node.getDescription().orElse(""), returnType, node.getStatus()); - return returnType; - } - - /** - * Adds schemaNode to typeBuilder as getter method - * or to genTOBuilder as property. - * - * @param nodeName string contains the name of list - * @param basePackageName string contains the module package name - * @param schemaNode data schema node which should be added as getter method to - * typeBuilder or as a property to - * genTOBuilder if is part of the list key - * @param typeBuilder generated type builder for the list schema node - * @param genTOBuilder generated TO builder for the list keys - * @param listKeys list of string which contains QNames of the list keys - * @param module current module - * @param typeProvider provider that defines contract for generated types - * @param schemaContext schema context - * @param genCtx map of generated entities in context of YANG modules - * @param genTypeBuilders map of generated type builders - * @param verboseClassComments generate verbose comments - * @throws IllegalArgumentException
    - *
  • if schemaNode equals null
  • - *
  • if typeBuilder equals null
  • - *
- */ - private static void addSchemaNodeToListBuilders(final String nodeName, final String basePackageName, - final DataSchemaNode schemaNode, final GeneratedTypeBuilder - typeBuilder, - final GeneratedTOBuilder genTOBuilder, final List - listKeys, final Module module, - final TypeProvider typeProvider, final SchemaContext - schemaContext, final Map genCtx, - final Map> - genTypeBuilders, final boolean verboseClassComments, - final BindingNamespaceType namespaceType) { - checkArgument(schemaNode != null, "Data Schema Node cannot be NULL."); - checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL."); - - if (schemaNode instanceof LeafSchemaNode) { - final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode; - final QName leafQName = leaf.getQName(); - - final Type type = resolveLeafSchemaNodeAsMethod(nodeName, schemaContext, typeBuilder, genCtx, leaf, module, - typeProvider, verboseClassComments); - if (listKeys.contains(leafQName)) { - if (type == null) { - resolveLeafSchemaNodeAsProperty(nodeName, schemaContext, typeProvider, genCtx, genTOBuilder, - leaf, true, - module); - } else { - AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty(nodeName, genTOBuilder, leaf, type, true); - } - } - } else { - if (schemaNode instanceof LeafListSchemaNode) { - resolveLeafListSchemaNode(schemaContext, typeBuilder, (LeafListSchemaNode) schemaNode, module, - typeProvider, genCtx, verboseClassComments); - } else if (schemaNode instanceof ContainerSchemaNode) { - containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (schemaNode instanceof ListSchemaNode) { - listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (schemaNode instanceof ChoiceSchemaNode) { - choiceToGenType(module, schemaContext, verboseClassComments, basePackageName, typeBuilder, typeBuilder, - (ChoiceSchemaNode) schemaNode, genTypeBuilders, genCtx, typeProvider, namespaceType); - } - } - } - - private static void addSchemaNodeToListTypeBuilders(final String nodeName, final String basePackageName, - final DataSchemaNode schemaNode, final GeneratedTypeBuilder - typeBuilder, - final GeneratedTypeBuilder genTypeBuilder, final List - listKeys, final Module module, - final TypeProvider typeProvider, final SchemaContext - schemaContext, final Map genCtx, - final Map> - genTypeBuilders, final boolean verboseClassComments, - final BindingNamespaceType namespaceType) { - checkArgument(schemaNode != null, "Data Schema Node cannot be NULL."); - checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL."); - - if (schemaNode instanceof LeafSchemaNode) { - final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode; - final QName leafQName = leaf.getQName(); - final Type type = resolveLeafSchemaNodeAsMethod(nodeName, schemaContext, typeBuilder, genCtx, leaf, module, - typeProvider, verboseClassComments); - if (listKeys.contains(leafQName)) { - resolveLeafSchemaNodeAsMethod(nodeName, schemaContext, genTypeBuilder, genCtx, leaf, module, - typeProvider, verboseClassComments); - } - } else { - if (schemaNode instanceof LeafListSchemaNode) { - resolveLeafListSchemaNode(schemaContext, typeBuilder, (LeafListSchemaNode) schemaNode, module, - typeProvider, genCtx, verboseClassComments); - } else if (schemaNode instanceof ContainerSchemaNode) { - containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (schemaNode instanceof ListSchemaNode) { - listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode, - schemaContext, verboseClassComments, genCtx, genTypeBuilders, typeProvider, namespaceType); - } else if (schemaNode instanceof ChoiceSchemaNode) { - choiceToGenType(module, schemaContext, verboseClassComments, basePackageName, typeBuilder, typeBuilder, - (ChoiceSchemaNode) schemaNode, genTypeBuilders, genCtx, typeProvider, namespaceType); - } - } - } - - private static boolean resolveLeafSchemaNodeAsProperty(final String nodeName, final SchemaContext schemaContext, - final TypeProvider - typeProvider, final Map - genCtx, final GeneratedTOBuilder - toBuilder, final LeafSchemaNode leaf, final - boolean isReadOnly, final Module module) { - - if (leaf != null && toBuilder != null) { - Type returnType; - 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.findModule(qname.getModule()).get(); - final ModuleContext mc = genCtx.get(unionModule); - returnType = mc.getTypedefs().get(typeDef.getPath()); - } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) { - // Annonymous enumeration (already generated, since it is inherited via uses). - LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf); - QName qname = originalLeaf.getQName(); - final Module enumModule = schemaContext.findModule(qname.getModule()).orElse(null); - returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath()); - } else { - returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, genCtx.get(module)); - } - return AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty(nodeName, toBuilder, leaf, returnType, isReadOnly); - } - return false; - } - - private static TypeDefinition getBaseOrDeclaredType(final TypeDefinition typeDef) { - final TypeDefinition baseType = typeDef.getBaseType(); - return baseType != null && baseType.getBaseType() != null ? baseType : typeDef; - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - private static GeneratedTypeBuilder processDataSchemaNode(final Module module, final String basePackageName, - final GeneratedTypeBuilder childOf, final - DataSchemaNode node, final SchemaContext - schemaContext, - final boolean verboseClassComments, final Map genCtx, final Map> genTypeBuilders, final TypeProvider typeProvider, final BindingNamespaceType - namespaceType) { - - final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(basePackageName, node, childOf, module, - genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - annotateDeprecatedIfNecessary(node.getStatus(), genType); - genType.setModuleName(module.getName()); - if (verboseClassComments) { - YangSourceDefinition.of(module, node).ifPresent(genType::setYangSourceDefinition); - TypeComments.description(node).ifPresent(genType::addComment); - node.getDescription().ifPresent(genType::setDescription); - node.getReference().ifPresent(genType::setReference); - } - genType.setSchemaPath((List) node.getPath().getPathFromRoot()); - if (BindingNamespaceType.isData(namespaceType)) { - genType.setParentTypeForBuilder(childOf); - } - - if (node instanceof DataNodeContainer) { - genCtx.get(module).addChildNodeType(node, genType); - } - return genType; - } - - /** - * Converts all groupings of the module to the list of - * Type objects. Firstly are groupings sorted according mutual - * dependencies. At least dependent (independent) groupings are in the list - * saved at first positions. For every grouping the record is added to map - * {@link ModuleContext#groupings allGroupings} - * - * @param module current module - * @param groupings collection of groupings from which types will be generated - * @param typeProvider provider that defines contract for generated types - * @param schemaContext schema context - * @param genCtx map of generated entities in context of YANG modules - * @param genTypeBuilders map of generated type builders - * @param verboseClassComments generate verbose comments - */ - static Map groupingsToGenTypes(final Module module, final Collection - groupings, Map genCtx, final SchemaContext schemaContext, final boolean - verboseClassComments, final Map> genTypeBuilders, final TypeProvider typeProvider) { - final String basePackageName = BindingMapping.getRootPackageName(module); - final List groupingsSortedByDependencies = new GroupingDefinitionDependencySort() - .sort(groupings); - for (final GroupingDefinition grouping : groupingsSortedByDependencies) { - genCtx = groupingToGenType(basePackageName, grouping, module, genCtx, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider); - } - return genCtx; - } - - /** - * Converts individual grouping to GeneratedType. Firstly generated type - * builder is created and every child node of grouping is resolved to the - * method. - * - * @param basePackageName string contains the module package name - * @param grouping GroupingDefinition which contains data about grouping - * @param module current module - * @param typeProvider provider that defines contract for generated types - * @param schemaContext schema context - * @param genCtx map of generated entities in context of YANG modules - * @param genTypeBuilders map of generated type builders - * @param verboseClassComments generate verbose comments - * @return GeneratedType which is generated from grouping (object of type - * GroupingDefinition) - */ - private static Map groupingToGenType(final String basePackageName, - final GroupingDefinition grouping, final Module module, Map genCtx, - final SchemaContext schemaContext, final boolean verboseClassComments, - final Map> genTypeBuilders, final TypeProvider typeProvider) { - final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(basePackageName, grouping, null, module, - genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, BindingNamespaceType.Grouping); - annotateDeprecatedIfNecessary(grouping.getStatus(), genType); - genCtx.get(module).addGroupingType(grouping, genType); - resolveDataSchemaNodes(module, basePackageName, genType, genType, grouping.getChildNodes(), genCtx, - schemaContext, verboseClassComments, genTypeBuilders, typeProvider, BindingNamespaceType.Grouping); - genCtx = processUsesImplements(grouping, module, schemaContext, genCtx, BindingNamespaceType.Grouping); - return genCtx; - } - - /** - * //TODO: add information about multiple base identities in YANG 1.1 - * Converts the identity object to GeneratedType. Firstly it is - * created transport object builder. If identity contains base identity then - * reference to base identity is added to superior identity as its extend. - * If identity doesn't contain base identity then only reference to abstract - * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode - * BaseIdentity} is added - * - * @param module current module - * @param basePackageName string contains the module package name - * @param identity IdentitySchemaNode which contains data about identity - * @param schemaContext SchemaContext which is used to get package and name - * information about base of identity - * @param genCtx generated context - * @return returns generated context - */ - static Map identityToGenType(final Module module, final String basePackageName, - final IdentitySchemaNode identity, final SchemaContext - schemaContext, final Map genCtx, - final boolean verboseClassComments) { - - resolveIdentitySchemaNode(basePackageName, schemaContext, identity, module, verboseClassComments, genCtx); - return genCtx; - } - - private static GeneratedTypeBuilder resolveIdentitySchemaNode(final String basePackageName, final SchemaContext - schemaContext, - final IdentitySchemaNode identity, final Module - module, final boolean verboseClassComments, - final Map genCtx) { - requireNonNull(identity, "Identity can not be null!"); - - //check first if identity has been resolved as base identity of some other one - GeneratedTypeBuilder newType = findIdentityByQname(identity.getQName(), genCtx); - if (newType == null) { - final Module parentModule = SchemaContextUtil.findParentModule(schemaContext, identity); - Preconditions.checkState(module.equals(parentModule), - "If the type is null ,it must be in the same module, otherwise it must has been" - + "resolved by an imported module."); - - final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity - .getPath(), - BindingNamespaceType.Identity); - newType = new GeneratedTypeBuilderImpl(packageName, identity.getQName().getLocalName(), true, false, - genCtx.get(module)); - - final Set baseIdentities = identity.getBaseIdentities(); - if (baseIdentities.size() == 0) { - //no base - abstract - final GeneratedTypeBuilderImpl genType = new GeneratedTypeBuilderImpl(BaseIdentity.class.getPackage() - .getName(), - BaseIdentity.class.getSimpleName(), genCtx.get(module)); - newType.addImplementsType(genType.toInstance()); - } else { - //multiple bases - inheritance - for (IdentitySchemaNode baseIdentity : baseIdentities) { - GeneratedTypeBuilder baseType = resolveIdentitySchemaNode(basePackageName, schemaContext, - baseIdentity, module, verboseClassComments, genCtx); - newType.addImplementsType(baseType.toInstance()); - } - } - - if (verboseClassComments) { - YangSourceDefinition.of(module).ifPresent(newType::setYangSourceDefinition); - TypeComments.description(module).ifPresent(newType::addComment); - module.getDescription().ifPresent(newType::setDescription); - module.getReference().ifPresent(newType::setReference); - } - newType.setSchemaPath((List) identity.getPath().getPathFromRoot()); - - qNameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, identity.getQName()); - - genCtx.get(module).addIdentityType(identity.getQName(), newType); - } - return newType; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategy.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategy.java deleted file mode 100644 index 5d81859126..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategy.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.util.ClassLoaderUtils; - -@Beta -public abstract class GeneratedClassLoadingStrategy implements ClassLoadingStrategy { - - private static final GeneratedClassLoadingStrategy TCCL_STRATEGY = new TCCLClassLoadingStrategy(); - - @Override - public Class loadClass(final Type type) throws ClassNotFoundException { - return loadClass(type.getFullyQualifiedName()); - } - - @Override - public abstract Class loadClass(String fqcn) throws ClassNotFoundException; - - public static ClassLoadingStrategy getTCCLClassLoadingStrategy() { - return TCCL_STRATEGY; - } - - private static final class TCCLClassLoadingStrategy extends GeneratedClassLoadingStrategy { - @Override - public Class loadClass(final String fullyQualifiedName) throws ClassNotFoundException { - return ClassLoaderUtils.loadClassWithTCCL(fullyQualifiedName); - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/ModuleToGenType.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/ModuleToGenType.java deleted file mode 100755 index 3515c472de..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/ModuleToGenType.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.groupingsToGenTypes; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.moduleTypeBuilder; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.processUsesImplements; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.resolveNotification; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.NOTIFICATION_LISTENER; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.TypeComments; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.NotificationDefinition; -import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.util.DataNodeIterator; - -@Beta -final class ModuleToGenType { - - private ModuleToGenType() { - throw new UnsupportedOperationException("Utility class"); - } - - static Map generate(final Module module, final Map> - genTypeBuilders, final SchemaContext schemaContext, final TypeProvider typeProvider, Map genCtx, final boolean verboseClassComments) { - - genCtx.put(module, new ModuleContext()); - genCtx = allTypeDefinitionsToGenTypes(module, genCtx, typeProvider); - genCtx = groupingsToGenTypes(module, module.getGroupings(), genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider); - genCtx = allIdentitiesToGenTypes(module, schemaContext, genCtx, verboseClassComments, genTypeBuilders, - typeProvider); - - if (!module.getChildNodes().isEmpty()) { - final GeneratedTypeBuilder moduleType = GenHelperUtil.moduleToDataType(module, genCtx, - verboseClassComments); - genCtx.get(module).addModuleNode(moduleType); - final String basePackageName = BindingMapping.getRootPackageName(module); - GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, moduleType, moduleType, module - .getChildNodes(), genCtx, schemaContext, verboseClassComments, genTypeBuilders, - typeProvider, - BindingNamespaceType.Data); - processUsesImplements(module, module, schemaContext, genCtx, BindingNamespaceType.Data); - } - - genCtx = notificationsToGenType(module, genCtx, schemaContext, genTypeBuilders, verboseClassComments, - typeProvider); - - //after potential parent data schema nodes - genCtx = actionsAndRPCMethodsToGenType(module, genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider); - - return genCtx; - } - - /** - * Converts all extended type definitions of module to the list of - * Type objects. - * - * @param module module from which is obtained set of type definitions - * @throws IllegalArgumentException
    - *
  • if module is null
  • - *
  • if name of module is null
  • - *
- * @throws IllegalStateException if set of type definitions from module is null - */ - private static Map allTypeDefinitionsToGenTypes(final Module module, final Map genCtx, - final TypeProvider typeProvider) { - Preconditions.checkArgument(module != null, "Module reference cannot be NULL."); - Preconditions.checkArgument(module.getName() != null, "Module name cannot be NULL."); - final DataNodeIterator it = new DataNodeIterator(module); - final List> typeDefinitions = it.allTypedefs(); - Preconditions.checkState(typeDefinitions != null, "Type Definitions for module «module.name» cannot be NULL."); - - typeDefinitions.stream().filter(Objects::nonNull).forEach(typedef -> { - final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef, - typedef); - if (type != null) { - final ModuleContext ctx = genCtx.get(module); - ctx.addTypedefType(typedef.getPath(), type); - ctx.addTypeToSchema(type, typedef); - } - }); - return genCtx; - } - - private static Map actionsAndRPCMethodsToGenType(final Module module, Map genCtx, final SchemaContext schemaContext, final boolean verboseClassComments, - final Map> - genTypeBuilders, final - TypeProvider typeProvider) { - - genCtx = RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider); - genCtx = RpcActionGenHelper.actionMethodsToGenType(module, genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider); - - return genCtx; - } - - /** - * Converts all identities of the module to the list of - * Type objects. - * - * @param module module from which is obtained set of all identity objects to - * iterate over them - * @param schemaContext schema context only used as input parameter for method - * {@link GenHelperUtil#identityToGenType(Module, String, IdentitySchemaNode, SchemaContext,Map, boolean)} - * @param genCtx generated context - * @return returns generated context - */ - private static Map allIdentitiesToGenTypes(final Module module, - final SchemaContext schemaContext, Map genCtx, boolean verboseClassComments, - final Map> genTypeBuilders, - final TypeProvider typeProvider) { - - final Set schemaIdentities = module.getIdentities(); - final String basePackageName = BindingMapping.getRootPackageName(module); - - if (schemaIdentities != null && !schemaIdentities.isEmpty()) { - for (final IdentitySchemaNode identity : schemaIdentities) { - GenHelperUtil.identityToGenType(module, basePackageName, identity, schemaContext, genCtx, - verboseClassComments); - } - } - - return genCtx; - } - - /** - * Converts all notifications of the module to the list of - * Type objects. In addition are to this list added containers - * and lists which are part of this notification. - * - * @param module module from which is obtained set of all notification objects - * to iterate over them - * @throws IllegalArgumentException
    - *
  • if the module equals null
  • - *
  • if the name of module equals null
  • - *
- * @throws IllegalStateException if set of notifications from module is null - */ - private static Map notificationsToGenType(final Module module, final Map genCtx, - final SchemaContext schemaContext, final - Map> - genTypeBuilders, - final boolean verboseClassComments, final - TypeProvider typeProvider) { - checkArgument(module != null, "Module reference cannot be NULL."); - checkArgument(module.getName() != null, "Module name cannot be NULL."); - final Set notifications = module.getNotifications(); - if (notifications.isEmpty()) { - return genCtx; - } - - final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(module, "Listener", verboseClassComments, - genCtx.get(module)); - listenerInterface.addImplementsType(NOTIFICATION_LISTENER); - final String basePackageName = BindingMapping.getRootPackageName(module); - - for (final NotificationDefinition notification : notifications) { - if (notification != null) { - resolveNotification(listenerInterface, null, basePackageName, notification, module, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider, genCtx); - processUsesImplements(notification, module, schemaContext, genCtx, BindingNamespaceType.Notification); - } - } - - //YANG 1.1 allows notifications be tied to containers and lists - final Collection potentials = module.getChildNodes(); - Set tiedNotifications = null; - - for (final DataSchemaNode potential : potentials) { - if (potential instanceof NotificationNodeContainer) { - tiedNotifications = ((NotificationNodeContainer) potential) - .getNotifications(); - for (final NotificationDefinition tiedNotification : tiedNotifications) { - if (tiedNotification != null) { - resolveNotification(listenerInterface, potential.getQName().getLocalName(), basePackageName, - tiedNotification, module, schemaContext, verboseClassComments, genTypeBuilders, - typeProvider, genCtx); - processUsesImplements(tiedNotification, module, schemaContext, genCtx, BindingNamespaceType - .Notification); - } - } - } - } - - if (verboseClassComments) { - if (tiedNotifications != null) { - YangSourceDefinition.of(module, - ImmutableSet.builder().addAll(notifications).addAll(tiedNotifications) - .build()).ifPresent(listenerInterface::setYangSourceDefinition); - } else { - YangSourceDefinition.of(module, notifications).ifPresent(listenerInterface::setYangSourceDefinition); - } - listenerInterface.addComment(TypeComments.javadoc( - "Interface for receiving the following YANG notifications defined in module " + module.getName() - + "").get()); - } - - genCtx.get(module).addTopLevelNodeType(listenerInterface); - - return genCtx; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelper.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelper.java deleted file mode 100755 index a1446fd298..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelper.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static com.google.common.base.Preconditions.checkState; -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.annotateDeprecatedIfNecessary; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.AuxiliaryGenUtils.checkModuleAndModuleName; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.addImplementedInterfaceFromUses; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.addRawInterfaceDefinition; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.moduleTypeBuilder; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.processUsesImplements; -import static org.opendaylight.mdsal.binding.javav2.generator.impl.GenHelperUtil.resolveDataSchemaNodesCheck; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.ACTION; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INPUT; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INSTANCE_IDENTIFIER; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.INSTANTIABLE; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.KEYED_INSTANCE_IDENTIFIER; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.LIST_ACTION; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.OUTPUT; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.RPC; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.RPC_CALLBACK; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.TREE_NODE; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes.augmentable; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.CLASS; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.VOID; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.parameterizedTypeFor; - -import com.google.common.annotations.Beta; -import com.google.common.annotations.VisibleForTesting; -import java.util.Collection; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes; -import org.opendaylight.mdsal.binding.javav2.generator.util.TypeComments; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ActionDefinition; -import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer; -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.OperationDefinition; -import org.opendaylight.yangtools.yang.model.api.RpcDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; - -/** - * Util class used for generation of types for RPCs, routedRPCs and Actions (YANG 1.1 only) - * in Binding spec. v2. In case of routed RPC detected in input YANG, RPC is turned to Action. - */ -@Beta -final class RpcActionGenHelper { - @VisibleForTesting - static final QName CONTEXT_REFERENCE = - QName.create("urn:opendaylight:yang:extension:yang-ext", "2013-07-09", "context-reference").intern(); - - private RpcActionGenHelper() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Let's find out what context we are talking about - * 1. routed RPC - * 2. global RPC - * - *

- * In 1st case, we need Binding Generator behave like YANG 1.1 Action - * - * @param schemaNode RPC input node - * @return presence optional - */ - @VisibleForTesting - static Optional getRoutingContext(final DataSchemaNode schemaNode) { - for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) { - if (CONTEXT_REFERENCE.equals(extension.getNodeType())) { - return Optional.ofNullable(extension.getQName()); - } - } - return Optional.empty(); - } - - private static void resolveActions(final DataNodeContainer parent, final Module module, - final SchemaContext schemaContext, final boolean verboseClassComments, - final Map> genTypeBuilders, final - Map genCtx, - final TypeProvider typeProvider, final BindingNamespaceType namespaceType) { - requireNonNull(parent, "Parent should not be NULL."); - final Collection potentials = parent.getChildNodes(); - for (DataSchemaNode potential : potentials) { - if (resolveDataSchemaNodesCheck(module, schemaContext, potential)) { - BindingNamespaceType namespaceType1 = namespaceType; - if (BindingNamespaceType.isData(namespaceType)) { - if (potential instanceof GroupingDefinition) { - namespaceType1 = BindingNamespaceType.Grouping; - } - } - - if (potential instanceof ActionNodeContainer) { - final Set actions = ((ActionNodeContainer) potential).getActions(); - for (ActionDefinition action : actions) { - final GeneratedTypeBuilder typeBuilder = resolveOperation(potential, action, module, - schemaContext, verboseClassComments, genTypeBuilders, genCtx, typeProvider, true, - namespaceType1); - genCtx.get(module).addTopLevelNodeType(typeBuilder); - genCtx.get(module).addTypeToSchema(typeBuilder, action); - } - } - - if (potential instanceof DataNodeContainer) { - resolveActions((DataNodeContainer) potential, module, schemaContext, verboseClassComments, - genTypeBuilders, genCtx, typeProvider, namespaceType1); - } - } - } - } - - /** - * Converts Yang 1.1 Actions to list of Type objects. - * - * @param module module from which is obtained set of all Action objects to - * iterate over them - * @param genCtx input, generated context - * @param verboseClassComments verbosity switch - * @return generated context - */ - static Map actionMethodsToGenType(final Module module, final Map - genCtx, - final SchemaContext schemaContext, final boolean - verboseClassComments, - final Map> - genTypeBuilders, final TypeProvider typeProvider) { - - checkModuleAndModuleName(module); - resolveActions(module, module, schemaContext, verboseClassComments, genTypeBuilders, genCtx, typeProvider, - BindingNamespaceType.Operation); - return genCtx; - } - - /** - * Converts global RPCs inputs and outputs sub-statements of the module - * to the list of Type objects. In addition, containers - * and lists which belong to input or output are also part of returning list. - * Detected routed RPCs are turned to Yang 1.1 Actions - * - * @param module module from which is obtained set of all RPC objects to - * iterate over them - * @param genCtx input, generated context - * @param verboseClassComments verbosity switch - * @return generated context - * @throws IllegalArgumentException

    - *
  • if the module is null
  • - *
  • if the name of module is null
  • - *
- * @throws IllegalStateException if set of RPCs from module is null - */ - static Map rpcMethodsToGenType(final Module module, final Map genCtx, - final SchemaContext schemaContext, final boolean - verboseClassComments, final Map> genTypeBuilders, final TypeProvider typeProvider) { - - checkModuleAndModuleName(module); - final Set rpcDefinitions = module.getRpcs(); - checkState(rpcDefinitions != null, "Set of RPCs from module " + module.getName() + " cannot be NULL."); - if (rpcDefinitions.isEmpty()) { - return genCtx; - } - - for (final RpcDefinition rpc : rpcDefinitions) { - final GeneratedTypeBuilder typeBuilder = resolveOperation(null, rpc, module, schemaContext, - verboseClassComments, genTypeBuilders, genCtx, typeProvider, false, - BindingNamespaceType.Operation); - genCtx.get(module).addTopLevelNodeType(typeBuilder); - genCtx.get(module).addTypeToSchema(typeBuilder, rpc); - } - - return genCtx; - } - - /** - * Converts RPC, Action or routed RPC into generated type. - * - * @return generated type - */ - private static GeneratedTypeBuilder resolveOperation(final DataSchemaNode parent, final OperationDefinition - operation, - final Module module, final SchemaContext schemaContext, - final boolean verboseClassComments, - final Map> - genTypeBuilders, final Map - genCtx, - final TypeProvider typeProvider, final boolean isAction, - final BindingNamespaceType namespaceType) { - - //operation name - final String operationName = operation.getQName().getLocalName(); - //concrete operation name - final StringBuilder sb = new StringBuilder(operationName).append('_'); - if (isAction) { - sb.append("Action"); - } else { - sb.append("Rpc"); - } - final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(module, sb.toString(), - verboseClassComments, genCtx.get(module)); - - final String basePackageName = interfaceBuilder.getPackageName(); - - if (verboseClassComments) { - interfaceBuilder.addComment(TypeComments.javadoc( - "Interface for implementing the following YANG Operation defined in module " - + module.getName() + "").get()); - YangSourceDefinition.of(module, operation).ifPresent(interfaceBuilder::setYangSourceDefinition); - } - - final String operationComment = encodeAngleBrackets(operation.getDescription().orElse(null)); - final MethodSignatureBuilder operationMethod = interfaceBuilder.addMethod("invoke"); - - //input - final ContainerSchemaNode input = operation.getInput(); - final GeneratedTypeBuilder inType = resolveOperationNode(interfaceBuilder, module, operation.getInput(), - basePackageName, schemaContext, operationName, verboseClassComments, typeProvider, genTypeBuilders, - genCtx, true, namespaceType); - annotateDeprecatedIfNecessary(operation.getStatus(), inType); - inType.setParentTypeForBuilder(interfaceBuilder); - genCtx.get(module).addChildNodeType(input, inType); - - //output - final ContainerSchemaNode output = operation.getOutput(); - final GeneratedTypeBuilder outType = resolveOperationNode(interfaceBuilder, module, operation.getOutput(), - basePackageName, schemaContext, operationName, verboseClassComments, typeProvider, genTypeBuilders, - genCtx, false, namespaceType); - annotateDeprecatedIfNecessary(operation.getStatus(), outType); - outType.setParentTypeForBuilder(interfaceBuilder); - genCtx.get(module).addChildNodeType(output, outType); - - final GeneratedType inTypeInstance = inType.toInstance(); - operationMethod.addParameter(inTypeInstance, "input"); - - if (isAction) { - requireNonNull(parent, "Parent must be specified for action."); - //action - GeneratedTypeBuilder parentType = genCtx.get(module).getChildNode(parent.getPath()); - checkState(parentType != null, "Parent generated type for " + parent - + " data schema node must have been generated already"); - annotateDeprecatedIfNecessary(parent.getStatus(), parentType); - - if (parent instanceof ListSchemaNode) { - //ListAction - GeneratedTransferObject keyType = null; - for (MethodSignatureBuilder method : parentType.getMethodDefinitions()) { - if (method.getName().equals("getIdentifier")) { - keyType = (GeneratedTransferObject) method.toInstance(parentType).getReturnType(); - } - } - - operationMethod.addParameter(parameterizedTypeFor(KEYED_INSTANCE_IDENTIFIER, parentType, keyType), - "kii"); - interfaceBuilder.addImplementsType(parameterizedTypeFor(LIST_ACTION, parentType, keyType, inType, - outType)); - } else { - //Action - operationMethod.addParameter(parameterizedTypeFor(INSTANCE_IDENTIFIER, parentType), "ii"); - interfaceBuilder.addImplementsType(parameterizedTypeFor(ACTION, parentType, - parameterizedTypeFor(INSTANCE_IDENTIFIER, parentType), inType, outType)); - } - } else { - //RPC - interfaceBuilder.addImplementsType(parameterizedTypeFor(RPC, inType, outType)); - } - - interfaceBuilder.addImplementsType(TREE_NODE); - operationMethod.addParameter(parameterizedTypeFor(RPC_CALLBACK, outType), "callback"); - - operationMethod.setComment(operationComment); - operationMethod.setReturnType(VOID); - - return interfaceBuilder; - } - - private static GeneratedTypeBuilder resolveOperationNode(final GeneratedTypeBuilder parent, final Module module, - final ContainerSchemaNode operationNode, final String basePackageName, final SchemaContext schemaContext, - final String operationName, final boolean verboseClassComments, final TypeProvider typeProvider, - final Map> genTypeBuilders, - final Map genCtx, final boolean isInput, final BindingNamespaceType namespaceType) { - final GeneratedTypeBuilder nodeType = addRawInterfaceDefinition(basePackageName, operationNode, schemaContext, - operationName, "", verboseClassComments, genTypeBuilders, namespaceType, genCtx.get(module)); - addImplementedInterfaceFromUses(operationNode, nodeType, genCtx); - - nodeType.addImplementsType(parameterizedTypeFor(BindingTypes.TREE_CHILD_NODE, parent, - parameterizedTypeFor(BindingTypes.ITEM, nodeType))); - - if (isInput) { - nodeType.addImplementsType(parameterizedTypeFor(INPUT, nodeType)); - } else { - nodeType.addImplementsType(parameterizedTypeFor(OUTPUT, nodeType)); - } - nodeType.addImplementsType(parameterizedTypeFor(INSTANTIABLE, nodeType)); - nodeType.addImplementsType(augmentable(nodeType)); - GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, nodeType, nodeType, operationNode.getChildNodes(), - genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider, namespaceType); - - final MethodSignatureBuilder nodeMethod = nodeType.addMethod("implementedInterface"); - nodeMethod.setReturnType(parameterizedTypeFor(CLASS, nodeType)); - nodeMethod.addAnnotation("", "Override"); - - processUsesImplements(operationNode, module, schemaContext, genCtx, namespaceType); - - return nodeType; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/BaseYangTypes.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/BaseYangTypes.java deleted file mode 100644 index d0b0bf0919..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/BaseYangTypes.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.yang.types; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import java.math.BigDecimal; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.Empty; -import org.opendaylight.yangtools.yang.common.Uint16; -import org.opendaylight.yangtools.yang.common.Uint32; -import org.opendaylight.yangtools.yang.common.Uint64; -import org.opendaylight.yangtools.yang.common.Uint8; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -public final class BaseYangTypes { - /** - * Mapping of basic built-in YANG types (RFC7950) to JAVA - * {@link org.opendaylight.mdsal.binding.javav2.model.api.Type Type}. - * This map is filled with mapping data in static initialization block - */ - private static final Map TYPE_MAP; - - /** - * Type representation of binary YANG type. - */ - public static final Type BINARY_TYPE = Types.primitiveType("byte[]", null); - - /** - * Type representation of boolean YANG type. - */ - public static final Type BOOLEAN_TYPE = Types.typeForClass(Boolean.class); - - /** - * Type representation of decimal64 YANG type. - */ - public static final Type DECIMAL64_TYPE = Types.typeForClass(BigDecimal.class); - - /** - * Type representation of empty YANG type. - */ - public static final Type EMPTY_TYPE = Types.typeForClass(Empty.class); - - /** - * Type representation of enumeration YANG type. - */ - public static final Type ENUM_TYPE = Types.typeForClass(Enum.class); - - /** - * Type representation of instance-identifier YANG type. - */ - public static final Type INSTANCE_IDENTIFIER = Types.parameterizedTypeFor(Types - .typeForClass(InstanceIdentifier.class)); - - /** - * Type representation of int8 YANG type. - */ - public static final Type INT8_TYPE = Types.typeForClass(Byte.class); - - /** - * Type representation of int16 YANG type. - */ - public static final Type INT16_TYPE = Types.typeForClass(Short.class); - - /** - * Type representation of int32 YANG type. - */ - public static final Type INT32_TYPE = Types.typeForClass(Integer.class); - - /** - * Type representation of int64 YANG type. - */ - public static final Type INT64_TYPE = Types.typeForClass(Long.class); - - /** - * Type representation of string YANG type. - */ - public static final Type STRING_TYPE = Types.typeForClass(String.class); - - /** - * Type representation of uint8 YANG type. - */ - public static final Type UINT8_TYPE = Types.typeForClass(Uint8.class); - - /** - * Type representation of uint16 YANG type. - */ - public static final Type UINT16_TYPE = Types.typeForClass(Uint16.class); - - /** - * Type representation of uint32 YANG type. - */ - public static final Type UINT32_TYPE = Types.typeForClass(Uint32.class); - - /** - * Type representation of uint64 YANG type. - */ - public static final Type UINT64_TYPE = Types.typeForClass(Uint64.class); - - /** - * Type representation of union YANG type. - */ - public static final Type UNION_TYPE = new UnionType(); - - private BaseYangTypes() { - throw new UnsupportedOperationException(); - } - - static { - final Builder b = ImmutableMap.builder(); - - b.put("binary", BINARY_TYPE); - b.put("boolean", BOOLEAN_TYPE); - b.put("decimal64", DECIMAL64_TYPE); - b.put("empty", EMPTY_TYPE); - b.put("enumeration", ENUM_TYPE); - b.put("instance-identifier", INSTANCE_IDENTIFIER); - b.put("int8", INT8_TYPE); - b.put("int16", INT16_TYPE); - b.put("int32", INT32_TYPE); - b.put("int64", INT64_TYPE); - b.put("string", STRING_TYPE); - b.put("uint8", UINT8_TYPE); - b.put("uint16", UINT16_TYPE); - b.put("uint32", UINT32_TYPE); - b.put("uint64", UINT64_TYPE); - b.put("union", UNION_TYPE); - - TYPE_MAP = b.build(); - } - - public static final TypeProvider BASE_YANG_TYPES_PROVIDER = new TypeProvider() { - /** - * Searches Type value to which is YANG type - * mapped. - * - * @param type - * type definition representation of YANG type - * @return java Type representation of type. - * If type isn't found then null is - * returned. - */ - @Override - public Type javaTypeForSchemaDefinitionType(final TypeDefinition type, final SchemaNode parentNode, - final ModuleContext context) { - if (type != null) { - return TYPE_MAP.get(type.getQName().getLocalName()); - } - - return null; - } - - @Override - public Type javaTypeForSchemaDefinitionType(final TypeDefinition type, final SchemaNode parentNode, - final Restrictions restrictions, final ModuleContext context) { - - final String typeName = type.getQName().getLocalName(); - switch (typeName) { - case "binary": - return restrictions == null ? Types.BYTE_ARRAY : Types.primitiveType("byte[]", restrictions); - case "decimal64": - return Types.typeForClass(BigDecimal.class, restrictions, context); - case "enumeration": - return Types.typeForClass(Enum.class, restrictions, context); - case "int8": - return Types.typeForClass(Byte.class, restrictions, context); - case "int16": - return Types.typeForClass(Short.class, restrictions, context); - case "int32": - return Types.typeForClass(Integer.class, restrictions, context); - case "int64": - return Types.typeForClass(Long.class, restrictions, context); - case "string": - return Types.typeForClass(String.class, restrictions, context); - case "uint8": - return Types.typeForClass(Uint8.class, restrictions, context); - case "uint16": - return Types.typeForClass(Uint16.class, restrictions, context); - case "uint32": - return Types.typeForClass(Uint32.class, restrictions, context); - case "uint64": - return Types.typeForClass(Uint64.class, restrictions, context); - case "union" : - return UNION_TYPE; - default: - return javaTypeForSchemaDefinitionType(type, parentNode, context); - } - } - - @Override - public String getTypeDefaultConstruction(final LeafSchemaNode node) { - return null; - } - - @Override - public String getConstructorPropertyName(final SchemaNode node) { - return null; - } - - @Override - public String getParamNameFromType(final TypeDefinition type) { - return JavaIdentifierNormalizer.normalizeSpecificIdentifier(type.getQName().getLocalName(), - JavaIdentifier.METHOD); - } - }; - - @Deprecated - private static > Restrictions singleRangeRestrictions(final T min, final T max) { - return Types.getDefaultRestrictions(min, max); - } - - public static final class UnionType implements Type { - @Override - public String getPackageName() { - return BindingMapping.PACKAGE_PREFIX; - } - - @Override - public String getName() { - return "Union"; - } - - @Override - public String getFullyQualifiedName() { - return "Union"; - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/GroupingDefinitionDependencySort.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/GroupingDefinitionDependencySort.java deleted file mode 100644 index dbcab703d6..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/GroupingDefinitionDependencySort.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.yang.types; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.opendaylight.yangtools.util.TopologicalSort; -import org.opendaylight.yangtools.util.TopologicalSort.Node; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.UsesNode; - -public class GroupingDefinitionDependencySort { - - /** - * Sorts set groupingDefinitions according to the mutual dependencies.
- * - *

- * Elements of groupingDefinitions are firstly transformed to {@link Node} interfaces and then are - * sorted by {@link TopologicalSort#sort(Set)} method. - *
- * - * Definition of dependency relation:
- * The first GroupingDefinition object (in this context) - * depends on second GroupingDefinition object if the first one - * contains in its set of UsesNode (obtained through - * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer#getUses() - * getUses} method) reference to the second one.
- * - * @param groupingDefinitions - * set of grouping definition which should be sorted according to - * mutual dependencies - * @return list of grouping definitiond which are sorted by mutual - * dependencies - * @throws IllegalArgumentException - * if groupingDefinitions - * - */ - public List sort(final Collection groupingDefinitions) { - if (groupingDefinitions == null) { - throw new IllegalArgumentException("Set of Type Definitions " + "cannot be NULL!"); - } - - final List resultGroupingDefinitions = new ArrayList<>(); - final Set unsorted = groupingDefinitionsToNodes(groupingDefinitions); - final List sortedNodes = TopologicalSort.sort(unsorted); - for (Node node : sortedNodes) { - NodeWrappedType nodeWrappedType = (NodeWrappedType) node; - resultGroupingDefinitions.add((GroupingDefinition) nodeWrappedType.getWrappedType()); - } - return resultGroupingDefinitions; - - } - - /** - * Wraps every grouping definition to node type and adds to every node - * information about dependencies. - * - *

- * The map with mapping from schema path (represents grouping definition) to - * node is created. For every created node (next nodeFrom) is for its - * wrapped grouping definition passed the set of its uses nodes - * through. For every uses node is found its wrapping node (next as - * nodeTo). This dependency relationship between nodeFrom and all - * found nodesTo is modeled with creating of one edge from nodeFrom to - * nodeTo. - * - * - * @param groupingDefinitions - * set of goruping definition which will be wrapped to nodes - * - * @return set of nodes where every one contains wrapped grouping definition - */ - private Set groupingDefinitionsToNodes(final Collection groupingDefinitions) { - final Map nodeMap = new HashMap<>(); - final Set resultNodes = new HashSet<>(); - - for (final GroupingDefinition groupingDefinition : groupingDefinitions) { - final Node node = new NodeWrappedType(groupingDefinition); - nodeMap.put(groupingDefinition.getPath(), node); - resultNodes.add(node); - } - - for (final Node node : resultNodes) { - final NodeWrappedType nodeWrappedType = (NodeWrappedType) node; - final GroupingDefinition groupingDefinition = (GroupingDefinition) nodeWrappedType.getWrappedType(); - - Set usesNodes = getAllUsesNodes(groupingDefinition); - - for (UsesNode usesNode : usesNodes) { - SchemaPath schemaPath = usesNode.getGroupingPath(); - Node nodeTo = nodeMap.get(schemaPath); - if (nodeTo != null) { - nodeWrappedType.addEdge(nodeTo); - } - } - } - - return resultNodes; - } - - /** - * Returns the set of the uses nodes which are get from uses in - * container, from uses in groupings inside - * container and from uses inside child nodes of the - * container. - * - * @param container - * data node container which can contain some uses of grouping - * @return set of uses nodes which were find in container. - */ - private Set getAllUsesNodes(final DataNodeContainer container) { - Set ret = new HashSet<>(); - Set usesNodes = container.getUses(); - ret.addAll(usesNodes); - - for (UsesNode usesNode : usesNodes) { - for (AugmentationSchemaNode augment : usesNode.getAugmentations()) { - ret.addAll(getAllUsesNodes(augment)); - } - } - Set groupings = container.getGroupings(); - for (GroupingDefinition groupingDefinition : groupings) { - ret.addAll(getAllUsesNodes(groupingDefinition)); - } - for (DataSchemaNode childNode : container.getChildNodes()) { - if (childNode instanceof DataNodeContainer) { - ret.addAll(getAllUsesNodes((DataNodeContainer) childNode)); - } else if (childNode instanceof ChoiceSchemaNode) { - for (CaseSchemaNode choiceCaseNode : ((ChoiceSchemaNode) childNode).getCases().values()) { - ret.addAll(getAllUsesNodes(choiceCaseNode)); - } - } - } - return ret; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/NodeWrappedType.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/NodeWrappedType.java deleted file mode 100644 index 38f67ffa37..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/NodeWrappedType.java +++ /dev/null @@ -1,62 +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.mdsal.binding.javav2.generator.yang.types; - -import org.opendaylight.yangtools.util.TopologicalSort.NodeImpl; - -public final class NodeWrappedType extends NodeImpl { - /** - * The payload which is saved inside Node. - */ - private final Object wrappedType; - - /** - * Create new instance of class NodeWrappedType. - * - * @param wrappedType - * object with payload data - */ - NodeWrappedType(Object wrappedType) { - this.wrappedType = wrappedType; - } - - /** - * Gets payload from class. - * - * @return object with wrappedType - */ - Object getWrappedType() { - return wrappedType; - } - - @Override - public boolean equals(Object object) { - if (this == object) { - return true; - } - if (!(object instanceof NodeWrappedType)) { - return false; - } - NodeWrappedType nodeWrappedType = (NodeWrappedType) object; - if (!wrappedType.equals(nodeWrappedType.wrappedType)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - return wrappedType.hashCode(); - } - - @Override - public String toString() { - return "NodeWrappedType{" + "wrappedType=" + wrappedType + '}'; - } - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeGenHelper.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeGenHelper.java deleted file mode 100755 index f90263ab1e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeGenHelper.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.yang.types; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl.addUnitsToGenTO; -import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.EnumerationBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.ActionDefinition; -import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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.RpcDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.Status; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.ModifierKind; -import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; -import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Auxiliary util class for {@link TypeProviderImpl} class. - */ -@Beta -public final class TypeGenHelper { - private static final Logger LOG = LoggerFactory.getLogger(TypeGenHelper.class); - - private TypeGenHelper() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Gets base type definition for extendTypeDef. The method is - * recursively called until non ExtendedType type is found. - * - * @param extendTypeDef type definition for which is the base type definition sought - * @return type definition which is base type for extendTypeDef - * @throws IllegalArgumentException if extendTypeDef equal null - */ - static TypeDefinition baseTypeDefForExtendedType(final TypeDefinition extendTypeDef) { - Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!"); - - TypeDefinition ret = extendTypeDef; - while (ret.getBaseType() != null) { - ret = ret.getBaseType(); - } - - return ret; - } - - /** - * Creates generated TO with data about inner extended type - * innerExtendedType, about the package name - * typedefName and about the generated TO name - * typedefName. - * - *

- * It is supposed that innerExtendedType is already present in - * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to - * be possible set it as extended type for the returning generated TO. - * - * @param typedef Type Definition - * @param innerExtendedType extended type which is part of some other extended type - * @param basePackageName string with the package name of the module - * @param moduleName Module Name - * @return generated TO which extends generated TO for - * innerExtendedType - * @throws IllegalArgumentException

    - *
  • if extendedType equals null
  • - *
  • if basePackageName equals null
  • - *
  • if typedefName equals null
  • - *
- */ - @SuppressWarnings({"rawtypes", "unchecked"}) - static GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition typedef, - final TypeDefinition innerExtendedType, final String basePackageName, final String moduleName, - final SchemaContext schemaContext, - final Map, Map>> genTypeDefsContextMap, - final ModuleContext context) { - - Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!"); - Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!"); - - final String typedefName = typedef.getQName().getLocalName(); - final String innerTypeDef = innerExtendedType.getQName().getLocalName(); - final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typedefName, context); - final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null)); - - genTOBuilder.setDescription(typedefDescription); - typedef.getReference().ifPresent(genTOBuilder::setReference); - genTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot()); - genTOBuilder.setModuleName(moduleName); - genTOBuilder.setTypedef(true); - final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef); - genTOBuilder.setRestrictions(r); - if (typedef.getStatus() == Status.DEPRECATED) { - genTOBuilder.addAnnotation("", "Deprecated"); - } - - if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) { - genTOBuilder.setIsUnion(true); - } - - Map, Map> modulesByDate = null; - Map typeMap = null; - final Module parentModule = findParentModule(schemaContext, innerExtendedType); - if (parentModule != null) { - modulesByDate = genTypeDefsContextMap.get(parentModule.getName()); - typeMap = modulesByDate.get(parentModule.getRevision()); - } - - if (typeMap != null) { - final Type type = typeMap.get(innerTypeDef); - if (type instanceof GeneratedTransferObject) { - genTOBuilder.setExtendsType((GeneratedTransferObject) type); - } - } - addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null)); - makeSerializable(genTOBuilder); - - return genTOBuilder.toInstance(); - } - - /** - * Wraps base YANG type to generated TO. - * - * @param basePackageName string with name of package to which the module belongs - * @param typedef type definition which is converted to the TO - * @param javaType JAVA Type to which is typedef mapped - * @return generated transfer object which representjavaType - */ - static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition typedef, - final Type javaType, final String moduleName, final - ModuleContext context) { - requireNonNull(javaType, "javaType cannot be null"); - final String propertyName = "value"; - - final GeneratedTOBuilderImpl genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName, - context); - genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef)); - final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName); - genPropBuilder.setReturnType(javaType); - genTOBuilder.addEqualsIdentity(genPropBuilder); - genTOBuilder.addHashIdentity(genPropBuilder); - genTOBuilder.addToStringProperty(genPropBuilder); - if (typedef.getStatus() == Status.DEPRECATED) { - genTOBuilder.addAnnotation("", "Deprecated"); - } - if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) { - addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef)); - } - addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null)); - genTOBuilder.setTypedef(true); - makeSerializable(genTOBuilder); - return genTOBuilder.toInstance(); - } - - /** - * Converts the pattern constraints from typedef to the list of - * the strings which represents these constraints. - * - * @param typedef extended type in which are the pattern constraints sought - * @return map of strings which represents the constraint patterns - * @throws IllegalArgumentException if typedef equals null - */ - static Map resolveRegExpressionsFromTypedef(final TypeDefinition typedef) { - if (!(typedef instanceof StringTypeDefinition)) { - return ImmutableMap.of(); - } - - // TODO: run diff against base ? - return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints()); - } - - /** - * Converts the pattern constraints to the list of - * the strings which represents these constraints. - * - * @param patternConstraints list of pattern constraints - * @return list of strings which represents the constraint patterns - */ - public static Map resolveRegExpressions(final List patternConstraints) { - if (patternConstraints.isEmpty()) { - return ImmutableMap.of(); - } - - final Map regExps = Maps.newHashMapWithExpectedSize(patternConstraints.size()); - for (PatternConstraint patternConstraint : patternConstraints) { - String regEx = patternConstraint.getJavaPatternString(); - - // The pattern can be inverted - final Optional optModifier = patternConstraint.getModifier(); - if (optModifier.isPresent()) { - regEx = applyModifier(optModifier.get(), regEx); - } - - regExps.put(regEx, patternConstraint.getRegularExpressionString()); - } - - return regExps; - } - - private static String applyModifier(final ModifierKind modifier, final String pattern) { - switch (modifier) { - case INVERT_MATCH: - return BindingMapping.negatePatternString(pattern); - default: - LOG.warn("Ignoring unhandled modifier {}", modifier); - return pattern; - } - } - - /** - * Finds out for each type definition how many immersion (depth) is - * necessary to get to the base type. Every type definition is inserted to - * the map which key is depth and value is list of type definitions with - * equal depth. In next step are lists from this map concatenated to one - * list in ascending order according to their depth. All type definitions - * are in the list behind all type definitions on which depends. - * - * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth - * @return list of type definitions sorted according their each other - * dependencies (type definitions which are depend on other type - * definitions are in list behind them). - */ - static List> sortTypeDefinitionAccordingDepth( - final Collection> unsortedTypeDefinitions) { - final List> sortedTypeDefinition = new ArrayList<>(); - - final Map>> typeDefinitionsDepths = new TreeMap<>(); - for (TypeDefinition unsortedTypeDefinition : unsortedTypeDefinitions) { - final int depth = getTypeDefinitionDepth(unsortedTypeDefinition); - final List> typeDefinitionsConcreteDepth = typeDefinitionsDepths.computeIfAbsent(depth, - k -> new ArrayList<>()); - typeDefinitionsConcreteDepth.add(unsortedTypeDefinition); - } - - // SortedMap guarantees order corresponding to keys in ascending order - typeDefinitionsDepths.values().forEach(sortedTypeDefinition::addAll); - - return sortedTypeDefinition; - } - - /** - * Adds to the genTOBuilder the constant which contains regular - * expressions from the regularExpressions. - * - * @param genTOBuilder generated TO builder to which are - * regular expressions added - * @param expressions list of string which represent regular expressions - */ - static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final Map expressions) { - if (!expressions.isEmpty()) { - genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), BindingMapping.PATTERN_CONSTANT_NAME, - ImmutableMap.copyOf(expressions)); - } - } - - /** - * Returns how many immersion is necessary to get from the type definition - * to the base type. - * - * @param typeDefinition type definition for which is depth sought. - * @return number of immersions which are necessary to get from the type - * definition to the base type - */ - private static int getTypeDefinitionDepth(final TypeDefinition typeDefinition) { - if (typeDefinition == null) { - return 1; - } - final TypeDefinition baseType = typeDefinition.getBaseType(); - if (baseType == null) { - return 1; - } - - int depth = 1; - if (baseType.getBaseType() != null) { - depth = depth + getTypeDefinitionDepth(baseType); - } else if (baseType instanceof UnionTypeDefinition) { - final List> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes(); - int maxChildDepth = 0; - int childDepth = 1; - for (TypeDefinition childTypeDefinition : childTypeDefinitions) { - childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition); - if (childDepth > maxChildDepth) { - maxChildDepth = childDepth; - } - } - return maxChildDepth; - } - return depth; - } - - static List> getAllTypedefs(final Module module) { - final List> ret = new ArrayList<>(); - - fillRecursively(ret, module); - - final Set notifications = module.getNotifications(); - for (NotificationDefinition notificationDefinition : notifications) { - fillRecursively(ret, notificationDefinition); - } - - final Set rpcs = module.getRpcs(); - for (RpcDefinition rpcDefinition : rpcs) { - ret.addAll(rpcDefinition.getTypeDefinitions()); - final ContainerSchemaNode input = rpcDefinition.getInput(); - if (input != null) { - fillRecursively(ret, input); - } - final ContainerSchemaNode output = rpcDefinition.getOutput(); - if (output != null) { - fillRecursively(ret, output); - } - } - - final Collection potentials = module.getChildNodes(); - - for (DataSchemaNode potential : potentials) { - if (potential instanceof ActionNodeContainer) { - final Set actions = ((ActionNodeContainer) potential).getActions(); - for (ActionDefinition action : actions) { - final ContainerSchemaNode input = action.getInput(); - if (input != null) { - fillRecursively(ret, input); - } - final ContainerSchemaNode output = action.getOutput(); - if (output != null) { - fillRecursively(ret, output); - } - } - } - } - - return ret; - } - - private static void fillRecursively(final List> list, final DataNodeContainer container) { - final Collection childNodes = container.getChildNodes(); - if (childNodes != null) { - childNodes.stream().filter(childNode -> !childNode.isAugmenting()).forEach(childNode -> { - if (childNode instanceof ContainerSchemaNode) { - fillRecursively(list, (ContainerSchemaNode) childNode); - } else if (childNode instanceof ListSchemaNode) { - fillRecursively(list, (ListSchemaNode) childNode); - } else if (childNode instanceof ChoiceSchemaNode) { - for (CaseSchemaNode caseNode : ((ChoiceSchemaNode) childNode).getCases().values()) { - fillRecursively(list, caseNode); - } - } - }); - } - - list.addAll(container.getTypeDefinitions()); - - final Set groupings = container.getGroupings(); - if (groupings != null) { - for (GroupingDefinition grouping : groupings) { - fillRecursively(list, grouping); - } - } - } - - /** - * Add {@link Serializable} to implemented interfaces of this TO. Also - * compute and add serialVersionUID property. - * - * @param gto transfer object which needs to be serializable - */ - static void makeSerializable(final GeneratedTOBuilderImpl gto) { - gto.addImplementsType(Types.typeForClass(Serializable.class)); - final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID"); - prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto))); - gto.setSUID(prop); - } - - /** - * Converts enumTypeDef to - * {@link Enumeration - * enumeration}. - * - * @param enumTypeDef enumeration type definition which is converted to enumeration - * @param enumName string with name which is used as the enumeration name - * @return enumeration type which is built with data (name, enum values) - * from enumTypeDef - * @throws IllegalArgumentException
    - *
  • if enumTypeDef equals null
  • - *
  • if enum values of enumTypeDef equal null
  • - *
  • if Q name of enumTypeDef equal null
  • - *
  • if name of enumTypeDef equal null
  • - *
- */ - @SuppressWarnings({"rawtypes", "unchecked"}) - static Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, - final SchemaNode parentNode, final SchemaContext schemaContext, final - ModuleContext context) { - Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!"); - Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null, - "Local Name in EnumTypeDefinition QName cannot be NULL!"); - final Module module = findParentModule(schemaContext, parentNode); - final String basePackageName = BindingMapping.getRootPackageName(module); - final String packageName; - - if (parentNode instanceof TypeDefinition) { - packageName = BindingGeneratorUtil.packageNameWithNamespacePrefix( - BindingMapping.getRootPackageName(module), - BindingNamespaceType.Typedef); - } else { - packageName = basePackageName; - } - - final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(packageName, enumName, context); - final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null)); - enumBuilder.setDescription(enumTypedefDescription); - enumBuilder.setReference(enumTypeDef.getReference().orElse(null)); - enumBuilder.setModuleName(module.getName()); - enumBuilder.setSchemaPath((List) enumTypeDef.getPath().getPathFromRoot()); - enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef); - return enumBuilder.toInstance(null); - } - - /** - * Converts typedef to the generated TO builder. - * - * @param basePackageName string with name of package to which the module belongs - * @param typedef type definition from which is the generated TO builder created - * @return generated TO builder which contains data from - * typedef and basePackageName - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, - final TypeDefinition typedef, final String - moduleName, final ModuleContext context) { - final String typeDefTOName = typedef.getQName().getLocalName(); - - if (basePackageName != null && typeDefTOName != null) { - final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(basePackageName, typeDefTOName, context); - final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null)); - - newType.setDescription(typedefDescription); - typedef.getReference().ifPresent(newType::setReference); - newType.setSchemaPath((List) typedef.getPath().getPathFromRoot()); - newType.setModuleName(moduleName); - - return newType; - } - return null; - } - - static Module getParentModule(final SchemaNode node, final SchemaContext schemaContext) { - return schemaContext.findModule(node.getPath().getPathFromRoot().iterator().next().getModule()).orElse(null); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeProviderImpl.java b/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeProviderImpl.java deleted file mode 100755 index 13b960b189..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/yang/types/TypeProviderImpl.java +++ /dev/null @@ -1,1074 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.yang.types; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets; -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.packageNameWithNamespacePrefix; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.getOuterClassPackageName; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.addStringRegExAsConstant; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.baseTypeDefForExtendedType; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getAllTypedefs; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getParentModule; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.makeSerializable; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideGeneratedTOFromExtendedType; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideTypeForEnum; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.resolveRegExpressionsFromTypedef; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.sortTypeDefinitionAccordingDepth; -import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.wrapJavaTypeIntoTO; -import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName; -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.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import java.util.ArrayList; -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.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode; -import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath; -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.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.DecimalTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition; -import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort; -import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl; -import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public final class TypeProviderImpl implements TypeProvider { - - private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class); - private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z"); - - /** - * Contains the schema data red from YANG files. - */ - private final SchemaContext schemaContext; - - /** - * Map<moduleName, Map<moduleDate, Map<typeName, type>>>. - */ - private final Map, Map>> genTypeDefsContextMap; - - /** - * Map which maps schema paths to JAVA Type. - */ - private final Map referencedTypes; - - /** - * Map for additional types e.g unions. - */ - private final Map> additionalTypes; - - /** - * Creates new instance of class TypeProviderImpl. - * - * @param schemaContext contains the schema data red from YANG files - * @throws IllegalArgumentException if schemaContext equal null. - */ - public TypeProviderImpl(final SchemaContext schemaContext) { - this.schemaContext = schemaContext; - this.genTypeDefsContextMap = new HashMap<>(); - this.referencedTypes = new HashMap<>(); - this.additionalTypes = new HashMap<>(); - resolveTypeDefsFromContext(); - } - - @Override - public Type javaTypeForSchemaDefinitionType(final TypeDefinition type, final SchemaNode parentNode, - final ModuleContext context) { - return javaTypeForSchemaDefinitionType(type, parentNode, null, context); - } - - /** - * Converts schema definition type typeDefinition to JAVA - * Type. - * - * @param type type definition which is converted to JAVA type - * @throws IllegalArgumentException
    - *
  • if typeDefinition equal null
  • - *
  • if QName of typeDefinition equal null
  • - *
  • if name of typeDefinition equal null
  • - *
- */ - @Override - public Type javaTypeForSchemaDefinitionType(final TypeDefinition type, final SchemaNode parentNode, - final Restrictions restrictions, final ModuleContext context) { - return javaTypeForSchemaDefType(type, parentNode, restrictions, context); - } - - @Override - public String getTypeDefaultConstruction(final LeafSchemaNode node) { - return null; - } - - @Override - public String getConstructorPropertyName(final SchemaNode node) { - return null; - } - - @Override - public String getParamNameFromType(final TypeDefinition type) { - return null; - } - - public Map, Map>> getGenTypeDefsContextMap() { - return this.genTypeDefsContextMap; - } - - /** - * Passes through all modules and through all its type definitions and - * convert it to generated types. - * - *

- * The modules are firstly sorted by mutual dependencies. The modules are - * sequentially passed. All type definitions of a module are at the - * beginning sorted so that type definition with less amount of references - * to other type definition are processed first.
- * For each module is created mapping record in the map - * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} - * which map current module name to the map which maps type names to - * returned types (generated types). - */ - private void resolveTypeDefsFromContext() { - - final Set modules = schemaContext.getModules(); - Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!"); - final List modulesSortedByDependency = ModuleDependencySort.sort(modules); - - for (final Module module : modulesSortedByDependency) { - Map, Map> dateTypeMap = genTypeDefsContextMap.get(module.getName()); - if (dateTypeMap == null) { - dateTypeMap = new HashMap<>(); - } - dateTypeMap.put(module.getRevision(), Collections.emptyMap()); - genTypeDefsContextMap.put(module.getName(), dateTypeMap); - } - - modulesSortedByDependency.stream().filter(Objects::nonNull).forEach(module -> { - ModuleContext context = new ModuleContext(); - final String basePackageName = packageNameWithNamespacePrefix(getRootPackageName(module), - BindingNamespaceType.Typedef); - final List> typeDefinitions = getAllTypedefs(module); - for (TypeDefinition typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) { - typedefToGeneratedType(basePackageName, module, typedef, context); - } - }); - } - - /** - * Converts typeDefinition to concrete JAVA Type. - * - * @param typeDefinition type definition which should be converted to JAVA - * Type - * @return JAVA Type which represents - * typeDefinition - * @throws IllegalArgumentException

    - *
  • if typeDefinition equal null
  • - *
  • if Q name of typeDefinition
  • - *
  • if name of typeDefinition
  • - *
- */ - public Type generatedTypeForExtendedDefinitionType(final TypeDefinition typeDefinition, - final SchemaNode parentNode) { - Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!"); - Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null, - "Type Definitions Local Name cannot be NULL!"); - - final TypeDefinition baseTypeDef = baseTypeDefForExtendedType(typeDefinition); - if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) { - final Module module = findParentModule(this.schemaContext, parentNode); - - if (module != null) { - final Map, Map> modulesByDate = - this.genTypeDefsContextMap.get(module.getName()); - final Map genTOs = modulesByDate.get(module.getRevision()); - if (genTOs != null) { - return genTOs.get(typeDefinition.getQName().getLocalName()); - } - } - } - return null; - } - - /** - * Puts refType to map with key refTypePath. - * - * @param refTypePath schema path used as the map key - * @param refType type which represents the map value - * @throws IllegalArgumentException
    - *
  • if refTypePath equal null
  • - *
  • if refType equal null
  • - *
- */ - public void putReferencedType(final SchemaPath refTypePath, final Type refType) { - Preconditions.checkArgument(refTypePath != null, - "Path reference of Enumeration Type Definition cannot be NULL!"); - Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!"); - this.referencedTypes.put(refTypePath, refType); - } - - /** - * Converts typeDef which should be of the type - * BitsTypeDefinition to GeneratedTOBuilder. - * - *

- * All the bits of the typeDef are added to returning generated TO as - * properties. - * - * @param basePackageName string with name of package to which the module belongs - * @param typeDef type definition from which is the generated TO builder created - * @param typeDefName string with the name for generated TO builder - * @return generated TO builder which represents typeDef - * @throws IllegalArgumentException

    - *
  • if typeDef equals null
  • - *
  • if basePackageName equals null
  • - *
- */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, - final TypeDefinition typeDef, final - String typeDefName, final String - moduleName, - final ModuleContext context) { - - Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!"); - Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!"); - - if (typeDef instanceof BitsTypeDefinition) { - final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef; - - final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, - true, false, context); - final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null)); - - genTOBuilder.setDescription(typedefDescription); - typeDef.getReference().ifPresent(genTOBuilder::setReference); - genTOBuilder.setSchemaPath((List) typeDef.getPath().getPathFromRoot()); - genTOBuilder.setModuleName(moduleName); - genTOBuilder.setBaseType(typeDef); - - final List bitList = bitsTypeDefinition.getBits(); - GeneratedPropertyBuilder genPropertyBuilder; - for (final Bit bit : bitList) { - final String name = bit.getName(); - genPropertyBuilder = genTOBuilder.addProperty( - JavaIdentifierNormalizer.normalizeSpecificIdentifier(name, JavaIdentifier.METHOD)); - genPropertyBuilder.setReadOnly(true); - genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE); - - genTOBuilder.addEqualsIdentity(genPropertyBuilder); - genTOBuilder.addHashIdentity(genPropertyBuilder); - genTOBuilder.addToStringProperty(genPropertyBuilder); - } - - return genTOBuilder; - } - return null; - } - - /** - * Converts typedef to generated TO with - * typeDefName. Every union type from typedef is - * added to generated TO builder as property. - * - * @param basePackageName string with name of package to which the module belongs - * @param typedef type definition which should be of type - * UnionTypeDefinition - * @param typeDefName string with name for generated TO - * @return generated TO builder which represents typedef - * @throws NullPointerException
    - *
  • if basePackageName is null
  • - *
  • if typedef is null
  • - *
  • if QName of typedef is null
  • - *
- */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public List provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, - final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, - final ModuleContext context) { - requireNonNull(basePackageName, "Base Package Name cannot be NULL!"); - requireNonNull(typedef, "Type Definition cannot be NULL!"); - requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!"); - - final List generatedTOBuilders = new ArrayList<>(); - final List> unionTypes = typedef.getTypes(); - final Module module = findParentModule(schemaContext, parentNode); - - final GeneratedTOBuilderImpl unionGenTOBuilder; - unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, true, false, - context); - final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null)); - unionGenTOBuilder.setDescription(typedefDescription); - typedef.getReference().ifPresent(unionGenTOBuilder::setReference); - unionGenTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot()); - unionGenTOBuilder.setModuleName(module.getName()); - - generatedTOBuilders.add(unionGenTOBuilder); - unionGenTOBuilder.setIsUnion(true); - final Map expressions = new HashMap<>(); - for (final TypeDefinition unionType : unionTypes) { - final String unionTypeName = unionType.getQName().getLocalName(); - if (unionType.getBaseType() != null) { - resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode); - } else if (unionType instanceof UnionTypeDefinition) { - generatedTOBuilders.add(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType, - unionGenTOBuilder.getFullyQualifiedName(), parentNode, context)); - } else if (unionType instanceof EnumTypeDefinition) { - final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType, - unionTypeName, unionGenTOBuilder, context); - updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName); - } else { - final Type javaType = javaTypeForSchemaDefType(unionType, parentNode, null, context); - updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName); - } - } - if (!expressions.isEmpty()) { - addStringRegExAsConstant(unionGenTOBuilder, expressions); - } - - //storeGenTO(typedef, unionGenTOBuilder, parentNode); - - return generatedTOBuilders; - } - - public Map> getAdditionalTypes() { - return this.additionalTypes; - } - - public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) { - if (!Strings.isNullOrEmpty(units)) { - to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\""); - final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS"); - prop.setReturnType(Types.STRING); - to.addToStringProperty(prop); - } - } - - private Type javaTypeForSchemaDefType(final TypeDefinition typeDefinition, final SchemaNode parentNode, - final Restrictions restrictions, final ModuleContext context) { - Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!"); - final String typedefName = typeDefinition.getQName().getLocalName(); - Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!"); - - // Deal with base types - if (typeDefinition.getBaseType() == null) { - // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type - // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates - // a base type which holds these constraints. - if (typeDefinition instanceof DecimalTypeDefinition) { - final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, - parentNode, restrictions, context); - if (ret != null) { - return ret; - } - } - - // Deal with leafrefs/identityrefs - Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, context); - if (ret != null) { - return ret; - } - - ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, - null); - if (ret == null) { - LOG.debug("Failed to resolve Java type for {}", typeDefinition); - } - - return ret; - } - - Type returnType = javaTypeForExtendedType(typeDefinition, context); - if (restrictions != null && !restrictions.isEmpty() && returnType instanceof GeneratedTransferObject) { - final GeneratedTransferObject gto = (GeneratedTransferObject) returnType; - final Module module = findParentModule(schemaContext, parentNode); - final Module module1 = findParentModule(schemaContext, typeDefinition); - final String basePackageName = BindingMapping.getRootPackageName(module); - final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition - .getPath(), BindingNamespaceType.Typedef); - final String genTOName = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(typedefName, JavaIdentifier.CLASS); - final String name = packageName + "." + genTOName; - if (module.equals(module1) && !returnType.getFullyQualifiedName().equals(name)) { - returnType = shadedTOWithRestrictions(gto, restrictions, context); - } - } - return returnType; - } - - /** - * Return JAVA Type representation of typedef. - * @param basePackageName string with name of package to which the module belongs - * @param module string with the name of the module for to which the - * typedef belongs - * @param typedef type definition of the node for which should be creted JAVA - * Type (usually generated TO) - * @return JAVA Type representation of typedef or - * null value if basePackageName or - * modulName or typedef or Q name of - * typedef equals null - */ - private Type typedefToGeneratedType(final String basePackageName, final Module module, - final TypeDefinition typedef, final ModuleContext context) { - final String moduleName = module.getName(); - final Optional moduleRevision = module.getRevision(); - if (basePackageName != null && moduleName != null && typedef != null) { - final String typedefName = typedef.getQName().getLocalName(); - final TypeDefinition innerTypeDefinition = typedef.getBaseType(); - if (!(innerTypeDefinition instanceof LeafrefTypeDefinition) - && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) { - Type returnType; - if (innerTypeDefinition.getBaseType() != null) { - returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, - module.getName(), schemaContext, genTypeDefsContextMap, context); - } else if (innerTypeDefinition instanceof UnionTypeDefinition) { - final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName, - (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef, context); - genTOBuilder.setTypedef(true); - genTOBuilder.setIsUnion(true); - addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null)); - makeSerializable((GeneratedTOBuilderImpl) genTOBuilder); - returnType = genTOBuilder.toInstance(); - } else if (innerTypeDefinition instanceof EnumTypeDefinition) { - // enums are automatically Serializable - final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition; - // TODO units for typedef enum - returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef, schemaContext, context); - } else if (innerTypeDefinition instanceof BitsTypeDefinition) { - final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition; - final GeneratedTOBuilder genTOBuilder = - provideGeneratedTOBuilderForBitsTypeDefinition( - basePackageName, bitsTypeDefinition, typedefName, module.getName(), context); - genTOBuilder.setTypedef(true); - addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null)); - makeSerializable((GeneratedTOBuilderImpl) genTOBuilder); - returnType = genTOBuilder.toInstance(); - } else { - final Type javaType = javaTypeForSchemaDefType(innerTypeDefinition, typedef, null, - context); - returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName(), context); - } - if (returnType != null) { - final Map, Map> modulesByDate = - genTypeDefsContextMap.get(moduleName); - Map typeMap = modulesByDate.get(moduleRevision); - if (typeMap != null) { - if (typeMap.isEmpty()) { - typeMap = new HashMap<>(4); - modulesByDate.put(moduleRevision, typeMap); - } - typeMap.put(typedefName, returnType); - } - return returnType; - } - } - } - return null; - } - - /** - * Returns JAVA Type for instances of the type - * ExtendedType. - * - * @param typeDefinition type definition which is converted to JAVA Type - * @return JAVA Type instance for typeDefinition - */ - private Type javaTypeForExtendedType(final TypeDefinition typeDefinition, final ModuleContext context) { - - final String typedefName = typeDefinition.getQName().getLocalName(); - final TypeDefinition baseTypeDef = baseTypeDefForExtendedType(typeDefinition); - Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, context); - if (returnType == null) { - final Module module = findParentModule(schemaContext, typeDefinition); - final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition); - if (module != null) { - final Map, Map> modulesByDate = genTypeDefsContextMap.get(module - .getName()); - final Map genTOs = modulesByDate.get(module.getRevision()); - if (genTOs != null) { - returnType = genTOs.get(typedefName); - } - if (returnType == null) { - returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType( - baseTypeDef, typeDefinition, r, context); - } - } - } - return returnType; - } - - /** - * Returns JAVA Type for instances of the type - * LeafrefTypeDefinition or - * IdentityrefTypeDefinition. - * - * @param typeDefinition type definition which is converted to JAVA Type - * @return JAVA Type instance for typeDefinition - */ - private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition typeDefinition, final SchemaNode parentNode, - final ModuleContext context) { - if (typeDefinition instanceof LeafrefTypeDefinition) { - final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition; - Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode, schemaContext), - "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref); - return provideTypeForLeafref(leafref, parentNode, context); - } else if (typeDefinition instanceof IdentityrefTypeDefinition) { - final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition; - return provideTypeForIdentityref(idref, schemaContext); - } else { - return null; - } - } - - /** - * Converts leafrefType to JAVA Type. - * - *

- * The path of leafrefType is followed to find referenced node - * and its Type is returned. - * - * @param leafrefType leafref type definition for which is the type sought - * @return JAVA Type of data schema node which is referenced in - * leafrefType - * @throws IllegalArgumentException

    - *
  • if leafrefType equal null
  • - *
  • if path statement of leafrefType equal null
  • - *
- */ - public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode, - final ModuleContext context) { - Type returnType = null; - Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!"); - - Preconditions.checkArgument(leafrefType.getPathStatement() != null, - "The Path Statement for Leafref Type Definition cannot be NULL!"); - - final RevisionAwareXPath xpath = leafrefType.getPathStatement(); - final String strXPath = xpath.toString(); - if (strXPath != null) { - if (strXPath.indexOf('[') == -1) { - final Module module; - final SchemaNode actualParentSchemaNode; - if (parentNode instanceof DerivableSchemaNode && ((DerivableSchemaNode) parentNode).isAddedByUses()) { - final Optional originalNode = ((DerivableSchemaNode) parentNode) - .getOriginal(); - Preconditions.checkArgument(originalNode.isPresent(), "originalNode can not be null."); - actualParentSchemaNode = originalNode.get(); - module = findParentModule(schemaContext, originalNode.get()); - } else { - actualParentSchemaNode = parentNode; - module = findParentModule(schemaContext, parentNode); - } - Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode); - - final SchemaNode dataNode; - if (xpath.isAbsolute()) { - dataNode = findDataSchemaNode(schemaContext, module, xpath); - } else { - dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, actualParentSchemaNode, xpath); - } - Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)", - strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName() - .getModule()); - - if (leafContainsEnumDefinition(dataNode)) { - returnType = this.referencedTypes.get(dataNode.getPath()); - } else if (leafListContainsEnumDefinition(dataNode)) { - returnType = Types.listTypeFor(this.referencedTypes.get(dataNode.getPath())); - } else { - returnType = resolveTypeFromDataSchemaNode(dataNode, context); - } - } else { - returnType = Types.typeForClass(Object.class); - } - } - Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)", - strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule()); - return returnType; - } - - /** - * Checks if dataNode is LeafSchemaNode and if it - * so then checks if it is of type EnumTypeDefinition. - * - * @param dataNode data schema node for which is checked if it is leaf and if it - * is of enum type - * @return boolean value - *
    - *
  • true - if dataNode is leaf of type enumeration
  • - *
  • false - other cases
  • - *
- */ - private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) { - if (dataNode instanceof LeafSchemaNode) { - final LeafSchemaNode leaf = (LeafSchemaNode) dataNode; - //CompatUtils is not used here anymore - if (leaf.getType() instanceof EnumTypeDefinition) { - return true; - } - } - return false; - } - - /** - * Checks if dataNode is LeafListSchemaNode and if - * it so then checks if it is of type EnumTypeDefinition. - * - * @param dataNode data schema node for which is checked if it is leaflist and if - * it is of enum type - * @return boolean value - *
    - *
  • true - if dataNode is leaflist of type - * enumeration
  • - *
  • false - other cases
  • - *
- */ - private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) { - if (dataNode instanceof LeafListSchemaNode) { - final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode; - if (leafList.getType() instanceof EnumTypeDefinition) { - return true; - } - } - return false; - } - - /** - * Converts dataNode to JAVA Type. - * - * @param dataNode contains information about YANG type - * @return JAVA Type representation of dataNode - */ - private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final ModuleContext context) { - Type returnType = null; - if (dataNode != null) { - if (dataNode instanceof LeafSchemaNode) { - final LeafSchemaNode leaf = (LeafSchemaNode) dataNode; - //not using CompatUtils here anymore - final TypeDefinition type = leaf.getType(); - returnType = javaTypeForSchemaDefType(type, leaf, null, context); - } else if (dataNode instanceof LeafListSchemaNode) { - final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode; - returnType = javaTypeForSchemaDefType(leafList.getType(), leafList, null, context); - } - } - return returnType; - } - - /** - * Seeks for identity reference idref the JAVA - * type.
- *
- * - *

- * Example:
- * If identy which is referenced via idref has name Idn - * then returning type is {@code Class}
- * - * @param idref identityref type definition for which JAVA Type - * is sought - * @return JAVA Type of the identity which is refrenced through - * idref - */ - private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref, - final SchemaContext schemaContext) { - //TODO: incompatibility with Binding spec v2, get first or only one - final QName baseIdQName = idref.getIdentities().iterator().next().getQName(); - final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null); - IdentitySchemaNode identity = null; - for (final IdentitySchemaNode id : module.getIdentities()) { - if (id.getQName().equals(baseIdQName)) { - identity = id; - } - } - Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists"); - - final String basePackageName = BindingMapping.getRootPackageName(module); - final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath(), - BindingNamespaceType.Identity); - - final String genTypeName = JavaIdentifierNormalizer.normalizeSpecificIdentifier(identity.getQName() - .getLocalName(), - JavaIdentifier.CLASS); - - final Type baseType = Types.typeForClass(Class.class); - final Type paramType = Types.wildcardTypeFor(packageName, genTypeName, true, true, null); - return Types.parameterizedTypeFor(baseType, paramType); - } - - private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, - final Restrictions restrictions, final ModuleContext context) { - final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName(), context); - final GeneratedTransferObject parent = gto.getSuperType(); - if (parent != null) { - gtob.setExtendsType(parent); - } - gtob.setRestrictions(restrictions); - for (final GeneratedProperty gp : gto.getProperties()) { - final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName()); - gpb.setValue(gp.getValue()); - gpb.setReadOnly(gp.isReadOnly()); - gpb.setAccessModifier(gp.getAccessModifier()); - gpb.setReturnType(gp.getReturnType()); - gpb.setFinal(gp.isFinal()); - gpb.setStatic(gp.isStatic()); - } - return gtob.toInstance(); - } - - /** - * Adds a new property with the name propertyName and with type - * type to unonGenTransObject. - * - * @param unionGenTransObject generated TO to which should be property added - * @param type JAVA type of the property which should be added - * to unionGentransObject - * @param propertyName string with name of property which should be added to - * unionGentransObject - */ - private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, - final String propertyName) { - if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) { - final GeneratedPropertyBuilder propBuilder = unionGenTransObject - .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(propertyName, JavaIdentifier - .METHOD)); - propBuilder.setReturnType(type); - - unionGenTransObject.addEqualsIdentity(propBuilder); - unionGenTransObject.addHashIdentity(propBuilder); - unionGenTransObject.addToStringProperty(propBuilder); - } - } - - /** - * Wraps code which handle case when union subtype is also of the type - * UnionType. - * - *

- * In this case the new generated TO is created for union subtype (recursive - * call of method {@link #provideGeneratedTOBuilderForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode, - * SchemaContext, Map, ModuleContext)} - * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder - * parentUnionGenTOBuilder is created property which type is - * equal to new generated TO. - * - * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child - * union subtype added - * @param basePackageName string with the name of the module package - * @param unionSubtype type definition which represents union subtype - * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of - * provideGeneratedTOBuildersForUnionTypeDef method. - */ - private GeneratedTOBuilder resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, - final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode, - final ModuleContext context) { - final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()); - final GeneratedTOBuilder subUnionGenTOBUilder = provideGeneratedTOBuilderForUnionTypeDef( - basePackageName, unionSubtype, newTOBuilderName, parentNode, context); - - final GeneratedPropertyBuilder propertyBuilder; - propertyBuilder = parentUnionGenTOBuilder.addProperty( - JavaIdentifierNormalizer.normalizeSpecificIdentifier(newTOBuilderName, JavaIdentifier.METHOD)); - propertyBuilder.setReturnType(subUnionGenTOBUilder); - parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder); - parentUnionGenTOBuilder.addToStringProperty(propertyBuilder); - - return subUnionGenTOBUilder; - } - - /** - * Converts output list of generated TO builders to one TO builder (first - * from list) which contains the remaining builders as its enclosing TO. - * - * @param basePackageName string with name of package to which the module belongs - * @param typedef type definition which should be of type - * UnionTypeDefinition - * @param typeDefName string with name for generated TO - * @return generated TO builder with the list of enclosed generated TO builders - */ - public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName, - final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, - final ModuleContext context) { - - final List builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName, - typedef, typeDefName, parentNode, context); - Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef); - - final GeneratedTOBuilder resultTOBuilder = builders.remove(0); - for (final GeneratedTOBuilder genTOBuilder : builders) { - resultTOBuilder.addEnclosingTransferObject(genTOBuilder); - } - - final GeneratedPropertyBuilder genPropBuilder; - - genPropBuilder = resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY).setReadOnly(false); - resultTOBuilder.addEqualsIdentity(genPropBuilder); - resultTOBuilder.addHashIdentity(genPropBuilder); - resultTOBuilder.addToStringProperty(genPropBuilder); - - provideGeneratedTOBuilderForUnionBuilder(findParentModule(schemaContext, parentNode), resultTOBuilder); - - return resultTOBuilder; - } - - - private GeneratedTOBuilder provideGeneratedTOBuilderForUnionBuilder(final Module parentModule, - final GeneratedTOBuilder genTOBuilder) { - 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(getOuterClassPackageName(genTOBuilder), - name.toString(), true); - unionBuilder.setIsUnionBuilder(true); - - final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance"); - method.setReturnType(genTOBuilder); - method.addParameter(Types.STRING, "defaultValue"); - method.setAccessModifier(AccessModifier.PUBLIC); - method.setStatic(true); - - getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilder.toInstance()); - - return unionBuilder; - } - - /** - * Wraps code which handle case when union subtype is of the type - * ExtendedType. - * - *

- * If TO for this type already exists it is used for the creation of the - * property in parentUnionGenTOBuilder. In other case the base - * type is used for the property creation. - * - * @param parentUnionGenTOBuilder generated TO builder in which new property is created - * @param unionSubtype type definition of the ExtendedType type which - * represents union subtype - * @param expressions map of strings with the regular expressions - * @param parentNode parent Schema Node for Extended Subtype - */ - private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, - final TypeDefinition unionSubtype, final Map expressions, final SchemaNode parentNode) { - final String unionTypeName = unionSubtype.getQName().getLocalName(); - final Type genTO = findGenTO(unionTypeName, unionSubtype, schemaContext, genTypeDefsContextMap); - if (genTO != null) { - updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, unionTypeName); - return; - } - - final TypeDefinition baseType = baseTypeDefForExtendedType(unionSubtype); - if (unionTypeName.equals(baseType.getQName().getLocalName())) { - final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType, - parentNode, null); - if (javaType != null) { - updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName); - } - } else if (baseType instanceof LeafrefTypeDefinition) { - final Type javaType = javaTypeForSchemaDefinitionType(baseType, - parentNode, null); - boolean typeExist = false; - for (final GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder - .getProperties()) { - final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType(); - if (origType != null && javaType != null && javaType == origType) { - typeExist = true; - break; - } - } - if (!typeExist && javaType != null) { - updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, - javaType.getName() + parentUnionGenTOBuilder.getName() + "Value"); - } - } - if (baseType instanceof StringTypeDefinition) { - expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype)); - } - } - - /** - * Returns string which contains the same value as name but - * integer suffix is incremented by one. If name contains no - * number suffix then number 1 is added. - * - * @param name string with name of augmented node - * @return string with the number suffix incremented by one (or 1 is added) - */ - private static String provideAvailableNameForGenTOBuilder(final String name) { - final Matcher mtch = NUMBERS_PATTERN.matcher(name); - if (mtch.find()) { - final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1; - return name.substring(0, mtch.start()) + newSuffix; - } else { - return name + 1; - } - } - - /** - * Searches for generated TO for searchedTypeDef type - * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}. - * - * @param searchedTypeName string with name of searchedTypeDef - * @return generated TO for searchedTypeDef or - * null it it doesn't exist - */ - private static Type findGenTO(final String searchedTypeName, final SchemaNode parentNode, - final SchemaContext schemaContext, final Map, - Map>> genTypeDefsContextMap) { - - final Module typeModule = findParentModule(schemaContext, parentNode); - if (typeModule != null && typeModule.getName() != null) { - final Map, Map> modulesByDate = genTypeDefsContextMap.get(typeModule - .getName()); - final Map genTOs = modulesByDate.get(typeModule.getRevision()); - if (genTOs != null) { - return genTOs.get(searchedTypeName); - } - } - return null; - } - - /** - * Adds enumeration to typeBuilder. The enumeration data are - * taken from enumTypeDef. - * - * @param enumTypeDef enumeration type definition is source of enumeration data for - * typeBuilder - * @param enumName string with the name of enumeration - * @param typeBuilder generated type builder to which is enumeration added - * @return enumeration type which contains enumeration data form - * enumTypeDef - * @throws IllegalArgumentException

    - *
  • if enumTypeDef equals null
  • - *
  • if enum values of enumTypeDef equal null
  • - *
  • if Q name of enumTypeDef equal null
  • - *
  • if name of enumTypeDef equal null
  • - *
  • if name of typeBuilder equal null
  • - *
- */ - private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, - final String enumName, final - GeneratedTypeBuilderBase typeBuilder, final - ModuleContext context) { - Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!"); - Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null, - "Local Name in EnumTypeDefinition QName cannot be NULL!"); - Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!"); - - final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName, context); - final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null)); - enumBuilder.setDescription(enumTypedefDescription); - enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef); - return enumBuilder.toInstance(enumBuilder); - } - - private static boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode, - final SchemaContext schemaContext) { - final SchemaNode leafRefValueNode; - final RevisionAwareXPath leafRefXPath = leafref.getPathStatement(); - final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString() - .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute()); - - ///// skip leafrefs in augments - they're checked once augments are resolved - final Iterator iterator = parentNode.getPath().getPathFromRoot().iterator(); - boolean isAugmenting = false; - DataNodeContainer current = null; - DataSchemaNode dataChildByName; - - while (iterator.hasNext() && !isAugmenting) { - final QName next = iterator.next(); - if (current == null) { - dataChildByName = schemaContext.getDataChildByName(next); - } else { - dataChildByName = current.getDataChildByName(next); - } - if (dataChildByName != null) { - isAugmenting = dataChildByName.isAugmenting(); - } else { - return false; - } - if (dataChildByName instanceof DataNodeContainer) { - current = (DataNodeContainer) dataChildByName; - } - } - if (isAugmenting) { - return false; - } - ///// - - final Module parentModule = getParentModule(parentNode, schemaContext); - if (!leafRefStrippedXPath.isAbsolute()) { - leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, - parentNode, leafRefStrippedXPath); - } else { - leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath); - } - return leafRefValueNode != null && leafRefValueNode.equals(parentNode); - } - - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenTypeTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenTypeTest.java deleted file mode 100644 index 638da24713..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AugmentToGenTypeTest.java +++ /dev/null @@ -1,743 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode; -import org.opendaylight.yangtools.yang.model.api.GroupingDefinition; -import org.opendaylight.yangtools.yang.model.api.Module; -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.UnknownSchemaNode; -import org.opendaylight.yangtools.yang.model.api.UsesNode; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class AugmentToGenTypeTest { - - @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:illegalThrows", "checkstyle:illegalCatch"}) - @Test(expected = UnsupportedOperationException.class) - public void constructorTest() throws Throwable { - final Constructor constructor = AugmentToGenType.class.getDeclaredConstructor(); - constructor.setAccessible(true); - final Object[] objs = {}; - try { - constructor.newInstance(objs); - } catch (final Exception e) { - throw e.getCause(); - } - } - - @Test - public void generateNullModuleTest() { - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = null; - - try { - AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Module reference cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateNullModuleNameTest() { - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = mock(Module.class); - when(m.getName()).thenReturn(null); - - try { - AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Module name cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateNullModuleAugmentationsTest() { - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = mock(Module.class); - when(m.getName()).thenReturn("name"); - when(m.getAugmentations()).thenReturn(null); - - try { - AugmentToGenType.generate(m, context, typeProvider, genCtx, genTypeBuilders, false); - fail(); - } catch (final IllegalStateException e) { - assertEquals("Augmentations Set cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateWithoutAugmentationsTest() { - final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test.yang"); - final TypeProvider typeProvider = new TypeProviderImpl(context); - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Map invoke = AugmentToGenType.generate(context.getModules().iterator().next(), - context, typeProvider, genCtx, genTypeBuilders, false); - assertNotNull(invoke); - } - - @Test - public void generateWithAugmentationsTest() { - final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test-augment.yang"); - final TypeProvider typeProvider = new TypeProviderImpl(context); - final Map genCtx = mock(Map.class); - final Collection moduleContexts = new ArrayList<>(); - final ModuleContext moduleContext = new ModuleContext(); - moduleContexts.add(moduleContext); - final QName create = QName.create("urn:test:simple:test", "2017-02-06", "my-cont"); - final SchemaNode schemaNode = mock(SchemaNode.class); - when(schemaNode.getPath()).thenReturn(SchemaPath.create(true, create)); - moduleContext.addChildNodeType(schemaNode, new GeneratedTypeBuilderImpl("test", "Test", moduleContext)); - when(genCtx.values()).thenReturn(moduleContexts); - when(genCtx.get(context.getModules().iterator().next())).thenReturn(moduleContext); - final Map> genTypeBuilders = new HashMap<>(); - - final Map invoke = AugmentToGenType.generate(context.getModules().iterator().next(), - context, typeProvider, genCtx, genTypeBuilders, false); - assertNotNull(invoke); - } - - @Test - public void resolveAugmentationsNullModuleTest() { - try { - AugmentToGenType.resolveAugmentations(null, null); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Module reference cannot be NULL.", e.getMessage()); - } - } - - @Test - public void resolveAugmentationsNullAugmentationsTest() { - final Module m = mock(Module.class); - when(m.getAugmentations()).thenReturn(null); - final SchemaContext schemaContext = mock(SchemaContext.class); - - try { - AugmentToGenType.resolveAugmentations(m, schemaContext); - fail(); - } catch (final IllegalStateException e) { - assertEquals("Augmentations Set cannot be NULL.", e.getMessage()); - } - } - - @Test - public void resolveAugmentationsTest() { - final Module m = mock(Module.class); - final Module m2 = mock(Module.class); - final SchemaContext schemaContext = mock(SchemaContext.class); - - final Set augmentations = new HashSet<>(); - - final QName q1 = QName.create("q1", "2017-04-04", "q1"); - final QName q2 = QName.create("q2", "2017-04-04", "q2"); - final QName q3 = QName.create("q3", "2017-04-04", "q3"); - final QName q4 = QName.create("q4", "2017-04-04", "q4"); - final QName q5 = QName.create("q5", "2017-04-04", "q5"); - - final AugmentationSchemaNode AugmentationSchemaNode1 = mock(AugmentationSchemaNode.class); - when(AugmentationSchemaNode1.getTargetPath()).thenReturn(SchemaPath.create(true, q1, q2)); - final AugmentationSchemaNode AugmentationSchemaNode2 = mock(AugmentationSchemaNode.class); - when(AugmentationSchemaNode2.getTargetPath()).thenReturn(SchemaPath.create(true, q3, q4, q5)); - augmentations.add(AugmentationSchemaNode1); - augmentations.add(AugmentationSchemaNode2); - - when(m.getAugmentations()).thenReturn(augmentations); - when(schemaContext.findModule(q1.getModule())).thenReturn(Optional.of(m2)); - when(schemaContext.findModule(q3.getModule())).thenReturn(Optional.of(m2)); - - final List result = AugmentToGenType.resolveAugmentations(m, schemaContext); - assertNotNull(result); - assertTrue(!result.isEmpty()); - assertEquals(result.get(0), AugmentationSchemaNode1); - assertEquals(result.get(1), AugmentationSchemaNode2); - } - - @Test - public void augmentationToGenTypesNullPckgNameTest() { - final String augmPackName = null; - final Map.Entry> schemaPathAugmentListEntry = null; - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = null; - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Package Name cannot be NULL.", e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesNullAugSchemaTest() { - final String augmPackName = "pckg.name"; - final Map.Entry> schemaPathAugmentListEntry = null; - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = null; - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Augmentation List Entry cannot be NULL.", e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesNullAugSchemaTargetPathTest() { - final String augmPackName = "pckg.name"; - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - when(augmSchema.getTargetPath()).thenReturn(null); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(null); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = null; - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final IllegalStateException e) { - assertEquals("Augmentation List Entry does not contain Target Path (Target Path is NULL).", e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesNullAugSchemaListTest() { - final String augmPackName = "pckg.name"; - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - final QName qnamePath = QName.create("test", "2017-04-04", "aug"); - final SchemaPath path = SchemaPath.create(true, qnamePath); - when(augmSchema.getTargetPath()).thenReturn(path); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(path); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = null; - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - final Module m = null; - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final IllegalStateException e) { - assertEquals("Augmentation List cannot be empty.", e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesNullAugSchemaTargetNodeTest() { - final String augmPackName = "pckg.name"; - - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - final QName qnamePath = QName.create("test", "2017-04-04", "aug"); - final SchemaPath path = SchemaPath.create(true, qnamePath); - when(augmSchema.getTargetPath()).thenReturn(path); - final Set uses = new HashSet<>(); - when(augmSchema.getUses()).thenReturn(uses); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - AugmentationSchemaNodeList.add(augmSchema); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(path); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = mock(SchemaContext.class); - final Module moduleAug = mock(Module.class); - final DataSchemaNode schNode = null; - when(moduleAug.getDataChildByName(qnamePath)).thenReturn(schNode); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug)); - - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - - final Module m = mock(Module.class); - when(m.getName()).thenReturn("augm-module"); - when(m.getNamespace()).thenReturn(qnamePath.getNamespace()); - when(m.getRevision()).thenReturn(qnamePath.getRevision()); - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("augment target not found: " + path, e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesNullAugTargetGTBTest() { - final String augmPackName = "pckg.name"; - - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - final QName qnamePath = QName.create("test", "2017-04-04", "aug"); - final SchemaPath path = SchemaPath.create(true, qnamePath); - when(augmSchema.getTargetPath()).thenReturn(path); - final Set uses = new HashSet<>(); - when(augmSchema.getUses()).thenReturn(uses); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - AugmentationSchemaNodeList.add(augmSchema); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(path); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = mock(SchemaContext.class); - final Module moduleAug = mock(Module.class); - final DataSchemaNode schNode = mock(DataSchemaNode.class); - when(moduleAug.getDataChildByName(qnamePath)).thenReturn(schNode); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug)); - - final TypeProvider typeProvider = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilders = new HashMap<>(); - - final Module m = mock(Module.class); - when(m.getName()).thenReturn("augm-module"); - when(m.getNamespace()).thenReturn(qnamePath.getNamespace()); - when(m.getRevision()).thenReturn(qnamePath.getRevision()); - - try { - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, m, context, false, genCtx, - genTypeBuilders, typeProvider); - fail(); - } catch (final NullPointerException e) { - assertEquals("Target type not yet generated: " + schNode, e.getMessage()); - } - } - - @Test - public void augmentationToGenTypesTargetChoicSchemaNodeTest() { - final String augmPackName = "pckg.name"; - - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - final QName qnamePath = QName.create("test", "2017-04-04", "aug"); - final SchemaPath path = SchemaPath.create(true, qnamePath); - when(augmSchema.getTargetPath()).thenReturn(path); - final Set uses = new HashSet<>(); - when(augmSchema.getUses()).thenReturn(uses); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - AugmentationSchemaNodeList.add(augmSchema); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(path); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = mock(SchemaContext.class); - final Module moduleAug = mock(Module.class); - final ChoiceSchemaNode targetSchNode = mock(ChoiceSchemaNode.class); - when(targetSchNode.getPath()).thenReturn(path); - when(moduleAug.getDataChildByName(qnamePath)).thenReturn(targetSchNode); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug)); - - final TypeProvider typeProvider = null; - - final Map genCtx = mock(Map.class); - final Collection moduleContexts = new ArrayList<>(); - final ModuleContext mc = new ModuleContext(); - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(augmPackName, "augm", mc); - mc.addChildNodeType(targetSchNode, gtb); - moduleContexts.add(mc); - when(genCtx.values()).thenReturn(moduleContexts); - - final Map> genTypeBuilders = new HashMap<>(); - - final Module m = mock(Module.class); - when(m.getName()).thenReturn("augm-module"); - when(m.getNamespace()).thenReturn(qnamePath.getNamespace()); - when(m.getRevision()).thenReturn(qnamePath.getRevision()); - - final Map result = AugmentToGenType.augmentationToGenTypes(augmPackName, - schemaPathAugmentListEntry, m, context, false, genCtx, genTypeBuilders, typeProvider); - assertNotNull(result); - } - - @Test - public void augmentationToGenTypesTest() { - final String augmPackName = "pckg.name"; - - final AugmentationSchemaNode augmSchema = mock(AugmentationSchemaNode.class); - final QName qnamePath = QName.create("test", "2017-04-04", "aug"); - final SchemaPath path = SchemaPath.create(true, qnamePath); - when(augmSchema.getTargetPath()).thenReturn(path); - final Set uses = new HashSet<>(); - when(augmSchema.getUses()).thenReturn(uses); - final List unknownSchemaNodes = new ArrayList<>(); - when(augmSchema.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes); - - final List AugmentationSchemaNodeList = new ArrayList<>(); - AugmentationSchemaNodeList.add(augmSchema); - final Map.Entry> schemaPathAugmentListEntry = mock(Map.Entry.class); - when(schemaPathAugmentListEntry.getKey()).thenReturn(path); - when(schemaPathAugmentListEntry.getValue()).thenReturn(AugmentationSchemaNodeList); - - final SchemaContext context = mock(SchemaContext.class); - final Module moduleAug = mock(Module.class); - final DerivableSchemaNode targetSchNode = mock(DerivableSchemaNode.class); - when(targetSchNode.getPath()).thenReturn(path); - when(targetSchNode.isAddedByUses()).thenReturn(true); - when(targetSchNode.getQName()).thenReturn(QName.create("test", "2017-04-04", "aug-node")); - when(moduleAug.getDataChildByName(qnamePath)).thenReturn(targetSchNode); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(moduleAug)); - - final TypeProvider typeProvider = null; - - final Map genCtx = new HashMap<>(); - - final Collection moduleContexts = new ArrayList<>(); - final ModuleContext mc = new ModuleContext(); - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(augmPackName, "augm", mc); - mc.addChildNodeType(targetSchNode, gtb); - moduleContexts.add(mc); - genCtx.put(moduleAug, mc); - - final Map> genTypeBuilders = new HashMap<>(); - - when(moduleAug.getName()).thenReturn("augm-module"); - when(moduleAug.getNamespace()).thenReturn(qnamePath.getNamespace()); - when(moduleAug.getRevision()).thenReturn(qnamePath.getRevision()); - - final Map result = - AugmentToGenType.augmentationToGenTypes(augmPackName, schemaPathAugmentListEntry, moduleAug, context, - false, genCtx, genTypeBuilders, typeProvider); - assertNotNull(result); - final ModuleContext moduleContext = result.get(moduleAug); - assertTrue(moduleContext.getAugmentations().get(0).getName().contains("Augm")); - assertEquals("pckg.name.data", moduleContext.getAugmentations().get(0).getPackageName()); - assertTrue(moduleContext.getChildNode(path).getName().contains("Augm")); - assertEquals("pckg.name", moduleContext.getChildNode(path).getPackageName()); - } - - @Test - public void findOriginalTargetFromGroupingNonGroupingTest() { - final Module module = mock(Module.class); - final QName qnamePath = QName.create("test", "2017-04-04", "test"); - final SchemaPath schemaPath = SchemaPath.create(true, qnamePath); - final DataSchemaNode schNode = mock(DataSchemaNode.class); - when(schNode.getPath()).thenReturn(schemaPath); - when(module.getDataChildByName(qnamePath)).thenReturn(schNode); - - final SchemaContext context = mock(SchemaContext.class); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(schemaPath); - - try { - AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Failed to generate code for augment in " + usesNode, e.getMessage()); - } - } - - @Test - public void findOriginalTargetFromGroupingAsUsesFailedTest() { - final Module module = mock(Module.class); - final QName qnamePath = QName.create("test", "2017-04-04", "test"); - final SchemaPath schemaPath = SchemaPath.create(true, qnamePath); - final DataSchemaNode schNode = mock(DataSchemaNode.class); - when(schNode.getPath()).thenReturn(schemaPath); - when(schNode.isAddedByUses()).thenReturn(true); - final Set groupings = new HashSet<>(); - final GroupingDefinition groupingDefinition = mock(GroupingDefinition.class); - when(groupingDefinition.getQName()).thenReturn(qnamePath); - groupings.add(groupingDefinition); - when(groupingDefinition.getDataChildByName(qnamePath)).thenReturn(schNode); - when(module.getGroupings()).thenReturn(groupings); - - final SchemaContext context = mock(SchemaContext.class); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(schemaPath); - - final Object[] args = { }; - try { - AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode); - fail(); - } catch (final IllegalStateException e) { - assertEquals("Failed to generate code for augment in " + usesNode, e.getMessage()); - } - } - - @Test - public void findOriginalTargetFromGroupingReturnNullTest() { - final Module module = mock(Module.class); - final QName qnamePath = QName.create("test", "2017-04-04", "test"); - final SchemaPath schemaPath = SchemaPath.create(true, qnamePath); - final DataSchemaNode schNode = null; - final Set groupings = new HashSet<>(); - final GroupingDefinition groupingDefinition = mock(GroupingDefinition.class); - when(groupingDefinition.getQName()).thenReturn(qnamePath); - groupings.add(groupingDefinition); - when(groupingDefinition.getDataChildByName(qnamePath)).thenReturn(schNode); - when(module.getGroupings()).thenReturn(groupings); - - final SchemaContext context = mock(SchemaContext.class); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(schemaPath); - - final Object[] args = { }; - final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode); - assertEquals(null, result); - } - - @Test - public void findOriginalTargetFromGroupingTest() { - final Module module = mock(Module.class); - final QName qnamePath = QName.create("test", "2017-04-04", "test"); - final SchemaPath schemaPath = SchemaPath.create(true, qnamePath); - final DataSchemaNode schNode = mock(DataSchemaNode.class); - when(schNode.getPath()).thenReturn(schemaPath); - final Set groupings = new HashSet<>(); - final GroupingDefinition groupingDefinition = mock(GroupingDefinition.class); - when(groupingDefinition.getQName()).thenReturn(qnamePath); - groupings.add(groupingDefinition); - final DerivableSchemaNode derivSchNode = mock(DerivableSchemaNode.class); - when(derivSchNode.isAddedByUses()).thenReturn(true); - final Optional optional = Optional.of(schNode); - when(derivSchNode.getOriginal()).thenReturn(optional); - when(groupingDefinition.getDataChildByName(qnamePath)).thenReturn(derivSchNode); - when(module.getGroupings()).thenReturn(groupings); - - final SchemaContext context = mock(SchemaContext.class); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(schemaPath); - - final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode); - assertEquals(schNode, result); - } - - @Test - public void findOriginalTargetFromGroupingChoiceTest() { - final Module module = mock(Module.class); - final QName qnamePath = QName.create("test", "2017-04-04", "test"); - final SchemaPath schemaPath = SchemaPath.create(true, qnamePath); - final ChoiceSchemaNode schNode = mock(ChoiceSchemaNode.class); - when(schNode.getPath()).thenReturn(schemaPath); - final Set groupings = new HashSet<>(); - final GroupingDefinition groupingDefinition = mock(GroupingDefinition.class); - when(groupingDefinition.getQName()).thenReturn(qnamePath); - groupings.add(groupingDefinition); - when(groupingDefinition.getDataChildByName(qnamePath)).thenReturn(schNode); - when(module.getGroupings()).thenReturn(groupings); - - final SchemaContext context = mock(SchemaContext.class); - when(context.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(schemaPath); - - final DataSchemaNode result = AugmentToGenType.findOriginalTargetFromGrouping(context, schemaPath, usesNode); - assertEquals(schNode, result); - } - - @Test - public void generateTypesFromAugmentedChoiceCasesNullPckgNameTest() { - final SchemaContext schemaContext = null; - final Module module = null; - final String pckgName = null; - final GeneratedType targetType = null; - final ChoiceSchemaNode targetNode = null; - final List schemaPathAugmentListEntry = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilder = new HashMap<>(); - - try { - AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType, - targetNode, schemaPathAugmentListEntry, genCtx, false, genTypeBuilder, null, - BindingNamespaceType.Data); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Base Package Name cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateTypesFromAugmentedChoiceCasesNullTargetType() { - final SchemaContext schemaContext = null; - final Module module = null; - final String pckgName = ""; - final GeneratedType targetType = null; - final ChoiceSchemaNode targetNode = null; - final List schemaPathAugmentListEntry = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilder = new HashMap<>(); - - try { - AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType, - targetNode, schemaPathAugmentListEntry, genCtx, false, genTypeBuilder, null, - BindingNamespaceType.Data); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Referenced Choice Type cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateTypesFromAugmentedChoiceCasesNullAugmentNodes() { - final SchemaContext schemaContext = null; - final Module module = null; - final String pckgName = ""; - final GeneratedType targetType = mock(GeneratedType.class); - final ChoiceSchemaNode targetNode = null; - final List schemaPathAugmentListEntry = null; - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilder = new HashMap<>(); - - try { - AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, module, pckgName, targetType, - targetNode, schemaPathAugmentListEntry, genCtx, false, genTypeBuilder, null, - BindingNamespaceType.Data); - fail(); - } catch (final IllegalArgumentException e) { - assertEquals("Set of Choice Case Nodes cannot be NULL.", e.getMessage()); - } - } - - @Test - public void generateTypesFromAugmentedChoiceCasesNullCaseNodeTest() { - final SchemaContext schemaContext = null; - final Module module = null; - final String pckgName = ""; - final GeneratedType targetType = mock(GeneratedType.class); - final ChoiceSchemaNode targetNode = null; - final Set augmentNodes = new HashSet<>(); - final DataSchemaNode caseNode = null; - augmentNodes.add(caseNode); - - final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class); - when(AugmentationSchemaNode.getChildNodes()).thenReturn(augmentNodes); - final List schemaPathAugmentListEntry = new ArrayList<>(); - schemaPathAugmentListEntry.add(AugmentationSchemaNode); - - final Map genCtx = new HashMap<>(); - final Map> genTypeBuilder = new HashMap<>(); - - final Map result = AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, - module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, genCtx, false, - genTypeBuilder, null, BindingNamespaceType.Data); - assertEquals(genCtx, result); - } - - @Test - public void generateTypesFromAugmentedChoiceCasesTest() { - final QName qnamePath = QName.create("test", "2017-04-04", "chcase"); - final QName qnamePath2 = QName.create("test", "2017-04-04", "chcase2"); - final SchemaPath path = SchemaPath.create(true, qnamePath, qnamePath2); - - final SchemaContext schemaContext = mock(SchemaContext.class); - final Module module = mock(Module.class); - when(module.getName()).thenReturn("test-module-case"); - final CaseSchemaNode schemaNode = mock(CaseSchemaNode.class); - when(schemaNode.getPath()).thenReturn(path); - when(module.getDataChildByName(qnamePath)).thenReturn(schemaNode); - when(module.getRevision()).thenReturn(qnamePath.getRevision()); - when(module.getNamespace()).thenReturn(qnamePath.getNamespace()); - final String pckgName = "test.augment.choice.cases"; - final GeneratedType targetType = mock(GeneratedType.class); - when(targetType.getFullyQualifiedName()).thenReturn(Augmentable.class.getName()); - - final Set augmentNodes = new HashSet<>(); - final CaseSchemaNode caseNode = mock(CaseSchemaNode.class); - when(caseNode.getPath()).thenReturn(path); - when(caseNode.getQName()).thenReturn(qnamePath); - when(caseNode.getDescription()).thenReturn(Optional.empty()); - when(caseNode.getReference()).thenReturn(Optional.empty()); - augmentNodes.add(caseNode); - - final AugmentationSchemaNode AugmentationSchemaNode = mock(AugmentationSchemaNode.class); - when(AugmentationSchemaNode.getChildNodes()).thenReturn(augmentNodes); - final List schemaPathAugmentListEntry = new ArrayList<>(); - schemaPathAugmentListEntry.add(AugmentationSchemaNode); - - final ChoiceSchemaNode targetNode = mock(ChoiceSchemaNode.class); - when(targetNode.getPath()).thenReturn(path); - when(targetNode.getDescription()).thenReturn(Optional.empty()); - when(targetNode.getReference()).thenReturn(Optional.empty()); - final Map genCtx = new HashMap<>(); - final ModuleContext moduleContext = new ModuleContext(); - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl(pckgName, "test-case-node-augment", - moduleContext); - when(targetType.getParentTypeForBuilder()).thenReturn(gtb); - genCtx.put(module, moduleContext); - final Map> genTypeBuilder = new HashMap<>(); - - when(schemaContext.findModule(qnamePath.getModule())).thenReturn(Optional.of(module)); - - final Map result = AugmentToGenType.generateTypesFromAugmentedChoiceCases(schemaContext, - module, pckgName, targetType, targetNode, schemaPathAugmentListEntry, genCtx, false, - genTypeBuilder, null, BindingNamespaceType.Data); - assertNotNull(result); - assertEquals(result.get(module), moduleContext); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtilsTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtilsTest.java deleted file mode 100644 index cdd227a746..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/AuxiliaryGenUtilsTest.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode; -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.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.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.type.BooleanTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class AuxiliaryGenUtilsTest { - - @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:illegalThrows", "checkstyle:illegalCatch"}) - @Test(expected = UnsupportedOperationException.class) - public void constructorTest() throws Throwable { - final Constructor constructor = AuxiliaryGenUtils.class.getDeclaredConstructor(); - constructor.setAccessible(true); - try { - constructor.newInstance(); - } catch (final Exception e) { - throw e.getCause(); - } - } - - @Test - public void annotateDeprecatedIfNecessaryNonDepricatedTest() { - final GeneratedTypeBuilderImpl generatedTypeBuilder = - new GeneratedTypeBuilderImpl("test.deprecated", "Non_Deprecated", new ModuleContext()); - final Status status = Status.CURRENT; - - AuxiliaryGenUtils.annotateDeprecatedIfNecessary(status, generatedTypeBuilder); - assertTrue(generatedTypeBuilder.toInstance().getAnnotations().isEmpty()); - } - - @Test - public void annotateDeprecatedIfNecessaryDepricatedTest() { - final GeneratedTypeBuilderImpl generatedTypeBuilder = - new GeneratedTypeBuilderImpl("test.deprecated", "Deprecated", new ModuleContext()); - final Status status = Status.DEPRECATED; - - AuxiliaryGenUtils.annotateDeprecatedIfNecessary(status, generatedTypeBuilder); - assertFalse(generatedTypeBuilder.toInstance().getAnnotations().isEmpty()); - assertEquals("Deprecated", generatedTypeBuilder.toInstance().getAnnotations().get(0).getName()); - } - - @Test - public void hasBuilderClassFalseTest() { - assertEquals(false, hasBuilderClass(LeafSchemaNode.class)); - } - - @Test - public void hasBuilderClassContainerTest() { - assertEquals(true, hasBuilderClass(ContainerSchemaNode.class)); - } - - @Test - public void hasBuilderClassListTest() { - assertEquals(true, hasBuilderClass(ListSchemaNode.class)); - } - - @Test - public void hasBuilderClassRpcTest() { - assertEquals(true, hasBuilderClass(RpcDefinition.class)); - } - - @Test - public void hasBuilderClassNotificationTest() { - assertEquals(true, hasBuilderClass(NotificationDefinition.class)); - } - - @Test - public void qNameConstantTest() { - final GeneratedTypeBuilderBase gtbb = new GeneratedTypeBuilderImpl("test", "qname_constants", - new ModuleContext()); - final String constantName = "ConstantName"; - final QName constantQName = QName.create("urn:constant", "2017-04-06", constantName); - - final Constant result = AuxiliaryGenUtils.qNameConstant(gtbb, constantName, constantQName); - assertEquals(constantName, result.getName()); - } - - @Test - public void constructGetterTest() { - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("test", "Getter_of", new ModuleContext()); - final String schemaNodeName = "schema_node_getter"; - final String comment = null; - final Type returnType = Types.STRING; - final Status status = Status.DEPRECATED; - - final MethodSignatureBuilder result = AuxiliaryGenUtils.constructGetter(gtb, schemaNodeName, comment, - returnType, status); - assertEquals("getSchemaNodeGetter", result.toInstance(returnType).getName()); - } - - @Test - public void getterMethodNameBooleanTest() throws Exception { - assertEquals("isBooleanMethod", AuxiliaryGenUtils.getterMethodName("boolean_method", Types.BOOLEAN)); - } - - @Test - public void getterMethodNameTest() throws Exception { - assertEquals("getClazz", AuxiliaryGenUtils.getterMethodName("clazz", Types.CLASS)); - } - - @Test - public void isNullOrEmptyIsNullTest() { - assertTrue(AuxiliaryGenUtils.isNullOrEmpty(null)); - } - - @Test - public void isNullOrEmptyIsEmptyTest() { - assertTrue(AuxiliaryGenUtils.isNullOrEmpty(new ArrayList<>())); - } - - @Test - public void isNullOrEmptyNotNullNotEmptyTest() { - final Collection list = new ArrayList<>(); - list.add(new Object()); - assertFalse(AuxiliaryGenUtils.isNullOrEmpty(list)); - } - - @Test - public void augGenTypeNameTest() { - final Map builders = new HashMap<>(); - builders.put("genTypeName1", new GeneratedTypeBuilderImpl("pckg.a1", "gen_a_1", new ModuleContext())); - builders.put("genTypeName2", new GeneratedTypeBuilderImpl("pckg.a2", "gen_a_2", new ModuleContext())); - final String genTypeName = "genTypeName"; - assertEquals("genTypeName3", AuxiliaryGenUtils.augGenTypeName(builders, genTypeName)); - } - - @Test - public void getAugmentIdentifierNullTest() { - assertNull(AuxiliaryGenUtils.getAugmentIdentifier(new ArrayList<>())); - } - - @Test - public void getAugmentIdentifierTest() { - final List list = new ArrayList<>(); - final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class); - final QName qname = - QName.create("urn:opendaylight:yang:extension:yang-ext", "2017-10-04", "augment-identifier"); - when(unknownSchemaNode.getNodeType()).thenReturn(qname); - final String value = "node parameter"; - when(unknownSchemaNode.getNodeParameter()).thenReturn(value); - list.add(unknownSchemaNode); - - assertEquals(value, AuxiliaryGenUtils.getAugmentIdentifier(list)); - } - - @Test - public void resolveInnerEnumFromTypeDefinitionNullTest() { - EnumTypeDefinition enumTypeDefinition = null; - final QName qname = null; - final GeneratedTypeBuilder gtb = null; - final Map map = new HashMap<>(); - final Module module = null; - - EnumBuilder result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map, gtb, - module); - assertEquals(null, result); - - enumTypeDefinition = mock(EnumTypeDefinition.class); - result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map, gtb, module); - assertEquals(null, result); - } - - @Test - public void resolveInnerEnumFromTypeDefinitionTest() { - final QName qname = QName.create("urn:enum:test", "2017-12-04", "enum-test"); - final EnumTypeDefinition enumTypeDefinition = mock(EnumTypeDefinition.class); - final QName enumQName = QName.create(qname, "enum-qname-test"); - when(enumTypeDefinition.getQName()).thenReturn(enumQName); - final SchemaPath schemaPath = SchemaPath.create(true, enumQName); - when(enumTypeDefinition.getPath()).thenReturn(schemaPath); - when(enumTypeDefinition.getDescription()).thenReturn(Optional.empty()); - when(enumTypeDefinition.getReference()).thenReturn(Optional.empty()); - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("urn.enum.test.pckg", "enum-test", - new ModuleContext()); - final Map map = new HashMap<>(); - final Module module = mock(Module.class); - final ModuleContext moduleContext = new ModuleContext(); - map.put(module, moduleContext); - - final EnumBuilder result = AuxiliaryGenUtils.resolveInnerEnumFromTypeDefinition(enumTypeDefinition, qname, map, - gtb, module); - assertNotNull(result); - } - - @Test - public void addTOToTypeBuilderNullTest() { - final BooleanTypeDefinition typeDef = mock(BooleanTypeDefinition.class); - final GeneratedTypeBuilder typeBuilder = - new GeneratedTypeBuilderImpl("test.boolean.type.def", "boolean-type-def", new ModuleContext()); - final DataSchemaNode leaf = mock(DataSchemaNode.class); - final QName qnameLeaf = QName.create("urn:leaf:qname:test", "2017-12-04", "leaf-qname-test"); - when(leaf.getQName()).thenReturn(qnameLeaf); - final Module parentModule = mock(Module.class); - final SchemaContext schemaContext = mock(SchemaContext.class); - final Set modules = new HashSet<>(); - when(schemaContext.getModules()).thenReturn(modules); - final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext); - final Map genCtx = new HashMap<>(); - genCtx.put(parentModule, new ModuleContext()); - - final GeneratedTOBuilder result = AuxiliaryGenUtils.addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule, - typeProvider, schemaContext, new ModuleContext(), genCtx); - assertEquals(null, result); - } - - @Test - public void addTOToTypeBuilderUnionTest() { - assertNotNull(addTOToBuilder("/base/test-union.yang")); - } - - @Test - public void addTOToTypeBuilderBitsTest() { - assertNotNull(addTOToBuilder("/base/test-bits.yang")); - } - - private static GeneratedTOBuilder addTOToBuilder(final String yangPath) { - final GeneratedTypeBuilder typeBuilder = new GeneratedTypeBuilderImpl("test.boolean.spc.def", "spec-type-def", - new ModuleContext()); - final SchemaContext schemaContext = YangParserTestUtils.parseYangResource(yangPath); - final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext); - final LeafSchemaNode leafSchemaNode = - (LeafSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next(); - final TypeDefinition> typeDef = leafSchemaNode.getType(); - final Map genCtx = new HashMap<>(); - genCtx.put(schemaContext.getModules().iterator().next(), new ModuleContext()); - - return AuxiliaryGenUtils.addTOToTypeBuilder(typeDef, typeBuilder, leafSchemaNode, - schemaContext.getModules().iterator().next(), typeProvider, schemaContext, new ModuleContext(), genCtx); - } - - @Test - public void createReturnTypeForUnionTest() { - final GeneratedTypeBuilder typeBuilder = new GeneratedTypeBuilderImpl("test.boolean.spc.def", - "spec-type-def", new ModuleContext()); - final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/base/test-union.yang"); - final TypeProviderImpl typeProvider = new TypeProviderImpl(schemaContext); - final LeafSchemaNode leafSchemaNode = - (LeafSchemaNode) schemaContext.getModules().iterator().next().getChildNodes().iterator().next(); - final TypeDefinition> typeDef = leafSchemaNode.getType(); - - final Type result = AuxiliaryGenUtils.createReturnTypeForUnion(addTOToBuilder("/base/test-union.yang"), typeDef, - typeBuilder, schemaContext.getModules().iterator().next(), typeProvider, false); - assertNotNull(result); - } - - @Test - public void isInnerTypeTrueTest() { - final LeafSchemaNode leaf = mock(LeafSchemaNode.class); - final TypeDefinition type = mock(TypeDefinition.class); - final QName qname = QName.create("namespace", "2017-12-04", "localName"); - final SchemaPath path = SchemaPath.create(true, qname); - when(leaf.getPath()).thenReturn(path); - when(type.getPath()).thenReturn(path); - - assertTrue(AuxiliaryGenUtils.isInnerType(leaf, type)); - - final QName qnameParent = QName.create(qname, "qnameParent"); - final SchemaPath parent = SchemaPath.create(true, qname, qnameParent); - when(type.getPath()).thenReturn(parent); - - assertTrue(AuxiliaryGenUtils.isInnerType(leaf, type)); - } - - @Test - public void isInnerTypeFalseTest() { - final LeafSchemaNode leaf = mock(LeafSchemaNode.class); - final TypeDefinition type = mock(TypeDefinition.class); - final QName qname = QName.create("namespace", "2017-12-04", "localName"); - final SchemaPath path = SchemaPath.create(true, qname); - when(leaf.getPath()).thenReturn(path); - - final QName qnameChild = QName.create(qname, "qnameChild"); - final QName qnameParent = QName.create(qname, "qnameParent"); - final SchemaPath parent = SchemaPath.create(true, qnameChild, qnameParent); - - when(type.getPath()).thenReturn(parent); - - assertFalse(AuxiliaryGenUtils.isInnerType(leaf, type)); - } - - @Test - public void resolveListKeyTOBuilderTest() { - final String pckgName = "pckg.name.test"; - final ListSchemaNode list = mock(ListSchemaNode.class); - final List keyDefs = new ArrayList<>(); - final QName qname = QName.create("namespace", "2017-12-04", "localname"); - keyDefs.add(qname); - when(list.getKeyDefinition()).thenReturn(keyDefs); - when(list.getQName()).thenReturn(qname); - - final GeneratedTOBuilder result = AuxiliaryGenUtils.resolveListKeyTOBuilder(pckgName, list, - new ModuleContext()); - assertNotNull(result); - assertEquals("LocalnameKey", result.getName()); - } - - @Test - public void resolveLeafSchemaNodeAsPropertyFalseTest() { - final GeneratedTOBuilder gtob = mock(GeneratedTOBuilder.class); - final LeafSchemaNode leaf = mock(LeafSchemaNode.class); - final boolean isReadOnly = true; - final Type type = null; - - assertFalse(AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty("list", gtob, leaf, type, isReadOnly)); - } - - @Test - public void resolveLeafSchemaNodeAsPropertyTrueTest() { - final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl("pckg.name.gto.tst", "gto_name", true); - final LeafSchemaNode leaf = mock(LeafSchemaNode.class); - when(leaf.getDescription()).thenReturn(Optional.empty()); - when(leaf.getReference()).thenReturn(Optional.empty()); - - final boolean isReadOnly = true; - final Type type = mock(Type.class); - when(leaf.getQName()).thenReturn(QName.create("ns", "2017-12-04", "ln")); - - assertTrue(AuxiliaryGenUtils.resolveLeafSchemaNodeAsProperty("list", gtob, leaf, type, isReadOnly)); - } - - @Test - public void checkModuleAndModuleNameTest() { - final Module module = mock(Module.class); - when(module.getName()).thenReturn("moduleName"); - AuxiliaryGenUtils.checkModuleAndModuleName(module); - } - - private static boolean hasBuilderClass(final Class clazz) { - return AuxiliaryGenUtils.hasBuilderClass(mock(clazz), BindingNamespaceType.Data); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImplTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImplTest.java deleted file mode 100644 index 889ab25f75..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/BindingGeneratorImplTest.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.List; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class BindingGeneratorImplTest { - - @Test - public void genTypesTypeDefTest() throws Exception { - final BindingGeneratorImpl bg = new BindingGeneratorImpl(false); - final SchemaContext schemaContext = YangParserTestUtils.parseYangResource("/generator/test-typedef.yang"); - final List generateTypes = bg.generateTypes(schemaContext); - assertNotNull(generateTypes); - for (final Type genType : generateTypes) { - if (genType.getName().equals("MyInnerCont") && genType.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.rev170206.data.asteriskmy_cont")) { - final GeneratedType gt = (GeneratedType) genType; - for (final MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getMyLeaf2")) { - assertEquals(methodSignature.getReturnType().getName(), "MyType"); - } - } - } - } - } - - @Test - public void generatedTypesEnumTest() throws Exception { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/apple-test.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("Apple") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.apple.rev170503.data")) { - final GeneratedType gt = (GeneratedType) type; - final Enumeration enumeration = gt.getEnumerations().get(0); - assertEquals("Apple1", enumeration.getName()); - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.apple.rev170503.data.Apple", - enumeration.getPackageName()); - assertEquals("apple", enumeration.getValues().get(0).getName()); - assertEquals("APPLE", enumeration.getValues().get(0).getMappedName()); - assertEquals("apple1", enumeration.getValues().get(1).getName()); - assertEquals("APPLE1", enumeration.getValues().get(1).getMappedName()); - } - } - } - - @Test - public void generatedTypesUsesEnumLeafTest() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class, - "/uses-statement/test-uses-leaf-innertype-base.yang", "/uses-statement/test-uses-leaf-innertype.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype.base.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - final MethodSignature methodSignature = gt.getMethodDefinitions().get(0); - assertEquals("ErrorType", methodSignature.getReturnType().getName()); - } - - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - final MethodSignature methodSignature = gt.getMethodDefinitions().get(0); - assertEquals("ErrorType", methodSignature.getReturnType().getName()); - } - } - } - - @Test - public void generatedTypesUsesBitsLeafTest() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class, - "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.base.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafBits")) { - assertEquals("LeafBits", methodSignature.getReturnType().getName()); - } - } - - } - - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafBits")) { - assertEquals("LeafBits", methodSignature.getReturnType().getName()); - } - } - } - } - } - - @Test - public void generatedTypesUsesUnionLeafTest() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class, - "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.base.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafUnion")) { - assertEquals("LeafUnion", methodSignature.getReturnType().getName()); - } - } - - } - - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafUnion")) { - assertEquals("LeafUnion", methodSignature.getReturnType().getName()); - } - } - } - } - } - - @Test - public void generatedTypesUsesLeafTest() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class, - "/uses-statement/test-uses-leaf-innertype2-base.yang", "/uses-statement/test-uses-leaf-innertype2.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.base.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafDecimal64")) { - assertEquals("BigDecimal", methodSignature.getReturnType().getName()); - } - } - - } - - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype2.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getLeafDecimal64")) { - assertEquals("BigDecimal", methodSignature.getReturnType().getName()); - } - } - } - } - } - - @Test - public void generatedTypesUsesLeafInnertype3Test() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResources(BindingGeneratorImplTest.class, - "/uses-statement/test-uses-leaf-innertype3-base.yang", - "/uses-statement/test-uses-leaf-innertype3.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("MyCont") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype3.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getBandwidth")) { - assertEquals("Bandwidth", methodSignature.getReturnType().getName()); - } - } - - } - - if (type.getName().equals("Open") && type.getPackageName() - .equals("org.opendaylight.mdsal.gen.javav2.urn.test.uses.leaf.innertype3.rev170809.data")) { - final GeneratedType gt = (GeneratedType) type; - for (MethodSignature methodSignature : gt.getMethodDefinitions()) { - if (methodSignature.getName().equals("getVersion")) { - assertEquals("ProtocolVersion", methodSignature.getReturnType().getName()); - } - - if (methodSignature.getName().equals("getLeafUnion")) { - assertEquals("LeafUnion", methodSignature.getReturnType().getName()); - } - } - - } - } - } - - @Test - public void generatedTypesTest() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResource("/generator/test-list.yang"); - final List generateTypes = bg.generateTypes(context); - - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - assertEquals(3, generateTypes.size()); - final int[] test_i = { 0 }; - for (final Type t : generateTypes) { - if (t instanceof GeneratedTransferObject) { - final GeneratedTransferObject genTransferObj = (GeneratedTransferObject) t; - assertBaseGeneratedType(genTransferObj, "MyListKey", - "org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list"); - assertEquals(3, genTransferObj.getProperties().size()); - int testJ = 0; - for (final GeneratedProperty generatedProperty : genTransferObj.getProperties()) { - switch (generatedProperty.getName()) { - case "keyReservedWord": - assertEquals("String", generatedProperty.getReturnType().getName()); - testJ++; - break; - case "key1": - assertEquals("String", generatedProperty.getReturnType().getName()); - testJ++; - break; - case "key2": - assertEquals("String", generatedProperty.getReturnType().getName()); - testJ++; - break; - default: - fail(); - } - } - assertEquals(3, testJ); - test_i[0] += 1; - } else { - testActualType((GeneratedType) t, test_i); - } - } - assertEquals(3, test_i[0]); - } - - @Test - public void generateTypesIdentityTest() throws Exception { - final BindingGenerator bg = new BindingGeneratorImpl(true); - final SchemaContext context = YangParserTestUtils.parseYangResourceDirectory("/identity/"); - assertNotNull(context); - - final List generateTypes = bg.generateTypes(context, context.getModules()); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getFullyQualifiedName() - .equals("org.opendaylight.mdsal.gen.javav2.identity3.module.rev170708.ident.Iden1")) { - final GeneratedType genType = (GeneratedType)type; - assertEquals("org.opendaylight.mdsal.gen.javav2.identity3.module.rev170708.ident.Iden2", - genType.getImplements().stream().findFirst().get().getFullyQualifiedName()); - - } - if (type.getFullyQualifiedName() - .equals("org.opendaylight.mdsal.gen.javav2.identity3.module.rev170708.ident.Iden2")) { - final GeneratedType genType = (GeneratedType)type; - assertEquals("org.opendaylight.mdsal.gen.javav2.identity.import_.rev170602.ident.Iden1", - genType.getImplements().stream().findFirst().get().getFullyQualifiedName()); - - } - if (type.getFullyQualifiedName() - .equals("org.opendaylight.mdsal.gen.javav2.identity3.module.rev170708.ident.Iden3")) { - final GeneratedType genType = (GeneratedType)type; - assertEquals("org.opendaylight.mdsal.gen.javav2.identity3.module.rev170708.ident.Iden1", - genType.getImplements().stream().findFirst().get().getFullyQualifiedName()); - - } - if (type.getFullyQualifiedName() - .equals("org.opendaylight.mdsal.gen.javav2.identity4.module.rev180227.ident.Iden3")) { - final GeneratedType genType = (GeneratedType)type; - genType.getImplements().stream().forEach(impl -> { - final String fqn = impl.getFullyQualifiedName(); - assertTrue(fqn.equals( - "org.opendaylight.mdsal.gen.javav2.identity4.module.rev180227.ident.Iden1") - || fqn.equals( - "org.opendaylight.mdsal.gen.javav2.identity4.module.rev180227.ident.Iden2")); - }); - - } - } - } - - private void testActualType(final GeneratedType type, final int[] testI) { - MethodSignature methodSignature = null; - switch (type.getName()) { - case "TestListData": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314", - type.getPackageName()); - methodSignature = type.getMethodDefinitions().get(0); - assertMethod(type, "getMyList", "List", "java.util", methodSignature); - testI[0] += 1; - break; - case "MyListKey": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list", - type.getPackageName()); - methodSignature = type.getMethodDefinitions().get(0); - assertMethod(type, "getKey", "String", "java.lang", methodSignature); - testI[0] += 1; - break; - case "MyListKey1": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list", - type.getPackageName()); - methodSignature = type.getMethodDefinitions().get(0); - assertMethod(type, "getKey1", "String", "java.lang", methodSignature); - testI[0] += 1; - break; - case "MyListKey2": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list", - type.getPackageName()); - methodSignature = type.getMethodDefinitions().get(0); - assertMethod(type, "getKey2", "String", "java.lang", methodSignature); - testI[0] += 1; - break; - case "MyListFoo": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.data.my_list", - type.getPackageName()); - methodSignature = type.getMethodDefinitions().get(0); - assertMethod(type, "getFoo", "String", "java.lang", methodSignature); - testI[0] += 1; - break; - case "MyList": - assertEquals("org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.data", - type.getPackageName()); - assertEquals(5, type.getMethodDefinitions().size()); - int testJ = 0; - for (final MethodSignature m : type.getMethodDefinitions()) { - switch (m.getName()) { - case "getIdentifier": - assertMethod(type, "getIdentifier", "MyListKey", - "org.opendaylight.mdsal.gen.javav2.urn.test.simple.test.list.rev170314.key.my_list", m); - testJ++; - break; - case "getKey1": - assertMethod(type, "getKey1", "String","java.lang", m); - testJ++; - break; - case "getKey2": - assertMethod(type, "getKey2", "String","java.lang", m); - testJ++; - break; - case "getFoo": - assertMethod(type, "getFoo", "String","java.lang", m); - testJ++; - break; - case "getKeyReservedWord": - assertMethod(type, "getKeyReservedWord", "String","java.lang", m); - testJ++; - break; - default: - fail(); - } - } - assertEquals(5, testJ); - testI[0] += 1; - break; - default: - fail(); - } - } - - private static void assertBaseGeneratedType(final GeneratedType genType, final String name, - final String packageName) { - assertEquals(name, genType.getName()); - - } - - private static void assertMethod(final GeneratedType definingTypeExpected, final String nameExpected, - final String typeNameExpected, final String typePackageNameExpected, - final MethodSignature methodSignature) { - assertEquals(definingTypeExpected, methodSignature.getDefiningType()); - assertEquals(nameExpected, methodSignature.getName()); - assertEquals(typeNameExpected, methodSignature.getReturnType().getName()); - assertEquals(typePackageNameExpected, methodSignature.getReturnType().getPackageName()); - } - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8542Test.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8542Test.java deleted file mode 100644 index 71ef89cb1b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8542Test.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class Bug8542Test { - @Test - public void testBug8542() { - final BindingGenerator bg = new BindingGeneratorImpl(false); - final SchemaContext context = YangParserTestUtils.parseYangResource("/bug-8542/recursive-uses-augment.yang"); - final List generateTypes = bg.generateTypes(context); - assertNotNull(generateTypes); - assertTrue(!generateTypes.isEmpty()); - for (final Type type : generateTypes) { - if (type.getName().equals("A11")) { - assertEquals("org.opendaylight.mdsal.gen.javav2.yang.test.uses.augment.recursive.rev170519.data.d", - type.getPackageName()); - } else if (type.getName().equals("B11")) { - assertEquals("org.opendaylight.mdsal.gen.javav2.yang.test.uses.augment.recursive.rev170519.data.d.a1", - type.getPackageName()); - } else if (type.getName().equals("C11")) { - assertEquals( - "org.opendaylight.mdsal.gen.javav2.yang.test.uses.augment.recursive.rev170519.data.d.a1.b1", - type.getPackageName()); - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8575Test.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8575Test.java deleted file mode 100644 index c5b7493534..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/Bug8575Test.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import org.junit.Test; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.UsesNode; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class Bug8575Test { - @Test - public void bug8575Test() throws Exception { - final Class[] parameterTypes = { SchemaContext.class, SchemaPath.class, UsesNode.class }; - final Method generate = - AugmentToGenType.class.getDeclaredMethod("findOriginalTargetFromGrouping", parameterTypes); - assertNotNull(generate); - generate.setAccessible(true); - - SchemaContext context = YangParserTestUtils.parseYangResource("/bug-8575/foo.yang"); - - final QName groupingQname = QName.create("foo", "2017-05-15", "A"); - final QName containerQname = QName.create("foo", "2017-05-15", "A1"); - final SchemaPath groupingPath = SchemaPath.create(true, groupingQname); - final SchemaPath targetPath = SchemaPath.create(true, containerQname); - - final UsesNode usesNode = mock(UsesNode.class); - when(usesNode.getGroupingPath()).thenReturn(groupingPath); - - final Object[] args = { context, targetPath, usesNode }; - final DataSchemaNode result = (DataSchemaNode) generate.invoke(AugmentToGenType.class, args); - assertNotNull(result); - assertTrue(result instanceof ContainerSchemaNode); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategyTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategyTest.java deleted file mode 100644 index 1b411a2a3a..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/GeneratedClassLoadingStrategyTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; - -public class GeneratedClassLoadingStrategyTest { - - @Test - public void loadClassTest() throws Exception { - final Dummy dummy = new Dummy(); - final GeneratedTypeBuilder gtb = new GeneratedTypeBuilderImpl("test", "dummy", new ModuleContext()); - final Class loadClass = dummy.loadClass(gtb.toInstance()); - Assert.assertNotNull(loadClass); - } - - private class Dummy extends GeneratedClassLoadingStrategy { - - @Override - public Class loadClass(final String fqcn) throws ClassNotFoundException { - return Object.class; - } - - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelperTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelperTest.java deleted file mode 100644 index daf174db68..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/RpcActionGenHelperTest.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import org.junit.Ignore; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.ActionDefinition; -import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer; -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.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.SchemaPath; -import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode; - -public class RpcActionGenHelperTest { - // Bridge for method references - @FunctionalInterface - private interface GeneratorMethod { - Map generate(Module module, Map genCtx, - SchemaContext schemaContext, boolean verboseClassComments, - Map> genTypeBuilders, TypeProvider typeProvider); - } - - @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:illegalThrows", "checkstyle:illegalCatch"}) - @Test(expected = UnsupportedOperationException.class) - public void constructorTest() throws Throwable { - final Constructor constructor = RpcActionGenHelper.class.getDeclaredConstructor(); - constructor.setAccessible(true); - try { - constructor.newInstance(); - } catch (final Exception e) { - throw e.getCause(); - } - } - - @Test - public void getRoutingContextAbsentTest() { - final DataSchemaNode dataSchemaNode = mock(DataSchemaNode.class); - final List unknownSchemaNodes = new ArrayList<>(); - when(dataSchemaNode.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes); - - final Optional result = RpcActionGenHelper.getRoutingContext(dataSchemaNode); - assertNotNull(result); - assertTrue(!result.isPresent()); - } - - @Test - public void getRoutingContextTest() { - final DataSchemaNode dataSchemaNode = mock(DataSchemaNode.class); - final List unknownSchemaNodes = new ArrayList<>(); - final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class); - when(unknownSchemaNode.getNodeType()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE); - final QName qname = QName.create("test", "2017-05-04", "unknown"); - when(unknownSchemaNode.getQName()).thenReturn(qname); - unknownSchemaNodes.add(unknownSchemaNode); - when(dataSchemaNode.getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes); - - final Optional result = RpcActionGenHelper.getRoutingContext(dataSchemaNode); - assertNotNull(result); - assertTrue(result.isPresent()); - assertEquals(qname, result.get()); - } - - @Ignore - @Test - public void actionMethodsToGenTypeContainerAsParentTest() { - actionMethodsToGenType(ContainerSchemaNode.class, false); - } - - @Ignore - @Test - public void actionMethodsToGenTypeListAsParentTest() { - actionMethodsToGenType(ListSchemaNode.class, false); - } - - @Test(expected = IllegalStateException.class) - public void rpcMethodsToGenTypeNullRpcsTest() { - final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test"); - - final Module module = mock(Module.class); - when(module.getName()).thenReturn("module-name"); - when(module.getRevision()).thenReturn(rpcQName.getRevision()); - when(module.getNamespace()).thenReturn(rpcQName.getNamespace()); - when(module.getRpcs()).thenReturn(null); - - final Map genCtx = new HashMap<>(); - final SchemaContext schemaContext = mock(SchemaContext.class); - final boolean verboseClassComments = false; - final Map> genTypeBuilders = new HashMap<>(); - final TypeProvider typeProvider = mock(TypeProvider.class); - - RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, - typeProvider); - } - - @Test - public void rpcMethodsToGenTypeEmptyRpcsTest() { - final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test"); - - final Module module = mock(Module.class); - when(module.getName()).thenReturn("module-name"); - when(module.getRevision()).thenReturn(rpcQName.getRevision()); - when(module.getNamespace()).thenReturn(rpcQName.getNamespace()); - final Set rpcs = new HashSet<>(); - when(module.getRpcs()).thenReturn(rpcs); - - final Map genCtx = new HashMap<>(); - final SchemaContext schemaContext = mock(SchemaContext.class); - final boolean verboseClassComments = false; - final Map> genTypeBuilders = new HashMap<>(); - final TypeProvider typeProvider = mock(TypeProvider.class); - - final Map result = RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider); - assertNotNull(result); - } - - @Test - public void rpcMethodsToGenTypeRoutedRpcTest() { - actionMethodsToGenType(ContainerSchemaNode.class, true); - } - - @Test - public void rpcMethodsToGenTypeRpcTest() { - final QName rpcQName = QName.create("test.rpc", "2017-05-04", "rpc-test"); - - final ContainerSchemaNode rpcParent = mock(ContainerSchemaNode.class); - final QName rpcParentQName = QName.create(rpcQName, "rpc-parent"); - when(rpcParent.getQName()).thenReturn(rpcParentQName); - - final Module module = mock(Module.class); - when(module.getName()).thenReturn("module-name"); - when(module.getRevision()).thenReturn(rpcQName.getRevision()); - when(module.getNamespace()).thenReturn(rpcQName.getNamespace()); - when(module.getDescription()).thenReturn(Optional.empty()); - when(module.getReference()).thenReturn(Optional.empty()); - final Set rpcs = new HashSet<>(); - final RpcDefinition rpcDefinition = mock(RpcDefinition.class); - when(rpcDefinition.getDescription()).thenReturn(Optional.empty()); - when(rpcDefinition.getReference()).thenReturn(Optional.empty()); - final SchemaPath rpcPath = SchemaPath.create(true, rpcParentQName, rpcQName); - when(rpcDefinition.getPath()).thenReturn(rpcPath); - when(rpcDefinition.getQName()).thenReturn(rpcQName); - - when(module.getDataChildByName(rpcParentQName)).thenReturn(rpcParent); - rpcs.add(rpcDefinition); - when(module.getRpcs()).thenReturn(rpcs); - - final ContainerSchemaNode input = mock(ContainerSchemaNode.class); - final QName qnameInput = QName.create(rpcQName, "rpc-input"); - final SchemaPath inputSchemaPath = SchemaPath.create(true, rpcQName, qnameInput); - when(input.getQName()).thenReturn(qnameInput); - when(input.getPath()).thenReturn(inputSchemaPath); - when(input.getDescription()).thenReturn(Optional.empty()); - when(input.getReference()).thenReturn(Optional.empty()); - - when(rpcDefinition.getInput()).thenReturn(input); - - final ContainerSchemaNode output = mock(ContainerSchemaNode.class); - final QName qnameOutput = QName.create(rpcQName, "rpc-output"); - final SchemaPath outputSchemaPath = SchemaPath.create(true, rpcQName, qnameOutput); - when(output.getQName()).thenReturn(qnameOutput); - when(output.getPath()).thenReturn(outputSchemaPath); - when(output.getDescription()).thenReturn(Optional.empty()); - when(output.getReference()).thenReturn(Optional.empty()); - when(rpcDefinition.getOutput()).thenReturn(output); - - final Map genCtx = new HashMap<>(); - final ModuleContext moduleContext = new ModuleContext(); - genCtx.put(module, moduleContext); - - final SchemaContext schemaContext = mock(SchemaContext.class); - when(schemaContext.findModule(rpcQName.getModule())).thenReturn(Optional.of(module)); - - final boolean verboseClassComments = false; - final Map> genTypeBuilders = new HashMap<>(); - final TypeProvider typeProvider = mock(TypeProvider.class); - - final Map result = RpcActionGenHelper.rpcMethodsToGenType(module, genCtx, schemaContext, - verboseClassComments, genTypeBuilders, typeProvider); - assertNotNull(result); - } - - private static void actionMethodsToGenType(final Class clazz, - final boolean isRoutedRpc) { - final GeneratorMethod generate; - if (isRoutedRpc) { - generate = RpcActionGenHelper::rpcMethodsToGenType; - } else { - generate = RpcActionGenHelper::actionMethodsToGenType; - } - - final QName actionQName = QName.create("test.action", "2017-05-04", "action-test"); - - final Module module = mock(Module.class); - when(module.getName()).thenReturn("module-name"); - when(module.getRevision()).thenReturn(actionQName.getRevision()); - when(module.getNamespace()).thenReturn(actionQName.getNamespace()); - when(module.getDescription()).thenReturn(Optional.empty()); - when(module.getReference()).thenReturn(Optional.empty()); - - final Collection childNodes = new ArrayList<>(); - final T actionNodeContainer = mock(clazz); - final QName actionParentQName = QName.create(actionQName, "action-parent"); - final SchemaPath actionParentPath = SchemaPath.create(true, actionParentQName); - when(((SchemaNode) actionNodeContainer).getPath()).thenReturn(actionParentPath); - when(((SchemaNode) actionNodeContainer).getQName()).thenReturn(actionParentQName); - if (clazz == ListSchemaNode.class) { - final List keyQNames = new ArrayList<>(); - keyQNames.add(QName.create(actionParentQName, "keyActions")); - when(((ListSchemaNode) actionNodeContainer).getKeyDefinition()).thenReturn(keyQNames); - } - - final Set actions = new HashSet<>(); - - final ActionDefinition actionDefinition = mock(ActionDefinition.class); - when(actionDefinition.getQName()).thenReturn(actionQName); - final SchemaPath actionPath = SchemaPath.create(true, actionQName); - when(actionDefinition.getPath()).thenReturn(actionPath); - when(actionDefinition.getDescription()).thenReturn(Optional.empty()); - when(actionDefinition.getReference()).thenReturn(Optional.empty()); - - final ContainerSchemaNode input = mock(ContainerSchemaNode.class); - final QName qnameInput = QName.create(actionQName, "action-input"); - final SchemaPath inputSchemaPath = SchemaPath.create(true, actionQName, qnameInput); - when(input.getQName()).thenReturn(qnameInput); - when(input.getPath()).thenReturn(inputSchemaPath); - when(input.getDescription()).thenReturn(Optional.empty()); - when(input.getReference()).thenReturn(Optional.empty()); - when(actionDefinition.getInput()).thenReturn(input); - - final ContainerSchemaNode output = mock(ContainerSchemaNode.class); - final QName qnameOutput = QName.create(actionQName, "action-output"); - final SchemaPath outputSchemaPath = SchemaPath.create(true, actionQName, qnameOutput); - when(output.getQName()).thenReturn(qnameOutput); - when(output.getPath()).thenReturn(outputSchemaPath); - when(output.getDescription()).thenReturn(Optional.empty()); - when(output.getReference()).thenReturn(Optional.empty()); - when(actionDefinition.getOutput()).thenReturn(output); - - actions.add(actionDefinition); - when(actionNodeContainer.getActions()).thenReturn(actions); - childNodes.add((DataSchemaNode) actionNodeContainer); - when(module.getChildNodes()).thenReturn(childNodes); - - final Map genCtx = new HashMap<>(); - final ModuleContext moduleContext = new ModuleContext(); - genCtx.put(module, moduleContext); - - final SchemaContext schemaContext = mock(SchemaContext.class); - when(schemaContext.findModule(actionQName.getModule())).thenReturn(Optional.of(module)); - - final boolean verboseClassComments = false; - final Map> genTypeBuilders = new HashMap<>(); - final TypeProvider typeProvider = mock(TypeProvider.class); - - if (isRoutedRpc) { - final Set rpcs = new HashSet<>(); - final RpcDefinition rpcDef = mock(RpcDefinition.class); - when(rpcDef.getPath()).thenReturn(outputSchemaPath); - when(rpcDef.getQName()).thenReturn(qnameOutput); - when(rpcDef.getDescription()).thenReturn(Optional.empty()); - when(rpcDef.getReference()).thenReturn(Optional.empty()); - - when(module.getDataChildByName(actionQName)).thenReturn((ContainerSchemaNode) actionNodeContainer); - final List unknownSchemaNodes = new ArrayList<>(); - final UnknownSchemaNode unknownSchemaNode = mock(UnknownSchemaNode.class); - when(unknownSchemaNode.getNodeType()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE); - when(unknownSchemaNode.getQName()).thenReturn(RpcActionGenHelper.CONTEXT_REFERENCE); - unknownSchemaNodes.add(unknownSchemaNode); - when(((DataSchemaNode) actionNodeContainer).getUnknownSchemaNodes()).thenReturn(unknownSchemaNodes); - when(rpcDef.getInput()).thenReturn(input); - when(rpcDef.getOutput()).thenReturn(output); - rpcs.add(rpcDef); - when(module.getRpcs()).thenReturn(rpcs); - } - - final Map result = generate.generate(module, genCtx, schemaContext, verboseClassComments, - genTypeBuilders, typeProvider); - assertNotNull(result); - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/UnionTypeDefTest.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/UnionTypeDefTest.java deleted file mode 100644 index 73f76670b7..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/UnionTypeDefTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.impl; - -import static junit.framework.TestCase.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import java.util.List; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class UnionTypeDefTest { - - @Test - public void unionTypeResolvingTest() { - final SchemaContext context = YangParserTestUtils.parseYangResources(UnionTypeDefTest.class, - "/union-test-models/abstract-topology.yang", "/ietf/ietf-inet-types.yang"); - - assertNotNull("context is null", context); - final BindingGenerator bindingGen = new BindingGeneratorImpl(true); - final List genTypes = bindingGen.generateTypes(context); - - assertNotNull("genTypes is null", genTypes); - assertFalse("genTypes is empty", genTypes.isEmpty()); - - // TODO: implement test - } - - @Test - public void unionTypedefLeafrefTest() { - final SchemaContext schemaContext = YangParserTestUtils.parseYangResource( - "/leafref_typedef_union/bug8449.yang"); - assertNotNull(schemaContext); - final List generateTypes = new BindingGeneratorImpl(false).generateTypes(schemaContext); - assertNotNull(generateTypes); - for (final Type type : generateTypes) { - if (type.getName().equals("Cont")) { - final GeneratedType gt = (GeneratedType) type; - assertNotNull(gt); - final GeneratedType refType = gt.getEnclosedTypes().iterator().next(); - for (final GeneratedProperty generatedProperty : refType.getProperties()) { - switch (generatedProperty.getName()) { - case "stringRefValue": - assertEquals(Types.STRING, generatedProperty.getReturnType()); - break; - case "value": - assertEquals(Types.CHAR_ARRAY, generatedProperty.getReturnType()); - break; - default: - break; - } - } - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallInput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallInput.java deleted file mode 100644 index 74f25cbaac..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallInput.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * action my-action-call input. - */ -public interface MyActionCallInput extends Input, Instantiable, TreeNode { - - @Override - Class implementedInterface(); - - String getV1(); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallOutput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallOutput.java deleted file mode 100644 index 2158dd3b5c..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionCallOutput.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * action my-action-call output. - */ -public interface MyActionCallOutput extends Output, Instantiable, TreeNode { - - @Override - Class implementedInterface(); - - String getV2(); - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionModuleMyActionCallAction.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionModuleMyActionCallAction.java deleted file mode 100644 index 441c8b04a3..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyActionModuleMyActionCallAction.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; - -/** - * It represents following YANG snippet: - * - *

- * module my-action-module { - * - *

- * container my-cont { - * action my-action-call { - * - *

- * input { - * leaf v1 { - * type string; - * } - * } - * - *

- * output { - * leaf v2 { - * type string - * } - * } - * } - * } - * }. - */ -public interface MyActionModuleMyActionCallAction extends Action, MyActionCallInput, - MyActionCallOutput> { - - @Override - void invoke(MyActionCallInput input, InstanceIdentifier ii, RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyCont.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyCont.java deleted file mode 100644 index dcbee86ebe..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/action/examples/MyCont.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; - -/** - * container my-cont. - */ -public interface MyCont extends TreeNode, Augmentable { -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallInput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallInput.java deleted file mode 100644 index e1ab4f298e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallInput.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.list.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * action list-action-call input. - */ -public interface ListActionCallInput extends Input, Instantiable, TreeNode { - - @Override - Class implementedInterface(); - - String getV1(); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallOutput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallOutput.java deleted file mode 100644 index 1868b3911e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionCallOutput.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.list.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * action list-action-call output. - */ -public interface ListActionCallOutput extends Output, Instantiable, - TreeNode { - - @Override - Class implementedInterface(); - - String getV2(); - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionModuleListActionCall.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionModuleListActionCall.java deleted file mode 100644 index 2fe0cf1631..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/ListActionModuleListActionCall.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.list.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.KeyedInstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.ListAction; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; - -/** - * It represents following YANG snippet: - * - *

- * module list-action-module { - * - *

- * list my-list { - * action list-action-call { - * - *

- * input { - * leaf v1 { - * type string; - * } - * } - * - *

- * output { - * leaf v2 { - * type string - * } - * } - * } - * } - * }. - */ -public interface ListActionModuleListActionCall extends ListAction { - - @Override - void invoke(ListActionCallInput input, KeyedInstanceIdentifier kii, - RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyList.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyList.java deleted file mode 100644 index 3b3a9a02e9..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyList.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.list.action.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * list my-list. - */ -public interface MyList extends TreeNode, Augmentable, Identifiable { -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyListKey.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyListKey.java deleted file mode 100644 index eb67a1fe6b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/list/action/examples/MyListKey.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2018 ZTE Corp. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.list.action.examples; - -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * key of list my-list. - */ -public class MyListKey implements Identifier { - - @Override - public boolean equals(Object obj) { - return false; - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return null; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallInput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallInput.java deleted file mode 100644 index 6c5c85893b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallInput.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.rpc.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * rpc my-call input. - */ -public interface MyCallInput extends Input, Instantiable, TreeNode { - - @Override - Class implementedInterface(); - - String getV1(); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallOutput.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallOutput.java deleted file mode 100644 index 75b40d0e8d..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyCallOutput.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.rpc.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * rpc my-call output. - */ -public interface MyCallOutput extends Output, Instantiable, TreeNode { - - @Override - Class implementedInterface(); - - String getV2(); - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyModuleMyCallRpc.java b/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyModuleMyCallRpc.java deleted file mode 100644 index 5a56df08ae..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/impl/rpc/examples/MyModuleMyCallRpc.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.impl.rpc.examples; - -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; - -/** - * It represents following YANG snippet: - * - *

- * module my-module { - * - *

- * rpc my-call { - * - *

- * input { - * leaf v1 { - * type string; - * } - * } - * - *

- * output { - * leaf v2 { - * type string - * } - * } - * } - * }. - */ -public interface MyModuleMyCallRpc extends Rpc { - - @Override - void invoke(MyCallInput input, RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/anydata/test-anydata.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/anydata/test-anydata.yang deleted file mode 100644 index e6b2897734..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/anydata/test-anydata.yang +++ /dev/null @@ -1,24 +0,0 @@ -module test-anydata { - yang-version 1.1; - - namespace "urn:test:simple:test:anydata"; - prefix test; - organization "test.org"; - revision "2017-06-08"; - - container .my-cont { - container my-inner-cont { - leaf my-leaf { - type string; - } - - anydata inner-anydata { - description "I am data schema node anydata"; - } - } - } - - anydata root-anydata { - description "I am root anydata"; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/anyxml/test-anyxml.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/anyxml/test-anyxml.yang deleted file mode 100644 index a9567374f2..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/anyxml/test-anyxml.yang +++ /dev/null @@ -1,24 +0,0 @@ -module test-anyxml { - yang-version 1; - - namespace "urn:test:simple:test:anyxml"; - prefix test; - organization "test.org"; - revision "2017-06-07"; - - container .my-cont { - container my-inner-cont { - leaf my-leaf { - type string; - } - - anyxml inner-anyxml { - description "I am data schema node anyxml"; - } - } - } - - anyxml root-anyxml { - description "I am root anyxml"; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-choice-case.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-choice-case.yang deleted file mode 100644 index c167d79f3d..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-choice-case.yang +++ /dev/null @@ -1,140 +0,0 @@ -module test-augment-choice-case { - yang-version 1; - namespace "urn:test:augment:choice:case"; - prefix "augtestchoice"; - - revision "2014-3-13" { - description - "Initial revision"; - } - - - container container { - choice ch2{} - choice ch3{ - case c3 { - leaf c3Leaf { - type string; - } - } - } - } - - augment "/container/" { - leaf augLeaf { - type string; - } - } - - augment "/container/" { - choice ch{} - } - - augment "/container/ch/" { - case c1 { - leaf c1Leaf { - type string; - } - } - - leaf c12 { - type string; - } - } - augment "/container/ch/c1/" { - leaf c1Leaf_AnotherAugment { - type string; - } - - choice deepChoice{} - } - - augment "/container/ch3/" { - case c32 { - leaf c32Leaf { - type string; - } - } - - leaf c34LeafS { - type string; - } - } - - - augment "/container/ch/c1/deepChoice/" { - case deepCase1 { - leaf deepLeafc1 { - type string; - } - } - case deepCase2 { - leaf deepLeafc2 { - type string; - } - } - } - - augment "/container/ch2/" { - case c2 { - leaf c2Leaf { - type string; - } - - choice c2DeepChoice { - case c2DeepChoiceCase1 { - leaf c2DeepChoiceCase1Leaf1 { - type string; - } - } - case c2DeepChoiceCase2 { - leaf c2DeepChoiceCase1Leaf2 { - type string; - } - } - } - } - } - - augment "/container/ch2/" { - leaf c22Leaf { - type string; - } - } - - augment "/container" { - /*ext:augment-identifier top-choice-augment1;*/ - choice augment-choice1 { - case case1 { - container case1-container { - leaf case1-leaf { - type string; - } - } - } - - case case2 { - container case2-container { - leaf case2-leaf { - type string; - } - } - } - } - } - - augment "/container/augment-choice1/case1" { - /*ext:augment-identifier top-choice-augment2;*/ - choice augment-choice2 { - case case11 { - container case11-choice-case-container { - leaf case11-choice-case-leaf { - type string; - } - } - } - } - } - - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-identifier.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-identifier.yang deleted file mode 100644 index f3a34d67d5..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-identifier.yang +++ /dev/null @@ -1,39 +0,0 @@ -module augment-identifier-test { - prefix "foo"; - namespace "org.test.augment.identifier"; - - import yang-ext { - prefix ext; - } - - container foo1 { - leaf my-leaf { - type string; - } - } - - augment /foo:foo1 { - leaf bar { - type string; - } - } - - augment /foo:foo1 { - leaf baz { - type string; - } - } - container foo2 { - leaf foo2-leaf { - type string; - } - } - - augment /foo:foo2 { - ext:augment-identifier i-am-new-identifier; - - leaf aug-foo2-leaf { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses-grouping.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses-grouping.yang deleted file mode 100644 index 2bee56afdb..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses-grouping.yang +++ /dev/null @@ -1,38 +0,0 @@ -module augment-test-uses-grouping { - prefix "foo"; - namespace "org.test.augment.uses.grouping"; - - container foo1 { - leaf my-leaf { - type string; - } - } - - augment /foo:foo1 { - uses grp { - augment my-cont { - leaf my-uses-grp-leaf { - type string; - } - } - } - - leaf bar { - type string; - } - } - - augment /foo:foo1 { - leaf baz { - type string; - } - } - - grouping grp { - container my-cont { - leaf my-grp-leaf { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses.yang deleted file mode 100644 index fec47e0ce8..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment-uses.yang +++ /dev/null @@ -1,29 +0,0 @@ -module augment-test-uses { - prefix "foo"; - namespace "org.test.augment.uses"; - - container foo1 { - leaf my-leaf { - type string; - } - } - - augment /foo:foo1 { - uses grp; - leaf bar { - type string; - } - } - - augment /foo:foo1 { - leaf baz { - type string; - } - } - - grouping grp { - leaf my-grp-leaf { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment.yang deleted file mode 100644 index a23619af46..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/augment-group/test-augment.yang +++ /dev/null @@ -1,22 +0,0 @@ -module augment-test { - prefix "foo"; - namespace "org.test.augment"; - - container foo1 { - leaf my-leaf { - type string; - } - } - - augment /foo:foo1 { - leaf bar { - type string; - } - } - - augment /foo:foo1 { - leaf baz { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-bits.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-bits.yang deleted file mode 100644 index 652a2822d1..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-bits.yang +++ /dev/null @@ -1,26 +0,0 @@ -module test-bits-module { - yang-version 1.1; - - namespace "urn:test:simple:bits"; - prefix tlfb; - revision "2017-03-14"; - - typedef mybits-type { - type bits { - bit disable-nagle { - position 0; - } - bit auto-sense-speed { - position 1; - } - bit ten-mb-only { - position 2; - } - } - } - - leaf mybits { - type mybits-type; - default "auto-sense-speed"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-leaf-with-description.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-leaf-with-description.yang deleted file mode 100644 index 54f9d11873..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-leaf-with-description.yang +++ /dev/null @@ -1,13 +0,0 @@ -module test-lesf-with-description-module { - yang-version 1.1; - - namespace "urn:test:simple:test:leaf"; - prefix tlf; - organization "leaf.list.org"; - revision "2017-03-14"; - - leaf foo { - type string; - description "I am leaf."; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-module.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-module.yang deleted file mode 100644 index bb34dabd34..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-module.yang +++ /dev/null @@ -1,10 +0,0 @@ -module test-module { - yang-version 1.1; - - namespace "urn:test:base:module"; - prefix test-base-module; - organization "test.org.base.module"; - revision "2017-04-06"; - - description "Base test module description"; -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-rpc-and-notification.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-rpc-and-notification.yang deleted file mode 100644 index d04dfd063b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-rpc-and-notification.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-rpc-and-notification-module { - yang-version 1; - namespace "urn:base:test-rpc-and-notification"; - prefix base-test-rpc-and-notification; - organization "yang-test-rpc-and-notification"; - revision "2017-04-06"; - - rpc my-rpc { - input { - leaf in { - type string; - } - } - - output { - leaf out { - type string; - } - } - } - - notification my-notification { - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-union.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-union.yang deleted file mode 100644 index 8752d837c9..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/test-union.yang +++ /dev/null @@ -1,18 +0,0 @@ -module test-union-module { - yang-version 1.1; - - namespace "urn:test:simple:union"; - prefix tlfb; - organization "leaf.union.org"; - revision "2017-03-14"; - - leaf foo { - type union { - type int32; - type enumeration { - enum "en"; - } - } - description "I am leaf."; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-import.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-import.yang deleted file mode 100644 index ac7c31b2fa..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-import.yang +++ /dev/null @@ -1,11 +0,0 @@ -module test-import { - - yang-version 1; - namespace "urn:test:simple:test:import"; - prefix "test-import"; - - revision 2017-04-21; - - container *my-import-%cont { - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-typedef-with-import.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-typedef-with-import.yang deleted file mode 100644 index a8e18bad46..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/base/with_import/test-typedef-with-import.yang +++ /dev/null @@ -1,17 +0,0 @@ -module test { - - yang-version 1; - namespace "urn:test:simple:test"; - prefix "test"; - - import test-import { prefix "imported-test"; revision-date 2017-04-21; } - - revision 2017-02-06; - - typedef my-type { - type int8; - } - - container .my-cont { - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8542/recursive-uses-augment.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8542/recursive-uses-augment.yang deleted file mode 100644 index e223a9aea7..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8542/recursive-uses-augment.yang +++ /dev/null @@ -1,53 +0,0 @@ -module recursive-uses-augment { - - namespace "yang:test:uses-augment-recursive"; - prefix ruses; - - revision 2017-05-19; - - container my-cont { - uses D; - } - - grouping A { - container A1 { - leaf leaf-A1 { - type string; - } - } - } - - grouping B { - container B1 { - leaf leaf-B1 { - type string; - } - } - } - - grouping C { - container C1 { - leaf leaf-C1 { - type string; - } - } - } - - grouping D { - uses "A" { - augment "A1" { - uses B { - augment "B1" { - uses C { - augment "C1" { - leaf D-aug-C1 { - type string; - } - } - } - } - } - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8575/foo.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8575/foo.yang deleted file mode 100644 index 8e53633191..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/bug-8575/foo.yang +++ /dev/null @@ -1,21 +0,0 @@ -module foo { - - namespace "foo"; - prefix foo; - - revision 2017-05-15; - - grouping A{ - container A1 { - leaf leaf-A-A1 { - type string; - } - } - } - - container A{ - leaf leaf-A { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice-case-choice.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice-case-choice.yang deleted file mode 100644 index 7968e40e12..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice-case-choice.yang +++ /dev/null @@ -1,94 +0,0 @@ -module test-choice-case-choice { - yang-version 1.1; - namespace "urn:opendaylight:params:xml:ns:yang:test:choice:case:choice"; - prefix "test-ccc"; - revision "2017-07-20" { - } - - list sub-tlvs { - choice range-sub-tlv { - case sid-label-tlv-case { - choice sid-label-index { - case ipv6-address-case { - } - case local-label-case { - } - case sid-case { - } - } - } - case prefix-sid-tlv-case { - choice flags { - case isis-prefix-flags-case { - } - case ospf-prefix-flags-case { - } - } - choice sid-label-index { - case ipv6-address-case { - } - case local-label-case { - } - case sid-case { - } - } - } - case binding-sid-tlv-case { - choice flags { - case ospf-binding-flags-case { - } - case isis-binding-flags-case { - } - } - list binding-sub-tlvs { - choice binding-sub-tlv { - case ero-metric-case { - } - case ipv6-ero-case { - } - case ipv4-ero-backup-case { - } - case prefix-sid-case { - choice flags { - case isis-prefix-flags-case { - } - case ospf-prefix-flags-case { - } - } - choice sid-label-index { - case ipv6-address-case { - } - case local-label-case { - } - case sid-case { - } - } - } - case sid-label-case { - choice sid-label-index { - case ipv6-address-case { - } - case local-label-case { - } - case sid-case { - } - } - } - case ipv6-prefix-sid-case { - } - case ipv4-ero-case { - } - case unnumbered-interface-id-backup-ero-case { - } - case ipv6-ero-backup-case { - } - case unnumbered-interface-id-ero-case { - } - } - } - } - case ipv6-prefix-sid-tlv-case { - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice.yang deleted file mode 100644 index e2e7e804b5..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/choice/test-choice.yang +++ /dev/null @@ -1,29 +0,0 @@ -module test-choice { - yang-version 1; - namespace "org.test.choice"; - prefix "tstch"; - - container food { - choice snack { - case sports-arena { - leaf pretzel { - type empty; - } - - leaf beer { - type empty; - } - } - - case late-night { - leaf chocolate { - type enumeration { - enum dark; - enum milk; - enum first-available; - } - } - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/apple-test.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/apple-test.yang deleted file mode 100644 index b2c4e77c74..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/apple-test.yang +++ /dev/null @@ -1,21 +0,0 @@ -module test-apple { - - yang-version 1; - namespace "urn:test:simple:apple"; - prefix "test-apple"; - - revision 2017-05-03; - - container apple { - leaf apple { - type enumeration { - enum apple { - value 0 ; - } - enum apple1 { - value 1 ; - } - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/my-rpc-module.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/my-rpc-module.yang deleted file mode 100644 index 8c7b6c6a39..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/my-rpc-module.yang +++ /dev/null @@ -1,21 +0,0 @@ -module my-rpc-module { - yang-version 1; - namespace "urn:my-rpc-module:simple:test"; - prefix my-rpc-module; - organization "yang-positive-smurfs"; - revision "2017-03-24"; - - rpc my-call { - input { - leaf v1 { - type string; - } - } - - output { - leaf v2 { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-augment.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-augment.yang deleted file mode 100644 index 8ce495fb0c..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-augment.yang +++ /dev/null @@ -1,17 +0,0 @@ -module test-augment { - yang-version 1; - - namespace "urn:test:simple:test"; - prefix test; - organization "test.org"; - revision "2017-02-06"; - - container my-cont { - } - - augment "/my-cont" { - leaf augment-leaf { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-cont.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-cont.yang deleted file mode 100644 index 85163beee6..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-cont.yang +++ /dev/null @@ -1,13 +0,0 @@ -module test-cont { - yang-version 1; - - namespace "urn:test:simple:test:cont"; - prefix test-cont; - organization "test.cont.org"; - revision "2017-02-17"; - - container my-cont { - container my-inner-cont { - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-leaf.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-leaf.yang deleted file mode 100644 index 8c5d18607e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-leaf.yang +++ /dev/null @@ -1,12 +0,0 @@ -module test-lesf-module { - yang-version 1.1; - - namespace "urn:test:simple:test:leaf"; - prefix tlf; - organization "leaf.list.org"; - revision "2017-03-14"; - - leaf foo { - type string; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-list.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-list.yang deleted file mode 100644 index d593441ffb..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-list.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-list { - yang-version 1.1; - - namespace "urn:test:simple:test:list"; - prefix test-list; - organization "test.list.org"; - revision "2017-03-14"; - - list my-list { - key "key key1 key2"; - leaf key{ - type string; - } - leaf key1 { - type string; - } - leaf key2 { - type string; - } - leaf foo{ - type string; - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-type.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-type.yang deleted file mode 100644 index 6579dbea11..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-type.yang +++ /dev/null @@ -1,13 +0,0 @@ -module test-type { - yang-version 1; - - namespace "urn:test:simple:test:type"; - prefix test-type; - organization "test.type.org"; - revision "2017-02-09"; - - typedef my-type { - type string; - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-typedef.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-typedef.yang deleted file mode 100644 index 59cd7ee929..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-typedef.yang +++ /dev/null @@ -1,38 +0,0 @@ -module test { - yang-version 1; - - namespace "urn:test:simple:test"; - prefix test; - organization "test.org"; - revision "2017-02-06"; - - typedef my-type { - type int8; - } - - container _.my-cont { - container my-inner-cont { - leaf my-leaf { - type string; - } - - leaf my-leaf2 { - type my-type; - } - } - } - - container my-union-cont { - leaf my-union-leaf { - type union { - type int8; - type int16; - } - } - } - - grouping my-grouping { - container _.my-cont { - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-union.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-union.yang deleted file mode 100644 index 57bd08d4f6..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test-union.yang +++ /dev/null @@ -1,16 +0,0 @@ -module test-union { - yang-version 1; - - namespace "urn:test:simple:test:union"; - prefix test-union; - organization "test.union.org"; - revision "2017-03-08"; - - typedef my-union { - type union { - type int32; - type string; - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test.yang deleted file mode 100644 index b31c46b0de..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/generator/test.yang +++ /dev/null @@ -1,11 +0,0 @@ -module test { - yang-version 1; - - namespace "urn:test:simple:test"; - prefix test; - organization "test.org"; - revision "2017-02-06"; - - container _.my-cont { - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity-import.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity-import.yang deleted file mode 100644 index 50ff3594a1..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity-import.yang +++ /dev/null @@ -1,11 +0,0 @@ -module identity-import { - yang-version 1.1; - namespace "identity:import"; - - prefix "ideimp"; - - revision 2017-06-02; - - identity iden1 { - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity.yang deleted file mode 100644 index 1a3a5fa119..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity.yang +++ /dev/null @@ -1,27 +0,0 @@ -module identity-module { - yang-version 1.1; - namespace "identity:module"; - - prefix "idemod"; - - revision 2017-06-01; - - import identity-import { - prefix "ideimp"; - } - - identity iden1 { - } - - identity iden2 { - base "idemod:iden1"; - } - - identity iden3 { - base "ideimp:iden1"; - } - - identity iden4 { - base "idemod:iden2"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity2.yang deleted file mode 100644 index 686244d521..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity2.yang +++ /dev/null @@ -1,15 +0,0 @@ -module identity2-module { - yang-version 1.1; - namespace "identity2:module"; - - prefix "ide2mod"; - - revision 2017-06-02; - - identity iden1 { - } - - identity iden2 { - base "ide2mod:iden1"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity3.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity3.yang deleted file mode 100644 index 0baf326eeb..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity3.yang +++ /dev/null @@ -1,25 +0,0 @@ -module identity3-module { - yang-version 1.1; - namespace "identity3:module"; - - prefix "ide3mod"; - - revision 2017-07-08; - - import identity-import { - prefix "ideimp"; - } - - identity iden1 { - base iden2; - } - - identity iden2 { - base "ideimp:iden1"; - } - - identity iden3 { - base iden1; - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity4.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity4.yang deleted file mode 100644 index c88cd061fa..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/identity/identity4.yang +++ /dev/null @@ -1,24 +0,0 @@ -module identity4-module { - yang-version 1.1; - namespace "identity4:module"; - - prefix "ide4mod"; - - revision 2018-02-27; - - identity iden1 { - } - - identity iden2 { - - } - - identity iden3 { - base iden1; - base iden2; - } - - identity iden4 { - base iden3; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/iana-if-type.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/iana-if-type.yang deleted file mode 100644 index a7fa137a7e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/iana-if-type.yang +++ /dev/null @@ -1,1516 +0,0 @@ -module iana-if-type { - namespace "urn:ietf:params:xml:ns:yang:iana-if-type"; - prefix ianaift; - - organization "IANA"; - contact - " Internet Assigned Numbers Authority - - Postal: ICANN - 4676 Admiralty Way, Suite 330 - Marina del Rey, CA 90292 - - Tel: +1 310 823 9358 - E-Mail: iana&iana.org"; - description - "This YANG module defines the iana-if-type typedef, which - contains YANG definitions 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. - - Copyright (c) 2011 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 XXXX; see - the RFC itself for full legal notices."; - // RFC Ed.: replace XXXX with actual RFC number and remove this - // note. - - // RFC Ed.: update the date below with the date of RFC publication - // and remove this note. - revision 2012-06-05 { - description - "Initial revision."; - reference - "RFC XXXX: TITLE"; - } - - typedef iana-if-type { - type enumeration { - enum "other" { - value 1; - description - "None of the following"; - } - enum "regular1822" { - value 2; - } - enum "hdh1822" { - value 3; - } - enum "ddnX25" { - value 4; - } - enum "rfc877x25" { - value 5; - reference - "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer"; - } - enum "ethernetCsmacd" { - value 6; - description - "For all ethernet-like interfaces, regardless of speed, - as per RFC3635."; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "iso88023Csmacd" { - value 7; - status deprecated; - description - "Deprecated via RFC3635. - Use ethernetCsmacd(6) instead."; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "iso88024TokenBus" { - value 8; - } - enum "iso88025TokenRing" { - value 9; - } - enum "iso88026Man" { - value 10; - } - enum "starLan" { - value 11; - status deprecated; - description - "Deprecated via RFC3635. - Use ethernetCsmacd(6) instead."; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "proteon10Mbit" { - value 12; - } - enum "proteon80Mbit" { - value 13; - } - enum "hyperchannel" { - value 14; - } - enum "fddi" { - value 15; - reference - "RFC 1512 - FDDI Management Information Base"; - } - enum "lapb" { - value 16; - reference - "RFC 1381 - SNMP MIB Extension for X.25 LAPB"; - } - enum "sdlc" { - value 17; - } - enum "ds1" { - value 18; - description - "DS1-MIB"; - reference - "RFC 4805 - Definitions of Managed Objects for the - DS1, J1, E1, DS2, and E2 Interface Types"; - } - enum "e1" { - value 19; - status obsolete; - description - "Obsolete see DS1-MIB"; - reference - "RFC 4805 - Definitions of Managed Objects for the - DS1, J1, E1, DS2, and E2 Interface Types"; - } - enum "basicISDN" { - value 20; - description - "see also RFC2127"; - } - enum "primaryISDN" { - value 21; - } - enum "propPointToPointSerial" { - value 22; - description - "proprietary serial"; - } - enum "ppp" { - value 23; - } - enum "softwareLoopback" { - value 24; - } - enum "eon" { - value 25; - description - "CLNP over IP"; - } - enum "ethernet3Mbit" { - value 26; - } - enum "nsip" { - value 27; - description - "XNS over IP"; - } - enum "slip" { - value 28; - description - "generic SLIP"; - } - enum "ultra" { - value 29; - description - "ULTRA technologies"; - } - enum "ds3" { - value 30; - description - "DS3-MIB"; - reference - "RFC 3896 - Definitions of Managed Objects for the - DS3/E3 Interface Type"; - } - enum "sip" { - value 31; - description - "SMDS, coffee"; - reference - "RFC 1694 - Definitions of Managed Objects for SMDS - Interfaces using SMIv2"; - } - enum "frameRelay" { - value 32; - description - "DTE only."; - reference - "RFC 2115 - Management Information Base for Frame Relay - DTEs Using SMIv2"; - } - enum "rs232" { - value 33; - reference - "RFC 1659 - Definitions of Managed Objects for RS-232-like - Hardware Devices using SMIv2"; - } - enum "para" { - value 34; - description - "parallel-port"; - reference - "RFC 1660 - Definitions of Managed Objects for - Parallel-printer-like Hardware Devices using - SMIv2"; - } - enum "arcnet" { - value 35; - description - "arcnet"; - } - enum "arcnetPlus" { - value 36; - description - "arcnet plus"; - } - enum "atm" { - value 37; - description - "ATM cells"; - } - enum "miox25" { - value 38; - reference - "RFC 1461 - SNMP MIB extension for Multiprotocol - Interconnect over X.25"; - } - enum "sonet" { - value 39; - description - "SONET or SDH"; - } - enum "x25ple" { - value 40; - reference - "RFC 2127 - ISDN Management Information Base using SMIv2"; - } - enum "iso88022llc" { - value 41; - } - enum "localTalk" { - value 42; - } - enum "smdsDxi" { - value 43; - } - enum "frameRelayService" { - value 44; - description - "FRNETSERV-MIB"; - reference - "RFC 2954 - Definitions of Managed Objects for Frame - Relay Service"; - } - enum "v35" { - value 45; - } - enum "hssi" { - value 46; - } - enum "hippi" { - value 47; - } - enum "modem" { - value 48; - description - "Generic modem"; - } - enum "aal5" { - value 49; - description - "AAL5 over ATM"; - } - enum "sonetPath" { - value 50; - } - enum "sonetVT" { - value 51; - } - enum "smdsIcip" { - value 52; - description - "SMDS InterCarrier Interface"; - } - enum "propVirtual" { - value 53; - description - "proprietary virtual/internal"; - reference - "RFC 2863 - The Interfaces Group MIB"; - } - enum "propMultiplexor" { - value 54; - description - "proprietary multiplexing"; - reference - "RFC 2863 - The Interfaces Group MIB"; - } - enum "ieee80212" { - value 55; - description - "100BaseVG"; - } - enum "fibreChannel" { - value 56; - description - "Fibre Channel"; - } - enum "hippiInterface" { - value 57; - description - "HIPPI interfaces"; - } - enum "frameRelayInterconnect" { - value 58; - status obsolete; - description - "Obsolete use either - frameRelay(32) or frameRelayService(44)."; - } - enum "aflane8023" { - value 59; - description - "ATM Emulated LAN for 802.3"; - } - enum "aflane8025" { - value 60; - description - "ATM Emulated LAN for 802.5"; - } - enum "cctEmul" { - value 61; - description - "ATM Emulated circuit"; - } - enum "fastEther" { - value 62; - status deprecated; - description - "Obsoleted via RFC3635. - ethernetCsmacd(6) should be used instead"; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "isdn" { - value 63; - description - "ISDN and X.25"; - reference - "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN - in the Packet Mode"; - } - enum "v11" { - value 64; - description - "CCITT V.11/X.21"; - } - enum "v36" { - value 65; - description - "CCITT V.36"; - } - enum "g703at64k" { - value 66; - description - "CCITT G703 at 64Kbps"; - } - enum "g703at2mb" { - value 67; - status obsolete; - description - "Obsolete see DS1-MIB"; - } - enum "qllc" { - value 68; - description - "SNA QLLC"; - } - enum "fastEtherFX" { - value 69; - status deprecated; - description - "Obsoleted via RFC3635 - ethernetCsmacd(6) should be used instead"; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "channel" { - value 70; - description - "channel"; - } - enum "ieee80211" { - value 71; - description - "radio spread spectrum"; - } - enum "ibm370parChan" { - value 72; - description - "IBM System 360/370 OEMI Channel"; - } - enum "escon" { - value 73; - description - "IBM Enterprise Systems Connection"; - } - enum "dlsw" { - value 74; - description - "Data Link Switching"; - } - enum "isdns" { - value 75; - description - "ISDN S/T interface"; - } - enum "isdnu" { - value 76; - description - "ISDN U interface"; - } - enum "lapd" { - value 77; - description - "Link Access Protocol D"; - } - enum "ipSwitch" { - value 78; - description - "IP Switching Objects"; - } - enum "rsrb" { - value 79; - description - "Remote Source Route Bridging"; - } - enum "atmLogical" { - value 80; - description - "ATM Logical Port"; - reference - "RFC 3606 - Definitions of Supplemental Managed Objects - for ATM Interface"; - } - enum "ds0" { - value 81; - description - "Digital Signal Level 0"; - reference - "RFC 2494 - Definitions of Managed Objects for the DS0 - and DS0 Bundle Interface Type"; - } - enum "ds0Bundle" { - value 82; - description - "group of ds0s on the same ds1"; - reference - "RFC 2494 - Definitions of Managed Objects for the DS0 - and DS0 Bundle Interface Type"; - } - enum "bsc" { - value 83; - description - "Bisynchronous Protocol"; - } - enum "async" { - value 84; - description - "Asynchronous Protocol"; - } - enum "cnr" { - value 85; - description - "Combat Net Radio"; - } - enum "iso88025Dtr" { - value 86; - description - "ISO 802.5r DTR"; - } - enum "eplrs" { - value 87; - description - "Ext Pos Loc Report Sys"; - } - enum "arap" { - value 88; - description - "Appletalk Remote Access Protocol"; - } - enum "propCnls" { - value 89; - description - "Proprietary Connectionless Protocol"; - } - enum "hostPad" { - value 90; - description - "CCITT-ITU X.29 PAD Protocol"; - } - enum "termPad" { - value 91; - description - "CCITT-ITU X.3 PAD Facility"; - } - enum "frameRelayMPI" { - value 92; - description - "Multiproto Interconnect over FR"; - } - enum "x213" { - value 93; - description - "CCITT-ITU X213"; - } - enum "adsl" { - value 94; - description - "Asymmetric Digital Subscriber Loop"; - } - enum "radsl" { - value 95; - description - "Rate-Adapt. Digital Subscriber Loop"; - } - enum "sdsl" { - value 96; - description - "Symmetric Digital Subscriber Loop"; - } - enum "vdsl" { - value 97; - description - "Very H-Speed Digital Subscrib. Loop"; - } - enum "iso88025CRFPInt" { - value 98; - description - "ISO 802.5 CRFP"; - } - enum "myrinet" { - value 99; - description - "Myricom Myrinet"; - } - enum "voiceEM" { - value 100; - description - "voice recEive and transMit"; - } - enum "voiceFXO" { - value 101; - description - "voice Foreign Exchange Office"; - } - enum "voiceFXS" { - value 102; - description - "voice Foreign Exchange Station"; - } - enum "voiceEncap" { - value 103; - description - "voice encapsulation"; - } - enum "voiceOverIp" { - value 104; - description - "voice over IP encapsulation"; - } - enum "atmDxi" { - value 105; - description - "ATM DXI"; - } - enum "atmFuni" { - value 106; - description - "ATM FUNI"; - } - enum "atmIma" { - value 107; - description - "ATM IMA"; - } - enum "pppMultilinkBundle" { - value 108; - description - "PPP Multilink Bundle"; - } - enum "ipOverCdlc" { - value 109; - description - "IBM ipOverCdlc"; - } - enum "ipOverClaw" { - value 110; - description - "IBM Common Link Access to Workstn"; - } - enum "stackToStack" { - value 111; - description - "IBM stackToStack"; - } - enum "virtualIpAddress" { - value 112; - description - "IBM VIPA"; - } - enum "mpc" { - value 113; - description - "IBM multi-protocol channel support"; - } - enum "ipOverAtm" { - value 114; - description - "IBM ipOverAtm"; - reference - "RFC 2320 - Definitions of Managed Objects for Classical IP - and ARP Over ATM Using SMIv2 (IPOA-MIB)"; - } - enum "iso88025Fiber" { - value 115; - description - "ISO 802.5j Fiber Token Ring"; - } - enum "tdlc" { - value 116; - description - "IBM twinaxial data link control"; - } - enum "gigabitEthernet" { - value 117; - status deprecated; - description - "Obsoleted via RFC3635 - ethernetCsmacd(6) should be used instead"; - reference - "RFC 3635 - Definitions of Managed Objects for the - Ethernet-like Interface Types."; - } - enum "hdlc" { - value 118; - description - "HDLC"; - } - enum "lapf" { - value 119; - description - "LAP F"; - } - enum "v37" { - value 120; - description - "V.37"; - } - enum "x25mlp" { - value 121; - description - "Multi-Link Protocol"; - } - enum "x25huntGroup" { - value 122; - description - "X25 Hunt Group"; - } - enum "transpHdlc" { - value 123; - description - "Transp HDLC"; - } - enum "interleave" { - value 124; - description - "Interleave channel"; - } - enum "fast" { - value 125; - description - "Fast channel"; - } - enum "ip" { - value 126; - description - "IP (for APPN HPR in IP networks)"; - } - enum "docsCableMaclayer" { - value 127; - description - "CATV Mac Layer"; - } - enum "docsCableDownstream" { - value 128; - description - "CATV Downstream interface"; - } - enum "docsCableUpstream" { - value 129; - description - "CATV Upstream interface"; - } - enum "a12MppSwitch" { - value 130; - description - "Avalon Parallel Processor"; - } - enum "tunnel" { - value 131; - description - "Encapsulation interface"; - } - enum "coffee" { - value 132; - description - "coffee pot"; - reference - "RFC 2325 - Coffee MIB"; - } - enum "ces" { - value 133; - description - "Circuit Emulation Service"; - } - enum "atmSubInterface" { - value 134; - description - "ATM Sub Interface"; - } - enum "l2vlan" { - value 135; - description - "Layer 2 Virtual LAN using 802.1Q"; - } - enum "l3ipvlan" { - value 136; - description - "Layer 3 Virtual LAN using IP"; - } - enum "l3ipxvlan" { - value 137; - description - "Layer 3 Virtual LAN using IPX"; - } - enum "digitalPowerline" { - value 138; - description - "IP over Power Lines"; - } - enum "mediaMailOverIp" { - value 139; - description - "Multimedia Mail over IP"; - } - enum "dtm" { - value 140; - description - "Dynamic syncronous Transfer Mode"; - } - enum "dcn" { - value 141; - description - "Data Communications Network"; - } - enum "ipForward" { - value 142; - description - "IP Forwarding Interface"; - } - enum "msdsl" { - value 143; - description - "Multi-rate Symmetric DSL"; - } - enum "ieee1394" { - value 144; - description - "IEEE1394 High Performance Serial Bus"; - } - enum "if-gsn" { - value 145; - description - "HIPPI-6400"; - } - enum "dvbRccMacLayer" { - value 146; - description - "DVB-RCC MAC Layer"; - } - enum "dvbRccDownstream" { - value 147; - description - "DVB-RCC Downstream Channel"; - } - enum "dvbRccUpstream" { - value 148; - description - "DVB-RCC Upstream Channel"; - } - enum "atmVirtual" { - value 149; - description - "ATM Virtual Interface"; - } - enum "mplsTunnel" { - value 150; - description - "MPLS Tunnel Virtual Interface"; - } - enum "srp" { - value 151; - description - "Spatial Reuse Protocol "; - } - enum "voiceOverAtm" { - value 152; - description - "Voice Over ATM"; - } - enum "voiceOverFrameRelay" { - value 153; - description - "Voice Over Frame Relay"; - } - enum "idsl" { - value 154; - description - "Digital Subscriber Loop over ISDN"; - } - enum "compositeLink" { - value 155; - description - "Avici Composite Link Interface"; - } - enum "ss7SigLink" { - value 156; - description - "SS7 Signaling Link"; - } - enum "propWirelessP2P" { - value 157; - description - "Prop. P2P wireless interface"; - } - enum "frForward" { - value 158; - description - "Frame Forward Interface"; - } - enum "rfc1483" { - value 159; - description - "Multiprotocol over ATM AAL5"; - reference - "RFC 1483 - Multiprotocol Encapsulation over ATM - Adaptation Layer 5"; - } - enum "usb" { - value 160; - description - "USB Interface"; - } - enum "ieee8023adLag" { - value 161; - description - "IEEE 802.3ad Link Aggregate"; - } - enum "bgppolicyaccounting" { - value 162; - description - "BGP Policy Accounting"; - } - enum "frf16MfrBundle" { - value 163; - description - "FRF .16 Multilink Frame Relay"; - } - enum "h323Gatekeeper" { - value 164; - description - "H323 Gatekeeper"; - } - enum "h323Proxy" { - value 165; - description - "H323 Voice and Video Proxy"; - } - enum "mpls" { - value 166; - description - "MPLS"; - } - enum "mfSigLink" { - value 167; - description - "Multi-frequency signaling link"; - } - enum "hdsl2" { - value 168; - description - "High Bit-Rate DSL - 2nd generation"; - } - enum "shdsl" { - value 169; - description - "Multirate HDSL2"; - } - enum "ds1FDL" { - value 170; - description - "Facility Data Link 4Kbps on a DS1"; - } - enum "pos" { - value 171; - description - "Packet over SONET/SDH Interface"; - } - enum "dvbAsiIn" { - value 172; - description - "DVB-ASI Input"; - } - enum "dvbAsiOut" { - value 173; - description - "DVB-ASI Output"; - } - enum "plc" { - value 174; - description - "Power Line Communtications"; - } - enum "nfas" { - value 175; - description - "Non Facility Associated Signaling"; - } - enum "tr008" { - value 176; - description - "TR008"; - } - enum "gr303RDT" { - value 177; - description - "Remote Digital Terminal"; - } - enum "gr303IDT" { - value 178; - description - "Integrated Digital Terminal"; - } - enum "isup" { - value 179; - description - "ISUP"; - } - enum "propDocsWirelessMaclayer" { - value 180; - description - "Cisco proprietary Maclayer"; - } - enum "propDocsWirelessDownstream" { - value 181; - description - "Cisco proprietary Downstream"; - } - enum "propDocsWirelessUpstream" { - value 182; - description - "Cisco proprietary Upstream"; - } - enum "hiperlan2" { - value 183; - description - "HIPERLAN Type 2 Radio Interface"; - } - enum "propBWAp2Mp" { - value 184; - 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."; - } - enum "sonetOverheadChannel" { - value 185; - description - "SONET Overhead Channel"; - } - enum "digitalWrapperOverheadChannel" { - value 186; - description - "Digital Wrapper"; - } - enum "aal2" { - value 187; - description - "ATM adaptation layer 2"; - } - enum "radioMAC" { - value 188; - description - "MAC layer over radio links"; - } - enum "atmRadio" { - value 189; - description - "ATM over radio links"; - } - enum "imt" { - value 190; - description - "Inter Machine Trunks"; - } - enum "mvl" { - value 191; - description - "Multiple Virtual Lines DSL"; - } - enum "reachDSL" { - value 192; - description - "Long Reach DSL"; - } - enum "frDlciEndPt" { - value 193; - description - "Frame Relay DLCI End Point"; - } - enum "atmVciEndPt" { - value 194; - description - "ATM VCI End Point"; - } - enum "opticalChannel" { - value 195; - description - "Optical Channel"; - } - enum "opticalTransport" { - value 196; - description - "Optical Transport"; - } - enum "propAtm" { - value 197; - description - "Proprietary ATM"; - } - enum "voiceOverCable" { - value 198; - description - "Voice Over Cable Interface"; - } - enum "infiniband" { - value 199; - description - "Infiniband"; - } - enum "teLink" { - value 200; - description - "TE Link"; - } - enum "q2931" { - value 201; - description - "Q.2931"; - } - enum "virtualTg" { - value 202; - description - "Virtual Trunk Group"; - } - enum "sipTg" { - value 203; - description - "SIP Trunk Group"; - } - enum "sipSig" { - value 204; - description - "SIP Signaling"; - } - enum "docsCableUpstreamChannel" { - value 205; - description - "CATV Upstream Channel"; - } - enum "econet" { - value 206; - description - "Acorn Econet"; - } - enum "pon155" { - value 207; - description - "FSAN 155Mb Symetrical PON interface"; - } - enum "pon622" { - value 208; - description - "FSAN622Mb Symetrical PON interface"; - } - enum "bridge" { - value 209; - description - "Transparent bridge interface"; - } - enum "linegroup" { - value 210; - description - "Interface common to multiple lines"; - } - enum "voiceEMFGD" { - value 211; - description - "voice E&M Feature Group D"; - } - enum "voiceFGDEANA" { - value 212; - description - "voice FGD Exchange Access North American"; - } - enum "voiceDID" { - value 213; - description - "voice Direct Inward Dialing"; - } - enum "mpegTransport" { - value 214; - description - "MPEG transport interface"; - } - enum "sixToFour" { - value 215; - status deprecated; - description - "6to4 interface (DEPRECATED)"; - reference - "RFC 4087 - IP Tunnel MIB"; - } - enum "gtp" { - value 216; - description - "GTP (GPRS Tunneling Protocol)"; - } - enum "pdnEtherLoop1" { - value 217; - description - "Paradyne EtherLoop 1"; - } - enum "pdnEtherLoop2" { - value 218; - description - "Paradyne EtherLoop 2"; - } - enum "opticalChannelGroup" { - value 219; - description - "Optical Channel Group"; - } - enum "homepna" { - value 220; - description - "HomePNA ITU-T G.989"; - } - enum "gfp" { - value 221; - description - "Generic Framing Procedure (GFP)"; - } - enum "ciscoISLvlan" { - value 222; - description - "Layer 2 Virtual LAN using Cisco ISL"; - } - enum "actelisMetaLOOP" { - value 223; - description - "Acteleis proprietary MetaLOOP High Speed Link"; - } - enum "fcipLink" { - value 224; - description - "FCIP Link"; - } - enum "rpr" { - value 225; - description - "Resilient Packet Ring Interface Type"; - } - enum "qam" { - value 226; - description - "RF Qam Interface"; - } - enum "lmp" { - value 227; - description - "Link Management Protocol"; - reference - "RFC 4327 - Link Management Protocol (LMP) Management - Information Base (MIB)"; - } - enum "cblVectaStar" { - value 228; - description - "Cambridge Broadband Networks Limited VectaStar"; - } - enum "docsCableMCmtsDownstream" { - value 229; - description - "CATV Modular CMTS Downstream Interface"; - } - enum "adsl2" { - value 230; - 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)"; - } - enum "macSecControlledIF" { - value 231; - description - "MACSecControlled"; - } - enum "macSecUncontrolledIF" { - value 232; - description - "MACSecUncontrolled"; - } - enum "aviciOpticalEther" { - value 233; - description - "Avici Optical Ethernet Aggregate"; - } - enum "atmbond" { - value 234; - description - "atmbond"; - } - enum "voiceFGDOS" { - value 235; - description - "voice FGD Operator Services"; - } - enum "mocaVersion1" { - value 236; - description - "MultiMedia over Coax Alliance (MoCA) Interface - as documented in information provided privately to IANA"; - } - enum "ieee80216WMAN" { - value 237; - description - "IEEE 802.16 WMAN interface"; - } - enum "adsl2plus" { - value 238; - description - "Asymmetric Digital Subscriber Loop Version 2, - Version 2 Plus and all variants"; - } - enum "dvbRcsMacLayer" { - value 239; - description - "DVB-RCS MAC Layer"; - reference - "RFC 5728 - The SatLabs Group DVB-RCS MIB"; - } - enum "dvbTdm" { - value 240; - description - "DVB Satellite TDM"; - reference - "RFC 5728 - The SatLabs Group DVB-RCS MIB"; - } - enum "dvbRcsTdma" { - value 241; - description - "DVB-RCS TDMA"; - reference - "RFC 5728 - The SatLabs Group DVB-RCS MIB"; - } - enum "x86Laps" { - value 242; - description - "LAPS based on ITU-T X.86/Y.1323"; - } - enum "wwanPP" { - value 243; - description - "3GPP WWAN"; - } - enum "wwanPP2" { - value 244; - description - "3GPP2 WWAN"; - } - enum "voiceEBS" { - value 245; - description - "voice P-phone EBS physical interface"; - } - enum "ifPwType" { - value 246; - description - "Pseudowire interface type"; - reference - "RFC 5601 - Pseudowire (PW) Management Information Base"; - } - enum "ilan" { - value 247; - description - "Internal LAN on a bridge per IEEE 802.1ap"; - } - enum "pip" { - value 248; - description - "Provider Instance Port on a bridge per IEEE 802.1ah PBB"; - } - enum "aluELP" { - value 249; - description - "Alcatel-Lucent Ethernet Link Protection"; - } - enum "gpon" { - value 250; - description - "Gigabit-capable passive optical networks (G-PON) as per - ITU-T G.948"; - } - enum "vdsl2" { - value 251; - 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)"; - } - enum "capwapDot11Profile" { - value 252; - description - "WLAN Profile Interface"; - reference - "RFC 5834 - Control and Provisioning of Wireless Access - Points (CAPWAP) Protocol Binding MIB for - IEEE 802.11"; - } - enum "capwapDot11Bss" { - value 253; - description - "WLAN BSS Interface"; - reference - "RFC 5834 - Control and Provisioning of Wireless Access - Points (CAPWAP) Protocol Binding MIB for - IEEE 802.11"; - } - enum "capwapWtpVirtualRadio" { - value 254; - description - "WTP Virtual Radio Interface"; - reference - "RFC 5833 - Control and Provisioning of Wireless Access - Points (CAPWAP) Protocol Base MIB"; - } - enum "bits" { - value 255; - description - "bitsport"; - } - enum "docsCableUpstreamRfPort" { - value 256; - description - "DOCSIS CATV Upstream RF Port"; - } - enum "cableDownstreamRfPort" { - value 257; - description - "CATV downstream RF port"; - } - enum "vmwareVirtualNic" { - value 258; - description - "VMware Virtual Network Interface"; - } - enum "ieee802154" { - value 259; - description - "IEEE 802.15.4 WPAN interface"; - reference - "IEEE 802.15.4-2006"; - } - enum "otnOdu" { - value 260; - description - "OTN Optical Data Unit"; - } - enum "otnOtu" { - value 261; - description - "OTN Optical channel Transport Unit"; - } - enum "ifVfiType" { - value 262; - description - "VPLS Forwarding Instance Interface Type"; - } - enum "g9981" { - value 263; - description - "G.998.1 bonded interface"; - } - enum "g9982" { - value 264; - description - "G.998.2 bonded interface"; - } - enum "g9983" { - value 265; - description - "G.998.3 bonded interface"; - } - enum "aluEpon" { - value 266; - description - "Ethernet Passive Optical Networks (E-PON)"; - } - enum "aluEponOnu" { - value 267; - description - "EPON Optical Network Unit"; - } - enum "aluEponPhysicalUni" { - value 268; - description - "EPON physical User to Network interface"; - } - enum "aluEponLogicalLink" { - value 269; - description - "The emulation of a point-to-point link over the EPON - layer"; - } - enum "aluGponOnu" { - value 270; - description - "GPON Optical Network Unit"; - reference - "ITU-T G.984.2"; - } - enum "aluGponPhysicalUni" { - value 271; - description - "GPON physical User to Network interface"; - reference - "ITU-T G.984.2"; - } - enum "vmwareNicTeam" { - value 272; - description - "VMware NIC Team"; - } - } - description - "This data type is used as the syntax of the 'type' - leaf in the 'interface' list in the YANG module - ietf-interface. - - The definition of this typedef with the - addition of newly assigned values is published - periodically by the IANA, in either the Assigned - Numbers RFC, or some derivative of it specific to - Internet Network Management number assignments. (The - latest arrangements can be obtained by contacting the - IANA.) - - Requests for new values should be made to IANA via - email (iana&iana.org)."; - reference - "ifType definitions registry. - "; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-inet-types.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-inet-types.yang deleted file mode 100644 index de20febbb7..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-inet-types.yang +++ /dev/null @@ -1,418 +0,0 @@ - module ietf-inet-types { - - namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types"; - prefix "inet"; - - organization - "IETF NETMOD (NETCONF Data Modeling Language) Working Group"; - - contact - "WG Web: - WG List: - - WG Chair: David Partain - - - WG Chair: David Kessens - - - Editor: Juergen Schoenwaelder - "; - - description - "This module contains a collection of generally useful derived - YANG data types for Internet addresses and related things. - - Copyright (c) 2010 IETF Trust and the persons identified as - authors of the code. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, is permitted pursuant to, and subject to the license - terms contained in, the Simplified BSD License set forth in Section - 4.c of the IETF Trust's Legal Provisions Relating to IETF Documents - (http://trustee.ietf.org/license-info). - - This version of this YANG module is part of RFC 6021; see - the RFC itself for full legal notices."; - - revision 2010-09-24 { - description - "Initial revision."; - reference - "RFC 6021: Common YANG Data Types"; - } - - /*** collection of protocol field related types ***/ - - typedef ip-version { - type enumeration { - enum unknown { - value "0"; - description - "An unknown or unspecified version of the Internet protocol."; - } - enum ipv4 { - value "1"; - description - "The IPv4 protocol as defined in RFC 791."; - } - enum ipv6 { - value "2"; - description - "The IPv6 protocol as defined in RFC 2460."; - } - } - description - "This value represents the version of the IP protocol. - - In the value set and its semantics, this type is equivalent - to the InetVersion textual convention of the SMIv2."; - reference - "RFC 791: Internet Protocol - RFC 2460: Internet Protocol, Version 6 (IPv6) Specification - RFC 4001: Textual Conventions for Internet Network Addresses"; - } - - typedef dscp { - type uint8 { - range "0..63"; - } - description - "The dscp type represents a Differentiated Services Code-Point - that may be used for marking packets in a traffic stream. - - In the value set and its semantics, this type is equivalent - to the Dscp textual convention of the SMIv2."; - reference - "RFC 3289: Management Information Base for the Differentiated - Services Architecture - RFC 2474: Definition of the Differentiated Services Field - (DS Field) in the IPv4 and IPv6 Headers - RFC 2780: IANA Allocation Guidelines For Values In - the Internet Protocol and Related Headers"; - } - - typedef ipv6-flow-label { - type uint32 { - range "0..1048575"; - } - description - "The flow-label type represents flow identifier or Flow Label - in an IPv6 packet header that may be used to discriminate - traffic flows. - - In the value set and its semantics, this type is equivalent - to the IPv6FlowLabel textual convention of the SMIv2."; - reference - "RFC 3595: Textual Conventions for IPv6 Flow Label - RFC 2460: Internet Protocol, Version 6 (IPv6) Specification"; - } - - typedef port-number { - type uint16 { - range "0..65535"; - } - description - "The port-number type represents a 16-bit port number of an - Internet transport layer protocol such as UDP, TCP, DCCP, or - SCTP. Port numbers are assigned by IANA. A current list of - all assignments is available from . - - Note that the port number value zero is reserved by IANA. In - situations where the value zero does not make sense, it can - be excluded by subtyping the port-number type. - - In the value set and its semantics, this type is equivalent - to the InetPortNumber textual convention of the SMIv2."; - reference - "RFC 768: User Datagram Protocol - RFC 793: Transmission Control Protocol - RFC 4960: Stream Control Transmission Protocol - RFC 4340: Datagram Congestion Control Protocol (DCCP) - RFC 4001: Textual Conventions for Internet Network Addresses"; - } - - /*** collection of autonomous system related types ***/ - - typedef as-number { - type uint32; - description - "The as-number type represents autonomous system numbers - which identify an Autonomous System (AS). An AS is a set - of routers under a single technical administration, using - an interior gateway protocol and common metrics to route - packets within the AS, and using an exterior gateway - protocol to route packets to other ASs'. IANA maintains - the AS number space and has delegated large parts to the - regional registries. - - Autonomous system numbers were originally limited to 16 - bits. BGP extensions have enlarged the autonomous system - number space to 32 bits. This type therefore uses an uint32 - base type without a range restriction in order to support - a larger autonomous system number space. - - In the value set and its semantics, this type is equivalent - to the InetAutonomousSystemNumber textual convention of - the SMIv2."; - reference - "RFC 1930: Guidelines for creation, selection, and registration - of an Autonomous System (AS) - RFC 4271: A Border Gateway Protocol 4 (BGP-4) - RFC 4893: BGP Support for Four-octet AS Number Space - RFC 4001: Textual Conventions for Internet Network Addresses"; - } - - /*** collection of IP address and hostname related types ***/ - - typedef ip-address { - type union { - type inet:ipv4-address; - type inet:ipv6-address; - } - description - "The ip-address type represents an IP address and is IP - version neutral. The format of the textual representations - implies the IP version."; - } - - typedef ipv4-address { - type string { - pattern - '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}' - + '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])' - + '(%[\p{N}\p{L}]+)?'; - } - description - "The ipv4-address type represents an IPv4 address in - dotted-quad notation. The IPv4 address may include a zone - index, separated by a % sign. - - The zone index is used to disambiguate identical address - values. For link-local addresses, the zone index will - typically be the interface index number or the name of an - interface. If the zone index is not present, the default - zone of the device will be used. - - The canonical format for the zone index is the numerical - format"; - } - - typedef ipv6-address { - type string { - pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}' - + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|' - + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}' - + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))' - + '(%[\p{N}\p{L}]+)?'; - pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|' - + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)' - + '(%.+)?'; - } - description - "The ipv6-address type represents an IPv6 address in full, - mixed, shortened, and shortened-mixed notation. The IPv6 - address may include a zone index, separated by a % sign. - - The zone index is used to disambiguate identical address - values. For link-local addresses, the zone index will - typically be the interface index number or the name of an - interface. If the zone index is not present, the default - zone of the device will be used. - - The canonical format of IPv6 addresses uses the compressed - format described in RFC 4291, Section 2.2, item 2 with the - following additional rules: the :: substitution must be - applied to the longest sequence of all-zero 16-bit chunks - in an IPv6 address. If there is a tie, the first sequence - of all-zero 16-bit chunks is replaced by ::. Single - all-zero 16-bit chunks are not compressed. The canonical - format uses lowercase characters and leading zeros are - not allowed. The canonical format for the zone index is - the numerical format as described in RFC 4007, Section - 11.2."; - reference - "RFC 4291: IP Version 6 Addressing Architecture - RFC 4007: IPv6 Scoped Address Architecture - RFC 5952: A Recommendation for IPv6 Address Text Representation"; - } - - typedef ip-prefix { - type union { - type inet:ipv4-prefix; - type inet:ipv6-prefix; - } - description - "The ip-prefix type represents an IP prefix and is IP - version neutral. The format of the textual representations - implies the IP version."; - } - - typedef ipv4-prefix { - type string { - pattern - '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}' - + '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])' - + '/(([0-9])|([1-2][0-9])|(3[0-2]))'; - } - description - "The ipv4-prefix type represents an IPv4 address prefix. - The prefix length is given by the number following the - slash character and must be less than or equal to 32. - - A prefix length value of n corresponds to an IP address - mask that has n contiguous 1-bits from the most - significant bit (MSB) and all other bits set to 0. - - The canonical format of an IPv4 prefix has all bits of - the IPv4 address set to zero that are not part of the - IPv4 prefix."; - } - - typedef ipv6-prefix { - type string { - pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}' - + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|' - + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}' - + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))' - + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))'; - pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|' - + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)' - + '(/.+)'; - } - description - "The ipv6-prefix type represents an IPv6 address prefix. - The prefix length is given by the number following the - slash character and must be less than or equal 128. - - A prefix length value of n corresponds to an IP address - mask that has n contiguous 1-bits from the most - significant bit (MSB) and all other bits set to 0. - - The IPv6 address should have all bits that do not belong - to the prefix set to zero. - - The canonical format of an IPv6 prefix has all bits of - the IPv6 address set to zero that are not part of the - IPv6 prefix. Furthermore, IPv6 address is represented - in the compressed format described in RFC 4291, Section - 2.2, item 2 with the following additional rules: the :: - substitution must be applied to the longest sequence of - all-zero 16-bit chunks in an IPv6 address. If there is - a tie, the first sequence of all-zero 16-bit chunks is - replaced by ::. Single all-zero 16-bit chunks are not - compressed. The canonical format uses lowercase - characters and leading zeros are not allowed."; - reference - "RFC 4291: IP Version 6 Addressing Architecture"; - } - - /*** collection of domain name and URI types ***/ - - typedef domain-name { - type string { - pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*' - + '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)' - + '|\.'; - length "1..253"; - } - description - "The domain-name type represents a DNS domain name. The - name SHOULD be fully qualified whenever possible. - - Internet domain names are only loosely specified. Section - 3.5 of RFC 1034 recommends a syntax (modified in Section - 2.1 of RFC 1123). The pattern above is intended to allow - for current practice in domain name use, and some possible - future expansion. It is designed to hold various types of - domain names, including names used for A or AAAA records - (host names) and other records, such as SRV records. Note - that Internet host names have a stricter syntax (described - in RFC 952) than the DNS recommendations in RFCs 1034 and - 1123, and that systems that want to store host names in - schema nodes using the domain-name type are recommended to - adhere to this stricter standard to ensure interoperability. - - The encoding of DNS names in the DNS protocol is limited - to 255 characters. Since the encoding consists of labels - prefixed by a length bytes and there is a trailing NULL - byte, only 253 characters can appear in the textual dotted - notation. - - The description clause of schema nodes using the domain-name - type MUST describe when and how these names are resolved to - IP addresses. Note that the resolution of a domain-name value - may require to query multiple DNS records (e.g., A for IPv4 - and AAAA for IPv6). The order of the resolution process and - which DNS record takes precedence can either be defined - explicitely or it may depend on the configuration of the - resolver. - - Domain-name values use the US-ASCII encoding. Their canonical - format uses lowercase US-ASCII characters. Internationalized - domain names MUST be encoded in punycode as described in RFC - 3492"; - reference - "RFC 952: DoD Internet Host Table Specification - RFC 1034: Domain Names - Concepts and Facilities - RFC 1123: Requirements for Internet Hosts -- Application - and Support - RFC 2782: A DNS RR for specifying the location of services - (DNS SRV) - RFC 3492: Punycode: A Bootstring encoding of Unicode for - Internationalized Domain Names in Applications - (IDNA) - RFC 5891: Internationalizing Domain Names in Applications - (IDNA): Protocol"; - } - - typedef host { - type union { - type inet:ip-address; - type inet:domain-name; - } - description - "The host type represents either an IP address or a DNS - domain name."; - } - - typedef uri { - type string; - description - "The uri type represents a Uniform Resource Identifier - (URI) as defined by STD 66. - - Objects using the uri type MUST be in US-ASCII encoding, - and MUST be normalized as described by RFC 3986 Sections - 6.2.1, 6.2.2.1, and 6.2.2.2. All unnecessary - percent-encoding is removed, and all case-insensitive - characters are set to lowercase except for hexadecimal - digits, which are normalized to uppercase as described in - Section 6.2.2.1. - - The purpose of this normalization is to help provide - unique URIs. Note that this normalization is not - sufficient to provide uniqueness. Two URIs that are - textually distinct after this normalization may still be - equivalent. - - Objects using the uri type may restrict the schemes that - they permit. For example, 'data:' and 'urn:' schemes - might not be appropriate. - - A zero-length URI is not a valid URI. This can be used to - express 'URI absent' where required. - - In the value set and its semantics, this type is equivalent - to the Uri SMIv2 textual convention defined in RFC 5017."; - reference - "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax - RFC 3305: Report from the Joint W3C/IETF URI Planning Interest - Group: Uniform Resource Identifiers (URIs), URLs, - and Uniform Resource Names (URNs): Clarifications - and Recommendations - RFC 5017: MIB Textual Conventions for Uniform Resource - Identifiers (URIs)"; - } - - } diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-interfaces.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-interfaces.yang deleted file mode 100644 index 481a5d2ed1..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-interfaces.yang +++ /dev/null @@ -1,469 +0,0 @@ -module ietf-interfaces { - - namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces"; - prefix if; - - import ietf-yang-types { - prefix yang; - revision-date 2010-09-24; - } - - organization - "IETF NETMOD (NETCONF Data Modeling Language) Working Group"; - - contact - "WG Web: - WG List: - - WG Chair: David Kessens - - - WG Chair: Juergen Schoenwaelder - - - Editor: Martin Bjorklund - "; - - description - "This module contains a collection of YANG definitions for - managing network interfaces. - - Copyright (c) 2012 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 XXXX; see - the RFC itself for full legal notices."; - - // RFC Ed.: replace XXXX with actual RFC number and remove this - // note. - - // RFC Ed.: update the date below with the date of RFC publication - // and remove this note. - revision 2012-11-15 { - description - "Initial revision."; - reference - "RFC XXXX: 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 - interfaces."; - } - - /* Features */ - - feature arbitrary-names { - description - "This feature indicates that the server allows interfaces to - be named arbitrarily."; - } - - feature if-mib { - description - "This feature indicates that the server implements IF-MIB."; - reference - "RFC 2863: The Interfaces Group MIB"; - } - - /* Data nodes */ - - container interfaces { - description - "Interface parameters."; - - list interface { - key "name"; - unique "type location"; - - description - "The list of interfaces on the device."; - - 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 and location. - - If the device allows arbitrarily named interfaces, the - feature 'arbitrary-names' is advertised. - - This leaf MAY be mapped to ifName by an implementation. - Such an implementation MAY restrict the allowed values for - this leaf so that it matches the restrictions of ifName. - If a NETCONF server that implements this restriction is - sent a value that doesn't match the restriction, it MUST - reply with an rpc-error with the error-tag - 'invalid-value'."; - reference - "RFC 2863: The Interfaces Group MIB - ifName"; - } - - leaf description { - type string; - description - "A textual description of the interface. - - This leaf MAY be mapped to ifAlias by an implementation. - Such an implementation MAY restrict the allowed values for - this leaf so that it matches the restrictions of ifAlias. - If a NETCONF server that implements this restriction is - sent a value that doesn't match the restriction, it MUST - reply with an rpc-error with the error-tag - 'invalid-value'."; - reference - "RFC 2863: The Interfaces Group MIB - ifAlias"; - } - - leaf location { - type string; - description - "The device-specific location of the interface of a - particular type. The format of the location string - depends on the interface type and the device. - - If the interface's type represents a physical interface, - this leaf MUST be set. - - When an interface entry is created, a server MAY - initialize the location leaf with a valid value, e.g., if - it is possible to derive the location from the name of - the interface."; - } - - leaf enabled { - type boolean; - default "true"; - description - "The desired state of the interface. - - This leaf contains the configured, desired state of the - interface. Systems that implement the IF-MIB use the - value of this leaf to set IF-MIB.ifAdminStatus to 'up' or - 'down' after an ifEntry has been initialized, as described - in RFC 2863."; - reference - "RFC 2863: The Interfaces Group MIB - ifAdminStatus"; - } - - leaf last-change { - type yang:date-and-time; - config false; - 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"; - } - config false; - description - "The ifIndex value for the ifEntry represented by this - interface. - - Media-specific modules must specify how the type is - mapped to entries in the ifTable."; - reference - "RFC 2863: The Interfaces Group MIB - ifIndex"; - } - - leaf phys-address { - type yang:phys-address; - config false; - description - "The interface's address at its protocol sub-layer. For - example, for an 802.x interface, this object normally - contains a 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-ref; - config false; - 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-ref; - config false; - 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"; - config false; - description - "An estimate of the interface's current bandwidth in bits - per second. For interfaces which 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 has no concept of bandwidth, this - node is not present."; - reference - "RFC 2863: The Interfaces Group MIB - - ifSpeed, ifHighSpeed"; - } - - container statistics { - config false; - description - "A collection of interface-related statistics objects."; - - leaf discontinuity-time { - type yang:date-and-time; - 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, which 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, which 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, which 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 which 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 which 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 which 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 which 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 which 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 which 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 which 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"; - } - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-yang-types.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-yang-types.yang deleted file mode 100644 index 51d9f8b887..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/ietf/ietf-yang-types.yang +++ /dev/null @@ -1,396 +0,0 @@ - module ietf-yang-types { - - namespace "urn:ietf:params:xml:ns:yang:ietf-yang-types"; - prefix "yang"; - - organization - "IETF NETMOD (NETCONF Data Modeling Language) Working Group"; - - contact - "WG Web: - WG List: - - WG Chair: David Partain - - - WG Chair: David Kessens - - - Editor: Juergen Schoenwaelder - "; - - description - "This module contains a collection of generally useful derived - YANG data types. - - Copyright (c) 2010 IETF Trust and the persons identified as - authors of the code. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, is permitted pursuant to, and subject to the license - terms contained in, the Simplified BSD License set forth in Section - 4.c of the IETF Trust's Legal Provisions Relating to IETF Documents - (http://trustee.ietf.org/license-info). - - This version of this YANG module is part of RFC 6021; see - the RFC itself for full legal notices."; - - revision 2010-09-24 { - description - "Initial revision."; - reference - "RFC 6021: Common YANG Data Types"; - } - - /*** collection of counter and gauge types ***/ - - typedef counter32 { - type uint32; - description - "The counter32 type represents a non-negative integer - that monotonically increases until it reaches a - maximum value of 2^32-1 (4294967295 decimal), when it - wraps around and starts increasing again from zero. - - Counters have no defined 'initial' value, and thus, a - single value of a counter has (in general) no information - content. Discontinuities in the monotonically increasing - value normally occur at re-initialization of the - management system, and at other times as specified in the - description of a schema node using this type. If such - other times can occur, for example, the creation of - a schema node of type counter32 at times other than - re-initialization, then a corresponding schema node - should be defined, with an appropriate type, to indicate - the last discontinuity. - - The counter32 type should not be used for configuration - schema nodes. A default statement SHOULD NOT be used in - combination with the type counter32. - - In the value set and its semantics, this type is equivalent - to the Counter32 type of the SMIv2."; - reference - "RFC 2578: Structure of Management Information Version 2 (SMIv2)"; - } - - typedef zero-based-counter32 { - type yang:counter32; - default "0"; - description - "The zero-based-counter32 type represents a counter32 - that has the defined 'initial' value zero. - - A schema node of this type will be set to zero (0) on creation - and will thereafter increase monotonically until it reaches - a maximum value of 2^32-1 (4294967295 decimal), when it - wraps around and starts increasing again from zero. - - Provided that an application discovers a new schema node - of this type within the minimum time to wrap, it can use the - 'initial' value as a delta. It is important for a management - station to be aware of this minimum time and the actual time - between polls, and to discard data if the actual time is too - long or there is no defined minimum time. - - In the value set and its semantics, this type is equivalent - to the ZeroBasedCounter32 textual convention of the SMIv2."; - reference - "RFC 4502: Remote Network Monitoring Management Information - Base Version 2"; - } - - typedef counter64 { - type uint64; - description - "The counter64 type represents a non-negative integer - that monotonically increases until it reaches a - maximum value of 2^64-1 (18446744073709551615 decimal), - when it wraps around and starts increasing again from zero. - - Counters have no defined 'initial' value, and thus, a - single value of a counter has (in general) no information - content. Discontinuities in the monotonically increasing - value normally occur at re-initialization of the - management system, and at other times as specified in the - description of a schema node using this type. If such - other times can occur, for example, the creation of - a schema node of type counter64 at times other than - re-initialization, then a corresponding schema node - should be defined, with an appropriate type, to indicate - the last discontinuity. - - The counter64 type should not be used for configuration - schema nodes. A default statement SHOULD NOT be used in - combination with the type counter64. - - In the value set and its semantics, this type is equivalent - to the Counter64 type of the SMIv2."; - reference - "RFC 2578: Structure of Management Information Version 2 (SMIv2)"; - } - - typedef zero-based-counter64 { - type yang:counter64; - default "0"; - description - "The zero-based-counter64 type represents a counter64 that - has the defined 'initial' value zero. - - A schema node of this type will be set to zero (0) on creation - and will thereafter increase monotonically until it reaches - a maximum value of 2^64-1 (18446744073709551615 decimal), - when it wraps around and starts increasing again from zero. - - Provided that an application discovers a new schema node - of this type within the minimum time to wrap, it can use the - 'initial' value as a delta. It is important for a management - station to be aware of this minimum time and the actual time - between polls, and to discard data if the actual time is too - long or there is no defined minimum time. - - In the value set and its semantics, this type is equivalent - to the ZeroBasedCounter64 textual convention of the SMIv2."; - reference - "RFC 2856: Textual Conventions for Additional High Capacity - Data Types"; - } - - typedef gauge32 { - type uint32; - description - "The gauge32 type represents a non-negative integer, which - may increase or decrease, but shall never exceed a maximum - value, nor fall below a minimum value. The maximum value - cannot be greater than 2^32-1 (4294967295 decimal), and - the minimum value cannot be smaller than 0. The value of - a gauge32 has its maximum value whenever the information - being modeled is greater than or equal to its maximum - value, and has its minimum value whenever the information - being modeled is smaller than or equal to its minimum value. - If the information being modeled subsequently decreases - below (increases above) the maximum (minimum) value, the - gauge32 also decreases (increases). - - In the value set and its semantics, this type is equivalent - to the Gauge32 type of the SMIv2."; - reference - "RFC 2578: Structure of Management Information Version 2 (SMIv2)"; - } - - typedef gauge64 { - type uint64; - description - "The gauge64 type represents a non-negative integer, which - may increase or decrease, but shall never exceed a maximum - value, nor fall below a minimum value. The maximum value - cannot be greater than 2^64-1 (18446744073709551615), and - the minimum value cannot be smaller than 0. The value of - a gauge64 has its maximum value whenever the information - being modeled is greater than or equal to its maximum - value, and has its minimum value whenever the information - being modeled is smaller than or equal to its minimum value. - If the information being modeled subsequently decreases - below (increases above) the maximum (minimum) value, the - gauge64 also decreases (increases). - - In the value set and its semantics, this type is equivalent - to the CounterBasedGauge64 SMIv2 textual convention defined - in RFC 2856"; - reference - "RFC 2856: Textual Conventions for Additional High Capacity - Data Types"; - } - - /*** collection of identifier related types ***/ - - typedef object-identifier { - type string { - pattern '(([0-1](\.[1-3]?[0-9]))|(2\.(0|([1-9]\d*))))' - + '(\.(0|([1-9]\d*)))*'; - } - description - "The object-identifier type represents administratively - assigned names in a registration-hierarchical-name tree. - - Values of this type are denoted as a sequence of numerical - non-negative sub-identifier values. Each sub-identifier - value MUST NOT exceed 2^32-1 (4294967295). Sub-identifiers - are separated by single dots and without any intermediate - whitespace. - - The ASN.1 standard restricts the value space of the first - sub-identifier to 0, 1, or 2. Furthermore, the value space - of the second sub-identifier is restricted to the range - 0 to 39 if the first sub-identifier is 0 or 1. Finally, - the ASN.1 standard requires that an object identifier - has always at least two sub-identifier. The pattern - captures these restrictions. - - Although the number of sub-identifiers is not limited, - module designers should realize that there may be - implementations that stick with the SMIv2 limit of 128 - sub-identifiers. - - This type is a superset of the SMIv2 OBJECT IDENTIFIER type - since it is not restricted to 128 sub-identifiers. Hence, - this type SHOULD NOT be used to represent the SMIv2 OBJECT - IDENTIFIER type, the object-identifier-128 type SHOULD be - used instead."; - reference - "ISO9834-1: Information technology -- Open Systems - Interconnection -- Procedures for the operation of OSI - Registration Authorities: General procedures and top - arcs of the ASN.1 Object Identifier tree"; - } - - - - - typedef object-identifier-128 { - type object-identifier { - pattern '\d*(\.\d*){1,127}'; - } - description - "This type represents object-identifiers restricted to 128 - sub-identifiers. - - In the value set and its semantics, this type is equivalent - to the OBJECT IDENTIFIER type of the SMIv2."; - reference - "RFC 2578: Structure of Management Information Version 2 (SMIv2)"; - } - - /*** collection of date and time related types ***/ - - typedef date-and-time { - type string { - pattern '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?' - + '(Z|[\+\-]\d{2}:\d{2})'; - } - description - "The date-and-time type is a profile of the ISO 8601 - standard for representation of dates and times using the - Gregorian calendar. The profile is defined by the - date-time production in Section 5.6 of RFC 3339. - - The date-and-time type is compatible with the dateTime XML - schema type with the following notable exceptions: - - (a) The date-and-time type does not allow negative years. - - (b) The date-and-time time-offset -00:00 indicates an unknown - time zone (see RFC 3339) while -00:00 and +00:00 and Z all - represent the same time zone in dateTime. - - (c) The canonical format (see below) of data-and-time values - differs from the canonical format used by the dateTime XML - schema type, which requires all times to be in UTC using the - time-offset 'Z'. - - This type is not equivalent to the DateAndTime textual - convention of the SMIv2 since RFC 3339 uses a different - separator between full-date and full-time and provides - higher resolution of time-secfrac. - - The canonical format for date-and-time values with a known time - zone uses a numeric time zone offset that is calculated using - the device's configured known offset to UTC time. A change of - the device's offset to UTC time will cause date-and-time values - to change accordingly. Such changes might happen periodically - in case a server follows automatically daylight saving time - (DST) time zone offset changes. The canonical format for - date-and-time values with an unknown time zone (usually referring - to the notion of local time) uses the time-offset -00:00."; - reference - "RFC 3339: Date and Time on the Internet: Timestamps - RFC 2579: Textual Conventions for SMIv2 - XSD-TYPES: XML Schema Part 2: Datatypes Second Edition"; - } - - typedef timeticks { - type uint32; - description - "The timeticks type represents a non-negative integer that - represents the time, modulo 2^32 (4294967296 decimal), in - hundredths of a second between two epochs. When a schema - node is defined that uses this type, the description of - the schema node identifies both of the reference epochs. - - In the value set and its semantics, this type is equivalent - to the TimeTicks type of the SMIv2."; - reference - "RFC 2578: Structure of Management Information Version 2 (SMIv2)"; - } - - typedef timestamp { - type yang:timeticks; - description - "The timestamp type represents the value of an associated - timeticks schema node at which a specific occurrence happened. - The specific occurrence must be defined in the description - of any schema node defined using this type. When the specific - occurrence occurred prior to the last time the associated - timeticks attribute was zero, then the timestamp value is - zero. Note that this requires all timestamp values to be - reset to zero when the value of the associated timeticks - attribute reaches 497+ days and wraps around to zero. - - The associated timeticks schema node must be specified - in the description of any schema node using this type. - - In the value set and its semantics, this type is equivalent - to the TimeStamp textual convention of the SMIv2."; - reference - "RFC 2579: Textual Conventions for SMIv2"; - } - - /*** collection of generic address types ***/ - - typedef phys-address { - type string { - pattern '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2})*)?'; - } - description - "Represents media- or physical-level addresses represented - as a sequence octets, each octet represented by two hexadecimal - numbers. Octets are separated by colons. The canonical - representation uses lowercase characters. - - In the value set and its semantics, this type is equivalent - to the PhysAddress textual convention of the SMIv2."; - reference - "RFC 2579: Textual Conventions for SMIv2"; - } - - typedef mac-address { - type string { - pattern '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}'; - } - description - "The mac-address type represents an IEEE 802 MAC address. - The canonical representation uses lowercase characters. - - In the value set and its semantics, this type is equivalent - to the MacAddress textual convention of the SMIv2."; - reference - "IEEE 802: IEEE Standard for Local and Metropolitan Area - Networks: Overview and Architecture - RFC 2579: Textual Conventions for SMIv2"; - } - - /*** collection of XML specific types ***/ - - typedef xpath1.0 { - type string; - description - "This type represents an XPATH 1.0 expression. - - When a schema node is defined that uses this type, the - description of the schema node MUST specify the XPath - context in which the XPath expression is evaluated."; - reference - "XPATH: XML Path Language (XPath) Version 1.0"; - } - - } diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref.yang deleted file mode 100644 index f13cf26cfd..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref.yang +++ /dev/null @@ -1,34 +0,0 @@ -module test-leafref { - - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:test:leafref"; - prefix "test"; - - revision "2017-02-24" { - description "Initial revision of test model."; - } - - container test-container { - list test-list { - leaf test-leaf { - type enumeration { - enum enum1 { - value 1; - } - enum enum2 { - value 2; - } - } - } - } - } - - container test-leafref-container { - leaf test-leafref { - type leafref { - path "/test:test-container/test:test-list/test:test-leaf"; - } - } - } - -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref2.yang deleted file mode 100644 index e3cbeb8c07..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref2.yang +++ /dev/null @@ -1,34 +0,0 @@ -module test-leafref2 { - - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:test:leafref2"; - prefix "test"; - - revision "2017-02-24" { - description "Initial revision of test model."; - } - - container testContainer { - list testList { - leaf testLeaf { - type enumeration { - enum enum1 { - value 1; - } - enum enum2 { - value 2; - } - } - } - } - } - - notification testLeafrefNotification { - leaf tesLeafref { - type leafref { - path "/test:testContainer/test:testList/test:testLeaf"; - } - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref3.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref3.yang deleted file mode 100644 index 168e04b635..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref/test-leafref3.yang +++ /dev/null @@ -1,27 +0,0 @@ -module test-leafref3 { - - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:test"; - prefix "test"; - - revision "2017-02-24" { - description "Initial revision of test model."; - } - - container testContainer { - list testList { - leaf testLeaf { - type string; - } - } - } - - notification testLeafrefNotification { - leaf tesLeafref { - type leafref { - path "/test:testContainer/test:testList/test:testLeaf"; - } - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang deleted file mode 100644 index 4cf0519f6a..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang +++ /dev/null @@ -1,49 +0,0 @@ -module bug8449 { - yang-version 1; - namespace "bug8449"; - prefix "tst"; - - revision "2017-05-16" { - } - - typedef name1-ref { - type leafref { - path "/tst:top/tst:name1"; - } - } - - typedef name2-ref { - type leafref { - path "/tst:top/tst:name2"; - } - } - - typedef name3-ref { - type string; - } - - container top { - leaf name1 { - type string; - } - leaf name2 { - type string; - } - } - - container test { - leaf ref { - type name3-ref; - } - } - - container cont { - leaf ref { - type union { - type name1-ref; - type name2-ref; - } - mandatory true; - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-leaf-list.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-leaf-list.yang deleted file mode 100644 index 8b9ca7819d..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-leaf-list.yang +++ /dev/null @@ -1,24 +0,0 @@ -module test-leaf-list { - yang-version 1; - namespace "org.test.leaf-list"; - prefix "ll"; - - container *1my-cont { - leaf-list min-max-leaf-list { - min-elements 1; - max-elements 3; - type string; - } - - leaf-list unbounded-leaf-list { - type string; - } - - list unkeyed-list { - max-elements 1; - leaf unkeyed-leaf { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list.yang deleted file mode 100644 index 752db99b27..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list.yang +++ /dev/null @@ -1,20 +0,0 @@ -module test-list { - yang-version 1.1; - - namespace "urn:test:simple:test:list"; - prefix test-list; - organization "test.list.org"; - revision "2017-03-14"; - - list my-list { - key "name"; - leaf name { - type string; - } - - leaf surname { - type string; - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list2.yang deleted file mode 100644 index 4eb8b572d2..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/list/test-list2.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-list2 { - yang-version 1.1; - - namespace "urn:test:simple:test:list2"; - prefix test-list2; - organization "test.list2.org"; - revision "2017-03-14"; - - list my-list { - key "key key1 key2"; - leaf key{ - type string; - } - leaf key1 { - type string; - } - leaf key2 { - type string; - } - leaf foo{ - type string; - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/class-type-test.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/class-type-test.yang deleted file mode 100644 index be38c8ab85..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/class-type-test.yang +++ /dev/null @@ -1,25 +0,0 @@ -module class-type-test { - - description "ODL BGPCEP snippet challenge"; - - prefix "class"; - namespace "org.class.type.test"; - - container my-cont { //data.myCont, dto.myContBuilder - uses classtype-object; //data.my_cont.ClassType, dto.my_cont.ClassTypeBuilder - } - - typedef class-type { //type.classType - type uint8 { - range 1..7; - } - } - - grouping classtype-object { //grp.ClassTypeObjectGrouping - container class-type { //grp.classtype_object.ClassTypeData - leaf class-type { //public type.ClassType getClassType() - type class-type; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-dto.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-dto.yang deleted file mode 100644 index 09b8c43612..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-dto.yang +++ /dev/null @@ -1,21 +0,0 @@ -module namespace-test-dto { - namespace "org.test.namespace.dto"; - prefix "dto"; - revision 2017-05-19; - - container a { - container b { - leaf leaf-b { - type string; - } - } - } - - grouping c { - container d { - leaf leaf-d { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-foo1.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-foo1.yang deleted file mode 100644 index 8290e3617a..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/namespace/namespace-test-foo1.yang +++ /dev/null @@ -1,21 +0,0 @@ -module namespace-test-foo1 { - namespace "org.test.namespace.foo1"; - prefix "foo1"; - revision 2017-05-19; - - container a { - container b { - leaf c { - type string; - } - } - } - - grouping a { - container b { - leaf c { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/operations/test-action.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/operations/test-action.yang deleted file mode 100644 index ee3de4e4db..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/operations/test-action.yang +++ /dev/null @@ -1,48 +0,0 @@ -module test-action { - yang-version 1.1; - namespace "urn:test:action"; - prefix "routed"; - - revision "2017-06-21" { - description - "Initial revision"; - } - - container my-cont { - action in-cont { - input { - leaf input-leaf { - type string; - } - } - - output { - leaf output-leaf { - type string; - } - } - } - } - - list my-list { - key "name"; - - leaf name { - type string; - } - - action in-list { - input { - leaf input-list-leaf { - type string; - } - } - - output { - leaf output-list-leaf { - type string; - } - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/union-test-models/abstract-topology.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/union-test-models/abstract-topology.yang deleted file mode 100644 index a4b589be82..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/union-test-models/abstract-topology.yang +++ /dev/null @@ -1,120 +0,0 @@ -module abstract-topology { - yang-version 1; - namespace "urn:model:abstract:topology"; - prefix "tp"; - - import ietf-inet-types { - prefix "inet"; - revision-date 2010-09-24; - } - - organization "OPEN DAYLIGHT"; - contact "http://www.opendaylight.org/"; - - description - "This module contains the definitions of elements that creates network - topology i.e. definition of network nodes and links. This module is not designed to be used solely for network representation. This module SHOULD be used as base module in defining the network topology."; - - revision "2013-02-08" { - reference "~~~ WILL BE DEFINED LATER"; - } - - revision "2013-01-01" { - reference "~~~ WILL BE DEFINED LATER"; - } - - typedef union-enum { - type union { - type int32; - type enumeration { - enum "unbounded"; - } - } - } - - typedef link-address { - type union { - type inet:ip-address; - type string; - } - } - - typedef node-id-ref { - type leafref { - path "/tp:topology/tp:network-nodes/tp:network-node/tp:node-id"; - } - description "This type is used for leafs that reference network node instance."; - } - - typedef link-id-ref { - type leafref { - path "/tp:topology/tp:network-links/tp:network-link/tp:link-id"; - } - description "This type is used for leafs that reference network link instance."; - } - - container topology { - description "This is the model of abstract topology which contains only Network Nodes and Network Links. Each topology MUST be identified by unique topology-id for reason that the store could contain many topologies."; - - leaf topology-id { - type inet:uri; - description "It is presumed that datastore will contain many topologies. To distinguish between topologies it is vital to have - UNIQUE topology identifier."; - } - - container network-nodes { - list network-node { - key "node-id"; - - leaf node-id { - type inet:uri; - description "The Topology identifier of network-node."; - } - - leaf bounding { - type union-enum; - } - - container attributes { - description "Aditional attributes that can Network Node contains."; - } - description "The list of network nodes defined for topology."; - } - } - - container network-links { - list network-link { - key "link-id"; - - leaf link-id { - type inet:uri; - description ""; - } - - leaf link-address { - type link-address; - } - - container source-node { - leaf id { - type node-id-ref; - description "Source node identifier."; - } - } - - container destination-node { - leaf id { - type node-id-ref; - description "Destination node identifier."; - } - } - - container attributes { - description "Aditional attributes that can Network Link contains."; - } - description "The Network Link which is defined by Local (Source) and Remote (Destination) Network Nodes. Every link MUST be defined either by identifier and - his local and remote Network Nodes (In real applications it is common that many links are originated from one node and end up in same remote node). To ensure that we would always know to distinguish between links, every link SHOULD have identifier."; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-binding-top-level-via-uses.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-binding-top-level-via-uses.yang deleted file mode 100644 index 193f6c2f39..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-binding-top-level-via-uses.yang +++ /dev/null @@ -1,22 +0,0 @@ -module opendaylight-binding-top-level-via-uses { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:md:sal:test:top-via-uses"; - prefix "binding-impl"; - - description - "Regression Test model for top-level-via uses"; - - revision "2015-11-12" { - description - "Initial revision"; - } - - grouping container-top { - container container-top { - presence "only for testing"; - } - } - - uses container-top; - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-sal-test-store.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-sal-test-store.yang deleted file mode 100644 index 1d3f6df840..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/opendaylight-sal-test-store.yang +++ /dev/null @@ -1,49 +0,0 @@ -module opendaylight-sal-test-store { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:store"; - prefix "binding-impl"; - - description - "Regression Test model for data store"; - - revision "2014-04-22" { - description - "Initial revision"; - } - - grouping name-value { - leaf name { - type string; - } - leaf value { - type string; - } - } - - container lists { - config false; - container unordered-container { - list unordered-list { - key "name"; - uses name-value; - } - } - container ordered-container { - list ordered-list { - ordered-by user; - key "name"; - uses name-value; - } - } - container unkeyed-container { - /* - Following list nodes not specify key, which - makes impossible to uniquely identify list items - over time. - */ - list unkeyed-list { - uses name-value; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement1.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement1.yang deleted file mode 100644 index 1c49bb3e35..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement1.yang +++ /dev/null @@ -1,24 +0,0 @@ -module test-augment-statement1 { - yang-version 1.1; - - namespace "urn:test:augment:statement1"; - prefix test-augment-statement1; - organization "test.type.org"; - revision "2017-07-10"; - - grouping s1-grp { - leaf leaf-s1-grp { - type string; - } - container cont-s1-grp { - } - } - - container top { - } - - augment "/top" { - container foo { - } - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement2.yang deleted file mode 100644 index b52c0441d9..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-augment-statement2.yang +++ /dev/null @@ -1,38 +0,0 @@ -module test-augment-statement2 { - yang-version 1.1; - - namespace "urn:test:augment:statement2"; - prefix test-augment-statement2; - organization "test.type.org"; - revision "2017-07-10"; - - import test-augment-statement1 { - prefix "s1"; - } - - grouping s2-grp { - leaf leaf-s2-grp { - type string; - } - - } - - container bar { - } - - augment "/s1:top" { - container bar1 { - } - leaf leaf-s2-aug { - type string; - } - uses s2-grp; - } - - augment "/s1:top" { - container bar2 { - } - - uses s1:s1-grp; - } -} diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity-base.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity-base.yang deleted file mode 100644 index 1e7eb3e15b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity-base.yang +++ /dev/null @@ -1,23 +0,0 @@ -module test-identity-base { - yang-version 1.1; - - namespace "urn:test:identity:base"; - prefix test-identity-base; - - organization "test.type.org"; - revision "2017-06-30"; - - identity test-root; - - identity test-one { - base test-root; - } - - identity test-two { - base test-root; - } - - container base-cont { - - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity.yang deleted file mode 100644 index 7f82bd6da6..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-identity.yang +++ /dev/null @@ -1,22 +0,0 @@ -module test-identity { - yang-version 1.1; - - namespace "urn:test:identity"; - prefix test-identity; - - import test-identity-base { - prefix base; - revision-date 2017-06-30; - } - - organization "test.type.org"; - revision "2017-06-30"; - - identity third-party { - base base:test-root; - } - - container my-cont { - - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref-base.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref-base.yang deleted file mode 100644 index a4177d08d9..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref-base.yang +++ /dev/null @@ -1,17 +0,0 @@ -module test-typeref-base { - yang-version 1.1; - - namespace "urn:test:typeref:base"; - prefix test-typeref-base; - - organization "test.type.org"; - revision "2017-06-30"; - - typedef as-number { - type uint32; - } - - container base-cont { - - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref.yang deleted file mode 100644 index 0de4dffbce..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref.yang +++ /dev/null @@ -1,32 +0,0 @@ -module test-typeref { - yang-version 1.1; - - namespace "urn:test:typeref"; - prefix test-typeref; - - import test-typeref-base { - prefix base; - revision-date 2017-06-30; - } - - organization "test.type.org"; - revision "2017-06-30"; - - typedef local-as-number { - type uint32; - } - - grouping as-number-subobject { - leaf as-number { - type base:as-number; - } - - leaf local-as-number { - type local-as-number; - } - } - - container my-cont { - uses as-number-subobject; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref2.yang deleted file mode 100644 index 59f4ae4c91..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-typeref2.yang +++ /dev/null @@ -1,30 +0,0 @@ -module test-typeref2 { - yang-version 1.1; - - namespace "urn:test:typeref2"; - prefix test-typeref2; - - typedef lsp-flag { - type enumeration { - enum unprotected { - value 0; - } - enum full-rerouting { - value 1; - } - } - } - - grouping protection-subobject { - container protection-subobject { - leaf lsp-flag { - type lsp-flag; - mandatory true; - } - } - } - - container my-cont { - uses protection-subobject; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-choice.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-choice.yang deleted file mode 100644 index f09c0cab01..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-choice.yang +++ /dev/null @@ -1,22 +0,0 @@ -module test-uses-choice { - yang-version 1.1; - - namespace "urn:test:uses:choice"; - prefix test-uses-choice; - organization "test.type.org"; - revision "2017-06-30"; - - grouping my-grouping { - choice my-choice { - case my-case { - leaf my-leaf { - type string; - } - } - } - } - - container my-cont { - uses my-grouping; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype-base.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype-base.yang deleted file mode 100644 index d05879562e..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype-base.yang +++ /dev/null @@ -1,31 +0,0 @@ -module test-uses-leaf-innertype-base { - namespace "urn:test:uses:leaf:innertype:base"; - prefix uses-leaf; - revision 2017-08-09; - - grouping errors { - leaf error-type { - type enumeration { - enum transport { - description "The transport layer"; - } - enum rpc { - description "The rpc or notification layer"; - } - enum protocol { - description "The protocol operation layer"; - } - enum application { - description "The server application layer"; - } - } - mandatory true; - description - "The protocol layer where the error occurred."; - } - } - - container my-cont { - uses errors; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype.yang deleted file mode 100644 index 4212f78cef..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype.yang +++ /dev/null @@ -1,12 +0,0 @@ -module test-uses-leaf-innertype { - namespace "urn:test:uses:leaf:innertype"; - prefix uses-leaf; - revision 2017-08-09; - import test-uses-leaf-innertype-base { - prefix "base"; - } - - container my-cont { - uses base:errors; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2-base.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2-base.yang deleted file mode 100644 index 72c06cfb2f..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2-base.yang +++ /dev/null @@ -1,58 +0,0 @@ -module test-uses-leaf-innertype2-base { - namespace "urn:test:uses:leaf:innertype2:base"; - prefix uses-leaf; - revision 2017-08-09; - - grouping my-grp { - leaf leaf-decimal64 { - description - "Minimum LSP Bandwidth. Units in bytes per second"; - type decimal64 { - fraction-digits 2; - } - } - - leaf leaf-union { - type union { - type int32; - type string; - } - } - - leaf leaf-bits { - type bits { - bit path-computation-with-gmpls-link-constraints { - position 0; - } - bit bidirectional-path-computation { - position 1; - } - bit diverse-path-computation { - position 2; - } - bit load-balanced-path-computation { - position 3; - } - bit synchronized-path-computation { - position 4; - } - bit support-for-multiple-objective-functions { - position 5; - } - bit support-for-additive-path-constraints { - position 6; - } - bit support-for-request-prioritization { - position 7; - } - bit support-for-multiple-requests-per-message { - position 8; - } - } - } - } - - container my-cont { - uses my-grp; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2.yang deleted file mode 100644 index da7225600a..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype2.yang +++ /dev/null @@ -1,12 +0,0 @@ -module test-uses-leaf-innertype2 { - namespace "urn:test:uses:leaf:innertype2"; - prefix uses-leaf; - revision 2017-08-09; - import test-uses-leaf-innertype2-base { - prefix "base"; - } - - container my-cont { - uses base:my-grp; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3-base.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3-base.yang deleted file mode 100644 index bf89889d36..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3-base.yang +++ /dev/null @@ -1,15 +0,0 @@ -module test-uses-leaf-innertype3-base{ - namespace "urn:test:uses:leaf:innertype3:base"; - prefix base; - revision 2017-08-09; - - typedef float32 { - type binary { - length 4; - } - } - - typedef bandwidth { - type float32; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3.yang deleted file mode 100644 index 7be844e8cf..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-leaf-innertype3.yang +++ /dev/null @@ -1,45 +0,0 @@ -module test-uses-leaf-innertype3{ - namespace "urn:test:uses:leaf:innertype3"; - prefix innertype3; - revision 2017-08-09; - import test-uses-leaf-innertype3-base { - prefix base; - } - - typedef protocol-version { - type uint8 { - range 1..7; - } - } - - grouping open-message { - leaf version { - type protocol-version; - default 4; - } - - leaf leaf-union { - type union { - type string; - type int64; - } - } - } - - grouping link-bandwidth-extended-community { - leaf bandwidth { - mandatory true; - type base:bandwidth; - units "bytes per second"; - } - } - - container my-cont { - uses link-bandwidth-extended-community; - } - - notification open { - uses open-message; - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-list.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-list.yang deleted file mode 100644 index 8f55bc228d..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-list.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-uses-list { - yang-version 1.1; - - namespace "urn:test:uses:list"; - prefix test-uses-list; - organization "test.type.org"; - revision "2017-06-30"; - - grouping my-grouping { - list my-list { - key "my-leaf"; - leaf my-leaf { - type string; - } - - leaf my-leaf-two { - type string; - } - } - } - - container my-cont { - uses my-grouping; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement-augment.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement-augment.yang deleted file mode 100644 index 215971c03b..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement-augment.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-uses-statement-augment { - yang-version 1.1; - - namespace "urn:test:uses:statement:augment"; - prefix test-uses-augment; - organization "test.type.org"; - revision "2017-07-07"; - - grouping example { - container nested { - leaf foo { - type string; - } - } - } - - container top { - uses example { - augment nested { - container bar { - } - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement1.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement1.yang deleted file mode 100644 index 86fe51686c..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement1.yang +++ /dev/null @@ -1,19 +0,0 @@ -module test-uses-statement1 { - yang-version 1.1; - - namespace "urn:test:uses:statement1"; - prefix test-uses-statement1; - organization "test.type.org"; - revision "2017-06-30"; - - grouping simple { - container foo; - leaf bar { - type string; - } - } - - container top { - uses simple; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement2.yang b/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement2.yang deleted file mode 100644 index 019263bba9..0000000000 --- a/binding2/mdsal-binding2-generator-impl/src/test/resources/uses-statement/test-uses-statement2.yang +++ /dev/null @@ -1,18 +0,0 @@ -module test-uses-statement2 { - yang-version 1.1; - - namespace "urn:test:uses:statement2"; - prefix test-uses-statement2; - organization "test.type.org"; - revision "2017-06-30"; - - grouping with-inner { - grouping inner { - container cont; - } - uses inner; - } - container top { - uses with-inner; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-util/pom.xml b/binding2/mdsal-binding2-generator-util/pom.xml deleted file mode 100644 index 11bfecf81c..0000000000 --- a/binding2/mdsal-binding2-generator-util/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-generator-util - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - - - org.opendaylight.yangtools - yang-model-api - - - org.opendaylight.yangtools - yang-model-util - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - org.opendaylight.mdsal - mdsal-binding2-util - - - org.opendaylight.yangtools - yang-parser-impl - test - - - org.apache.commons - commons-lang3 - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - !javax.annotation, - * - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/AbstractBaseType.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/AbstractBaseType.java deleted file mode 100644 index 9186a7fd97..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/AbstractBaseType.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * This class represents ancestor for other Types. - */ -@Beta -public abstract class AbstractBaseType implements Type { - - /** - * Name of the package to which this Type belongs. - */ - protected final String packageName; - - /** - * Name of this Type. - */ - protected final String name; - - /** - * Constructs the instance of this class with the concrete package name type - * name. - * - * @param pkName - * string with the package name to which this Type - * belongs - * @param name - * string with the name for this Type - */ - protected AbstractBaseType(final String pkName, final String name, final ModuleContext context) { - requireNonNull(pkName, "Package Name for Generated Type cannot be null!"); - requireNonNull(name, "Name of Generated Type cannot be null!"); - this.packageName = JavaIdentifierNormalizer.normalizeFullPackageName(pkName); - requireNonNull(context, - "In case of not having identifiers normalized, ModuleContext instance must be provided."); - this.name = JavaIdentifierNormalizer.normalizeClassIdentifier(pkName, name, context); - } - - /** - * Constructs the instance of this class with the concrete package name type - * name. - * - * @param pkName - * string with the package name to which this Type - * belongs - * @param name - * string with the name for this Type - * @param isNormalized - * true if pkName and name are normalized - */ - protected AbstractBaseType(final String pkName, final String name, final boolean isNormalized, - final ModuleContext context) { - requireNonNull(pkName, "Package Name for Generated Type cannot be null!"); - requireNonNull(name, "Name of Generated Type cannot be null!"); - if (isNormalized) { - this.packageName = pkName; - this.name = name; - } else { - this.packageName = JavaIdentifierNormalizer.normalizeFullPackageName(pkName); - requireNonNull(context, - "In case of not having identifiers normalized, ModuleContext instance must be provided."); - this.name = JavaIdentifierNormalizer.normalizeClassIdentifier(pkName, name, context); - } - } - - protected AbstractBaseType(final String pkName, final String name, final boolean isPkNameNormalized, - final boolean isTypeNormalized, final ModuleContext context) { - requireNonNull(pkName, "Package Name for Generated Type cannot be null!"); - requireNonNull(name, "Name of Generated Type cannot be null!"); - if (isPkNameNormalized) { - this.packageName = pkName; - } else { - this.packageName = JavaIdentifierNormalizer.normalizeFullPackageName(pkName); - } - - if (isTypeNormalized) { - this.name = name; - } else { - requireNonNull(context, - "In case of not having identifiers normalized ModuleContext instance must be provided."); - this.name = JavaIdentifierNormalizer.normalizeClassIdentifier(pkName, name, context); - } - } - - @Override - public int hashCode() { - return Objects.hash(this.name, this.packageName); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof Type)) { - return false; - } - final Type other = (Type) obj; - return Objects.equals(this.name, other.getName()) && Objects.equals(this.packageName, other.getPackageName()); - } - - - @Override - public String toString() { - if (this.packageName.isEmpty()) { - return "Type (" + this.name + ")"; - } - return "Type (" + this.packageName + "." + this.name + ")"; - } - - @Override - public String getPackageName() { - return this.packageName; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getFullyQualifiedName() { - if (this.packageName.isEmpty()) { - return this.name; - } else { - return this.packageName + "." + this.name; - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingGeneratorUtil.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingGeneratorUtil.java deleted file mode 100644 index 10e59a980c..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingGeneratorUtil.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import com.google.common.annotations.Beta; -import com.google.common.base.CharMatcher; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableList.Builder; -import com.google.common.collect.Interner; -import com.google.common.collect.Interners; -import com.google.common.collect.Iterables; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Optional; -import java.util.regex.Pattern; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.TypeMemberBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -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.type.BinaryTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; -import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; -import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition; -import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition; -import org.opendaylight.yangtools.yang.model.util.type.BaseTypes; -import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder; - -/** - * Standard Util class that contains various method for converting - * input strings to valid JAVA language strings e.g. package names, - * class names, attribute names and/or valid JavaDoc comments. - */ -@Beta -public final class BindingGeneratorUtil { - - private static final CharMatcher GT_MATCHER = CharMatcher.is('>'); - private static final CharMatcher LT_MATCHER = CharMatcher.is('<'); - private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u"); - - private static final Interner PACKAGE_INTERNER = Interners.newWeakInterner(); - private static final Comparator> SUID_MEMBER_COMPARATOR = - Comparator.comparing(TypeMemberBuilder::getName); - - private static final Comparator SUID_NAME_COMPARATOR = - Comparator.comparing(Type::getFullyQualifiedName); - - private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() { - @Override - public Optional getLengthConstraint() { - return Optional.empty(); - } - - @Override - public List getPatternConstraints() { - return Collections.emptyList(); - } - - @Override - public Optional> getRangeConstraint() { - return Optional.empty(); - } - - @Override - public boolean isEmpty() { - return true; - } - }; - - private BindingGeneratorUtil() { - throw new UnsupportedOperationException("Utility class"); - } - - /** - * Encodes angle brackets in yang statement description. - * @param description description of a yang statement which is used to generate javadoc comments - * @return string with encoded angle brackets - */ - public static String encodeAngleBrackets(final String description) { - String newDesc = description; - if (newDesc != null) { - newDesc = LT_MATCHER.replaceFrom(newDesc, "<"); - newDesc = GT_MATCHER.replaceFrom(newDesc, ">"); - } - return newDesc; - } - - public static long computeDefaultSUID(final GeneratedTypeBuilderBase to) { - final ByteArrayOutputStream bout = new ByteArrayOutputStream(); - try (DataOutputStream dout = new DataOutputStream(bout)) { - dout.writeUTF(to.getName()); - dout.writeInt(to.isAbstract() ? 3 : 7); - - for (final Type ifc : sortedCollection(SUID_NAME_COMPARATOR, to.getImplementsTypes())) { - dout.writeUTF(ifc.getFullyQualifiedName()); - } - - for (final GeneratedPropertyBuilder gp : sortedCollection(SUID_MEMBER_COMPARATOR, to.getProperties())) { - dout.writeUTF(gp.getName()); - } - - for (final MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) { - if (!m.getAccessModifier().equals(AccessModifier.PRIVATE)) { - dout.writeUTF(m.getName()); - dout.write(m.getAccessModifier().ordinal()); - } - } - - dout.flush(); - } catch (final IOException e) { - throw new IllegalStateException("Failed to hash object " + to, e); - } - - final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray()); - long hash = 0; - for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { - hash = hash << 8 | hashBytes[i] & 0xFF; - } - return hash; - } - - /** - * Creates package name from specified basePackageName (package - * name for module) and schemaPath. - * - *

- * Resulting package name is concatenation of basePackageName - * and all local names of YANG nodes which are parents of some node for - * which schemaPath is specified. - * - *

- * Based on type of node, there is also possible suffix added in order - * to prevent package name conflicts. - * - * @param basePackageName - * string with package name of the module, MUST be normalized, - * otherwise this method may return an invalid string. - * @param schemaPath - * list of names of YANG nodes which are parents of some node + - * name of this node - * @return string with valid JAVA package name - * @throws NullPointerException if any of the arguments are null - */ - public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath, final - BindingNamespaceType namespaceType) { - - final Iterable pathTowardsRoot = schemaPath.getPathTowardsRoot(); - final Iterable pathFromRoot = schemaPath.getPathFromRoot(); - final int size = Iterables.size(pathTowardsRoot) - 1; - if (size <= 0) { - if (namespaceType != null) { - final StringBuilder sb = new StringBuilder(); - sb.append(basePackageName).append('.').append(namespaceType.getPackagePrefix()); - return JavaIdentifierNormalizer.normalizeFullPackageName(sb.toString()); - } - return JavaIdentifierNormalizer.normalizeFullPackageName(basePackageName); - } - - return generateNormalizedPackageName(basePackageName, pathFromRoot, size, namespaceType); - } - - /** - * Creates package name from specified basePackageName (package - * name for module) and namespaceType. - * - *

- * Resulting package name is concatenation of basePackageName - * and prefix of namespaceType. - * - * @param basePackageName - * string with package name of the module, MUST be normalized, - * otherwise this method may return an invalid string. - * @param namespaceType - * the namespace to which the module belongs - * @return string with valid JAVA package name - * @throws NullPointerException if any of the arguments are null - */ - public static String packageNameWithNamespacePrefix(final String basePackageName, - final BindingNamespaceType namespaceType) { - final StringBuilder sb = new StringBuilder(); - sb.append(basePackageName) - .append('.') - .append(namespaceType.getPackagePrefix()); - return JavaIdentifierNormalizer.normalizeFullPackageName(sb.toString()); - } - - public static Restrictions getRestrictions(final TypeDefinition type) { - if (type == null || type.getBaseType() == null) { - if (type instanceof DecimalTypeDefinition) { - final DecimalTypeDefinition decimal = (DecimalTypeDefinition) type; - final DecimalTypeBuilder tmpBuilder = BaseTypes.decimalTypeBuilder(decimal.getPath()); - tmpBuilder.setFractionDigits(decimal.getFractionDigits()); - final DecimalTypeDefinition tmp = tmpBuilder.build(); - - if (!tmp.getRangeConstraint().equals(decimal.getRangeConstraint())) { - return new Restrictions() { - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Optional> getRangeConstraint() { - return decimal.getRangeConstraint(); - } - - @Override - public List getPatternConstraints() { - return ImmutableList.of(); - } - - @Override - public Optional getLengthConstraint() { - return Optional.empty(); - } - }; - } - } - - return EMPTY_RESTRICTIONS; - } - - final Optional length; - final List pattern; - final Optional> range; - - /* - * Take care of extended types. - * - * Other types which support constraints are check afterwards. There is a slight twist with them, as returned - * constraints are the effective view, e.g. they are inherited from base type. Since the constraint is already - * enforced by the base type, we want to skip them and not perform duplicate checks. - * - * We end up emitting ConcreteType instances for YANG base types, which leads to their constraints not being - * enforced (most notably decimal64). Therefore we need to make sure we do not strip the next-to-last - * restrictions. - */ - if (type instanceof BinaryTypeDefinition) { - final BinaryTypeDefinition binary = (BinaryTypeDefinition)type; - final BinaryTypeDefinition base = binary.getBaseType(); - if (base != null && base.getBaseType() != null) { - length = currentOrEmpty(binary.getLengthConstraint(), base.getLengthConstraint()); - } else { - length = binary.getLengthConstraint(); - } - - pattern = ImmutableList.of(); - range = Optional.empty(); - } else if (type instanceof DecimalTypeDefinition) { - length = Optional.empty(); - pattern = ImmutableList.of(); - - final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type; - final DecimalTypeDefinition base = decimal.getBaseType(); - if (base != null && base.getBaseType() != null) { - range = currentOrEmpty(decimal.getRangeConstraint(), base.getRangeConstraint()); - } else { - range = decimal.getRangeConstraint(); - } - } else if (type instanceof RangeRestrictedTypeDefinition) { - // Integer-like types - length = Optional.empty(); - pattern = ImmutableList.of(); - range = extractRangeConstraint((RangeRestrictedTypeDefinition)type); - } else if (type instanceof StringTypeDefinition) { - final StringTypeDefinition string = (StringTypeDefinition)type; - final StringTypeDefinition base = string.getBaseType(); - if (base != null && base.getBaseType() != null) { - length = currentOrEmpty(string.getLengthConstraint(), base.getLengthConstraint()); - } else { - length = string.getLengthConstraint(); - } - - pattern = uniquePatterns(string); - range = Optional.empty(); - } else { - length = Optional.empty(); - pattern = ImmutableList.of(); - range = Optional.empty(); - } - - // Now, this may have ended up being empty, too... - if (!length.isPresent() && pattern.isEmpty() && !range.isPresent()) { - return EMPTY_RESTRICTIONS; - } - - // Nope, not empty allocate a holder - return new Restrictions() { - @Override - public Optional> getRangeConstraint() { - return range; - } - - @Override - public List getPatternConstraints() { - return pattern; - } - - @Override - public Optional getLengthConstraint() { - return length; - } - - @Override - public boolean isEmpty() { - return false; - } - }; - } - - /** - * Creates package name from specified basePackageName (package - * name for module) and schemaPath which crosses an augmentation. - * - *

- * Resulting package name is concatenation of basePackageName - * and all local names of YANG nodes which are parents of some node for - * which schemaPath is specified. - * - *

- * Based on type of node, there is also possible suffix added in order - * to prevent package name conflicts. - * - * @param basePackageName - * string with package name of the module, MUST be normalized, - * otherwise this method may return an invalid string. - * @param schemaPath - * list of names of YANG nodes which are parents of some node + - * name of this node - * @return string with valid JAVA package name - * @throws NullPointerException if any of the arguments are null - */ - public static String packageNameForAugmentedGeneratedType(final String basePackageName, - final SchemaPath schemaPath) { - final Iterable pathTowardsRoot = schemaPath.getPathTowardsRoot(); - final Iterable pathFromRoot = schemaPath.getPathFromRoot(); - final int size = Iterables.size(pathTowardsRoot); - if (size == 0) { - return basePackageName; - } - - return generateNormalizedPackageName(basePackageName, pathFromRoot, size, BindingNamespaceType.Data); - } - - /** - * Creates package name from parentAugmentPackageName (package - * name for direct parent augmentation) and augmentationSchema . - * - *

- * Resulting package name is concatenation of parentAugmentPackageName - * and the local name of schemaPath. - * - *

- * Based on type of node, there is also possible suffix added in order - * to prevent package name conflicts. - * - * @param parentAugmentPackageName - * string with package name of direct parent augmentation, MUST be normalized, - * otherwise this method may return an invalid string. - * @param augmentationSchema - * augmentation schema which is direct son of parent augmentation. - * @return string with valid JAVA package name - * @throws NullPointerException if any of the arguments are null - */ - public static String packageNameForAugmentedGeneratedType(final String parentAugmentPackageName, - final AugmentationSchemaNode augmentationSchema) { - final QName last = augmentationSchema.getTargetPath().getLastComponent(); - - return generateNormalizedPackageName(parentAugmentPackageName, last); - } - - public static String packageNameForSubGeneratedType(final String basePackageName, final SchemaNode node, - final BindingNamespaceType namespaceType) { - final String parent = packageNameForGeneratedType(basePackageName, node.getPath(), namespaceType); - final QName last = node.getPath().getLastComponent(); - - return generateNormalizedPackageName(parent, last); - } - - public static String replacePackageTopNamespace(final String basePackageName, - final String toReplacePackageName, - final BindingNamespaceType toReplaceNameSpace, - final BindingNamespaceType replacedNameSpace) { - Preconditions.checkArgument(basePackageName != null); - String normalizeBasePackageName = JavaIdentifierNormalizer.normalizeFullPackageName(basePackageName); - - if (!normalizeBasePackageName.equals(toReplacePackageName)) { - final String topPackageName = new StringBuilder(normalizeBasePackageName) - .append('.').append(toReplaceNameSpace.getPackagePrefix()).toString(); - - Preconditions.checkState(toReplacePackageName.equals(topPackageName) - || toReplacePackageName.contains(topPackageName), - "Package name to replace does not belong to the given namespace to replace!"); - - return new StringBuilder(normalizeBasePackageName) - .append('.') - .append(replacedNameSpace.getPackagePrefix()) - .append(toReplacePackageName.substring(topPackageName.length())) - .toString(); - } else { - return new StringBuilder(normalizeBasePackageName) - .append('.').append(replacedNameSpace.getPackagePrefix()).toString(); - } - } - - private static final ThreadLocal SHA1_MD = ThreadLocal.withInitial(() -> { - try { - return MessageDigest.getInstance("SHA"); - } catch (final NoSuchAlgorithmException e) { - throw new IllegalStateException("Failed to get a SHA digest provider", e); - } - }); - - private static String generateNormalizedPackageName(final String base, final Iterable path, final int - size, final BindingNamespaceType namespaceType) { - final StringBuilder builder = new StringBuilder(base); - if (namespaceType != null) { - builder.append('.').append(namespaceType.getPackagePrefix()); - } - final Iterator iterator = path.iterator(); - for (int i = 0; i < size; ++i) { - builder.append('.'); - final String nodeLocalName = iterator.next().getLocalName(); - builder.append(nodeLocalName); - } - final String normalizedPackageName = JavaIdentifierNormalizer.normalizeFullPackageName(builder.toString()); - // Prevent duplication of input - PACKAGE_INTERNER.intern(normalizedPackageName); - return normalizedPackageName; - } - - private static String generateNormalizedPackageName(final String parent, final QName path) { - final StringBuilder sb = new StringBuilder(parent) - .append('.') - .append(path.getLocalName()); - - final String normalizedPackageName = JavaIdentifierNormalizer.normalizeFullPackageName(sb.toString()); - // Prevent duplication of input - PACKAGE_INTERNER.intern(normalizedPackageName); - return normalizedPackageName; - } - - private static Iterable sortedCollection(final Comparator comparator, final Collection input) { - if (input.size() > 1) { - final List ret = new ArrayList<>(input); - ret.sort(comparator); - return ret; - } else { - return input; - } - } - - private static > T currentOrEmpty(final T current, final T base) { - return current.equals(base) ? (T)Optional.empty() : current; - } - - private static List uniquePatterns(final StringTypeDefinition type) { - final List constraints = type.getPatternConstraints(); - if (constraints.isEmpty()) { - return constraints; - } - - final Builder builder = ImmutableList.builder(); - boolean filtered = false; - for (final PatternConstraint c : constraints) { - if (containsConstraint(type.getBaseType(), c)) { - filtered = true; - } else { - builder.add(c); - } - } - - return filtered ? builder.build() : constraints; - } - - private static boolean containsConstraint(final StringTypeDefinition type, final PatternConstraint constraint) { - for (StringTypeDefinition wlk = type; wlk != null; wlk = wlk.getBaseType()) { - if (wlk.getPatternConstraints().contains(constraint)) { - return true; - } - } - - return false; - } - - private static > Optional> - extractRangeConstraint(final T def) { - final T base = (T) def.getBaseType(); - if (base != null && base.getBaseType() != null) { - return currentOrEmpty(def.getRangeConstraint(), base.getRangeConstraint()); - } - - return def.getRangeConstraint(); - } - - public static String replaceAllIllegalChars(final CharSequence stringBuilder) { - final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u"); - return ret.isEmpty() ? "" : ret; - } - -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingTypes.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingTypes.java deleted file mode 100644 index 756b56e2aa..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/BindingTypes.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.parameterizedTypeFor; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.typeForClass; - -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.KeyedInstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.ListAction; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.Output; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeRoot; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.NotificationListener; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.concepts.Identifier; - -public final class BindingTypes { - - public static final ConcreteType ACTION = typeForClass(Action.class); - public static final ConcreteType AUGMENTABLE = typeForClass(Augmentable.class); - public static final ConcreteType AUGMENTATION = typeForClass(Augmentation.class); - public static final ConcreteType IDENTIFIABLE_ITEM = typeForClass(IdentifiableItem.class); - public static final ConcreteType IDENTIFIER = typeForClass(Identifier.class); - public static final ConcreteType IDENTIFIABLE = typeForClass(Identifiable.class); - public static final ConcreteType INPUT = typeForClass(Input.class); - public static final ConcreteType INSTANCE_IDENTIFIER = typeForClass(InstanceIdentifier.class); - public static final ConcreteType INSTANTIABLE = typeForClass(Instantiable.class); - public static final ConcreteType ITEM = typeForClass(Item.class); - public static final ConcreteType KEYED_INSTANCE_IDENTIFIER = typeForClass(KeyedInstanceIdentifier.class); - public static final ConcreteType LIST_ACTION = typeForClass(ListAction.class); - public static final ConcreteType NOTIFICATION = typeForClass(Notification.class); - public static final ConcreteType NOTIFICATION_LISTENER = typeForClass(NotificationListener.class); - public static final ConcreteType OUTPUT = typeForClass(Output.class); - public static final ConcreteType RPC = typeForClass(Rpc.class); - public static final ConcreteType RPC_CALLBACK = typeForClass(RpcCallback.class); - public static final ConcreteType TREE_NODE = typeForClass(TreeNode.class); - public static final ConcreteType TREE_ROOT = typeForClass(TreeRoot.class); - public static final ConcreteType TREE_CHILD_NODE = typeForClass(TreeChildNode.class); - - private BindingTypes() { - throw new UnsupportedOperationException("Utility class"); - } - - public static ParameterizedType augmentable(Type type) { - return parameterizedTypeFor(AUGMENTABLE, type); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/FormattingUtils.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/FormattingUtils.java deleted file mode 100644 index 3045f8664f..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/FormattingUtils.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import com.google.common.annotations.Beta; -import com.google.common.base.CharMatcher; -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import java.util.StringTokenizer; -import java.util.regex.Pattern; -import javax.annotation.RegEx; -import org.opendaylight.yangtools.yang.common.QName; - -/** - * Util class. - */ -@Beta -public final class FormattingUtils { - private static final CharMatcher NEWLINE_OR_TAB = CharMatcher.anyOf("\n\t"); - @RegEx - private static final String SPACES_REGEX = " +"; - private static final Pattern SPACES_PATTERN = Pattern.compile(SPACES_REGEX); - - private FormattingUtils() { - throw new UnsupportedOperationException("Util class"); - } - - public static String formatSchemaPath(final String moduleName, final Iterable schemaPath) { - final StringBuilder sb = new StringBuilder(); - sb.append(moduleName); - - QName currentElement = Iterables.getFirst(schemaPath, null); - for (final QName pathElement : schemaPath) { - sb.append('/'); - if (!currentElement.getNamespace().equals(pathElement.getNamespace())) { - currentElement = pathElement; - sb.append(pathElement); - } else { - sb.append(pathElement.getLocalName()); - } - } - return sb.toString(); - } - - /** - * Used in #yangtemplateformodule.scala.txt for formating revision description. - * - * @param text Content of tag description - * @param nextLineIndent Number of spaces from left side default is 12 - * @return formatted description - */ - public static String formatToParagraph(final String text, final int nextLineIndent) { - if (Strings.isNullOrEmpty(text)) { - return ""; - } - boolean isFirstElementOnNewLineEmptyChar = false; - final StringBuilder sb = new StringBuilder(); - final StringBuilder lineBuilder = new StringBuilder(); - final String lineIndent = Strings.repeat(" ", nextLineIndent); - final String textToFormat = NEWLINE_OR_TAB.removeFrom(text); - final String formattedText = SPACES_PATTERN.matcher(textToFormat).replaceAll(" "); - final StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true); - - while (tokenizer.hasMoreElements()) { - final String nextElement = tokenizer.nextElement().toString(); - - if (lineBuilder.length() + nextElement.length() > 80) { - // Trim trailing whitespace - for (int i = lineBuilder.length() - 1; i >= 0 && lineBuilder.charAt(i) != ' '; --i) { - lineBuilder.setLength(i); - } - // Trim leading whitespace - while (lineBuilder.charAt(0) == ' ') { - lineBuilder.deleteCharAt(0); - } - sb.append(lineBuilder).append('\n'); - lineBuilder.setLength(0); - - if (nextLineIndent > 0) { - sb.append(lineIndent); - } - - if (" ".equals(nextElement)) { - isFirstElementOnNewLineEmptyChar = true; - } - } - if (isFirstElementOnNewLineEmptyChar) { - isFirstElementOnNewLineEmptyChar = false; - } else { - lineBuilder.append(nextElement); - } - } - return sb.append(lineBuilder).append('\n').toString(); - } - - /** - * Used in all yangtemplates for formating augmentation target. - * - * @param schemaPath path to augmented node - * @return path in string format - */ - public static String formatToAugmentPath(final Iterable schemaPath) { - final StringBuilder sb = new StringBuilder(); - for (final QName pathElement : schemaPath) { - sb.append('/').append(pathElement.getLocalName()); - } - return sb.toString(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifier.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifier.java deleted file mode 100644 index 06d6d05abe..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifier.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import com.google.common.annotations.Beta; - -/** - * Types of java identifier: - *

    - *
  • class
  • - *
  • interface
  • - *
  • enum
  • - *
  • enum value
  • - *
  • method
  • - *
  • variable
  • - *
  • constant
  • - *
  • package
  • - *
. - */ -@Beta -public enum JavaIdentifier { - - CLASS, INTERFACE, ENUM, ENUM_VALUE, METHOD, VARIABLE, CONSTANT, PACKAGE -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizer.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizer.java deleted file mode 100644 index 714807bd83..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizer.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import com.google.common.annotations.Beta; -import com.google.common.base.CharMatcher; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ListMultimap; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration.Pair; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; - -/** - * This util class converts every non-java char in identifier to java char by - * its unicode name (JAVA SE - * SPECIFICATIONS - Identifiers). There are special types of mapping - * non-java chars to original identifiers according to specific - * {@linkplain JavaIdentifier java type}: - *
    - *
  • class, enum, interface
  • - *
  • - *
      - *
    • without special separator
    • - *
    • the first character of identifier, any other first character of - * identifier part mapped by non-Java char name from unicode and char in - * identifier behind non-java char name are converting to upper case
    • - *
    • examples:
    • - *
    • - *
        - *
      • example* - ExampleAsterisk
      • - *
      • example*example - ExampleAserisksExample
      • - *
      • \example - ReverseSolidusExample
      • - *
      • 1example - DigitOneExample
      • - *
      • example1 - Example1
      • - *
      • int - IntReservedKeyword
      • - *
      • con - ConReservedKeyword
      • - *
      - *
    • - *
    - *
  • - *
  • enum value, constant
  • - *
  • - *
      - *
    • used underscore as special separator
    • - *
    • converted identifier to upper case
    • - *
    • examples:
    • - *
    • - *
        - *
      • example* - EXAMPLE_ASTERISK
      • - *
      • example*example - EXAMPLE_ASTERISK_EXAMPLE
      • - *
      • \example - REVERSE_SOLIDUS_EXAMPLE
      • - *
      • 1example - DIGIT_ONE_EXAMPLE
      • - *
      • example1 - EXAMPLE1
      • - *
      • int - INT_RESERVED_KEYWORD
      • - *
      • con - CON_RESERVED_KEYWORD
      • - *
      - *
    • - *
    - *
  • - *
  • method, variable
  • - *
  • - *
  • - *
      - *
    • without special separator
    • - *
    • the first character of identifier is converting to lower case
    • - *
    • any other first character of identifier part mapped by non-Java char name - * from unicode and char in identifier behind non-java char name are converting - * to upper case
    • - *
    • examples:
    • - *
    • - *
        - *
      • example* - exampleAsterisk
      • - *
      • example*example - exampleAserisksExample
      • - *
      • \example - reverseSolidusExample
      • - *
      • 1example - digitOneExample
      • - *
      • example1 - example1
      • - *
      • int - intReservedKeyword
      • - *
      • con - conReservedKeyword
      • - *
      - *
    • - *
    - *
  • - *
  • package - full package name ( - * Naming a package)
  • - *
  • - *
  • - *
      - *
    • parts of package name are separated by dots
    • - *
    • parts of package name are converting to lower case
    • - *
    • if parts of package name are reserved Java or Windows keywords, such as - * 'int' the suggested convention is to add an underscore to keyword
    • - *
    • dash is parsed as underscore according to - * Naming a package
    • - *
    • examples:
    • - *
    • - *
        - *
      • org.example* - org.exampleasterisk
      • - *
      • org.example*example - org.exampleasteriskexample
      • - *
      • org.\example - org.reversesolidusexample
      • - *
      • org.1example - org.digitoneexample
      • - *
      • org.example1 - org.example1
      • - *
      • org.int - org.int_
      • - *
      • org.con - org.con_
      • - *
      • org.foo-cont - org.foo_cont
      • - *
      - *
    • - *
    - *
  • - *
- * - *

- * There is special case in CLASS, INTERFACE, ENUM, ENUM VALUE, CONSTANT, METHOD - * and VARIABLE if identifier contains single dash - then the converter ignores - * the single dash in the way of the non-java chars. In other way, if dash is - * the first or the last char in the identifier or there is more dashes in a row - * in the identifier, then these dashes are converted as non-java chars. - * Example: - *

    - *
  • class, enum, interface
  • - *
  • - *
      - *
    • foo-cont - FooCont
    • - *
    • foo--cont - FooHyphenMinusHyphenMinusCont
    • - *
    • -foo - HyphenMinusFoo
    • - *
    • foo- - FooHyphenMinus
    • - *
    - *
  • - *
  • enum value, constant - *
  • - *
      - *
    • foo-cont - FOO_CONT
    • - *
    • foo--cont - FOO_HYPHEN_MINUS_HYPHEN_MINUS_CONT
    • - *
    • -foo - HYPHEN_MINUS_FOO
    • - *
    • foo- - FOO_HYPHEN_MINUS
    • - *
    - *
  • - *
  • method, variable
  • - *
  • - *
      - *
    • foo-cont - fooCont
    • - *
    • foo--cont - fooHyphenMinusHyphenMinusCont
    • - *
    • -foo - hyphenMinusFoo
    • - *
    • foo- - fooHyphenMinus
    • - *
    - *
  • - *
- * - *

- * Next special case talks about normalizing class name which already exists in - * package - but with different camel cases (foo, Foo, fOo, ...). To every next - * classes with same names will by added their actual rank (serial number), - * except the first one. This working for CLASS, ENUM and INTEFACE java - * identifiers. If there exist the same ENUM VALUES in ENUM (with different - * camel cases), then it's parsed with same logic like CLASSES, ENUMS and - * INTERFACES but according to list of pairs of their ENUM parent. Example: - * - *

    - *
  • class, enum, interface
  • - *
  • - *
      - *
    • package name org.example, class (or interface or enum) Foo - normalized - * to Foo - *
    • package name org.example, class (or interface or enum) fOo - normalized - * to Foo1 - *
    - *
  • - *
  • enum value
  • - *
  • - *
      - *
    • - * - *
      - * type enumeration {
      - *     enum foo;
      - *     enum Foo;
      - * }
      - * 
      - * - *
    • - *
    • YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum - * values.
    • - *
    - *
  • - *
- */ -@Beta -public final class JavaIdentifierNormalizer { - - public static final Set SPECIAL_RESERVED_PATHS = ImmutableSet.of( - "org.opendaylight.yangtools.concepts", - "org.opendaylight.yangtools.yang.common", - "org.opendaylight.yangtools.yang.model", - "org.opendaylight.mdsal.binding.javav2.spec", - "java", - "com"); - - private static final char UNDERSCORE = '_'; - private static final char DASH = '-'; - private static final String RESERVED_KEYWORD = "reserved_keyword"; - private static final Set PRIMITIVE_TYPES = ImmutableSet.of("char[]", "byte[]"); - - private static final CharMatcher DASH_MATCHER = CharMatcher.is(DASH); - private static final CharMatcher DASH_OR_SPACE_MATCHER = CharMatcher.anyOf(" -"); - private static final CharMatcher UNDERSCORE_MATCHER = CharMatcher.is(UNDERSCORE); - private static final Splitter DOT_SPLITTER = Splitter.on('.'); - private static final Splitter UNDERSCORE_SPLITTER = Splitter.on(UNDERSCORE); - - private static final Pattern DOUBLE_UNDERSCORE_PATTERN = Pattern.compile("__", Pattern.LITERAL); - - // Converted to lower case - private static final Set WINDOWS_RESERVED_WORDS = BindingMapping.WINDOWS_RESERVED_WORDS.stream() - .map(String::toLowerCase).collect(ImmutableSet.toImmutableSet()); - - private JavaIdentifierNormalizer() { - throw new UnsupportedOperationException("Util class"); - } - - /** - *

- * According to YANG RFC 7950, - * all assigned names in an enumeration MUST be unique. Created names are contained in the list - * of {@link Enumeration.Pair}. This method adds actual index with underscore behind name of new - * enum value only if this name already exists in one of the list of {@link Enumeration.Pair}. - * Then, the name will be converted to java chars according to {@link JavaIdentifier#ENUM_VALUE} - * and returned. - *

- * Example: - * - *
-     * type enumeration {
-     *     enum foo;
-     *     enum Foo;
-     * }
-     * 
- * - *

- * YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum values. - * - * @param name - * - name of new enum value - * @param values - * - list of all actual enum values - * @return converted and fixed name of new enum value - */ - public static String normalizeEnumValueIdentifier(final String name, final List values) { - return convertIdentifierEnumValue(name, name, values, 1); - } - - /** - * Normalizing full package name by non java chars and reserved keywords. - * - * @param fullPackageName - * - full package name - * @return normalized name - */ - public static String normalizeFullPackageName(final String fullPackageName) { - final Iterator it = DOT_SPLITTER.split(fullPackageName).iterator(); - if (!it.hasNext()) { - return fullPackageName; - } - - final StringBuilder sb = new StringBuilder(fullPackageName.length()); - while (true) { - String next = it.next(); - sb.append(normalizePartialPackageName(next)); - if (!it.hasNext()) { - return sb.toString(); - } - - if (!next.isEmpty()) { - sb.append('.'); - } - } - } - - /** - * Normalizing part of package name by non java chars. - * - * @param packageNamePart - * - part of package name - * @return normalized name - */ - static String normalizePartialPackageName(final String packageNamePart) { - // if part of package name consist from java or windows reserved word, return it with - // underscore at the end and in lower case - final String lowerPart = packageNamePart.toLowerCase(); - if (BindingMapping.JAVA_RESERVED_WORDS.contains(lowerPart) || WINDOWS_RESERVED_WORDS.contains(lowerPart)) { - return lowerPart + UNDERSCORE; - } - - final String normalizedPart = DASH_MATCHER.replaceFrom(packageNamePart, UNDERSCORE); - - final StringBuilder sb = new StringBuilder(); - final StringBuilder innerSb = new StringBuilder(); - for (int i = 0; i < normalizedPart.length(); i++) { - final char c = normalizedPart.charAt(i); - if (c == UNDERSCORE) { - if (innerSb.length() != 0) { - sb.append(normalizeSpecificIdentifier(innerSb.toString(), JavaIdentifier.PACKAGE)); - innerSb.setLength(0); - } - sb.append(UNDERSCORE); - } else { - innerSb.append(c); - } - } - if (innerSb.length() != 0) { - sb.append(normalizeSpecificIdentifier(innerSb.toString(), JavaIdentifier.PACKAGE)); - } - // returned normalized part of package name - return sb.toString(); - } - - /** - * Find and convert non Java chars in identifiers of generated transfer objects, initially - * derived from corresponding YANG according to - * Java - * Specifications - Identifiers. If there is more same class names at the same package, then - * append rank (serial number) to the end of them. Works for class, enum, interface. - * - * @param packageName - * - package of identifier - * @param className - * - name of identifier - * @return - java acceptable identifier - */ - static String normalizeClassIdentifier(final String packageName, final String className, - final ModuleContext context) { - if (packageName.isEmpty() && PRIMITIVE_TYPES.contains(className)) { - return className; - } - for (final String reservedPath : SPECIAL_RESERVED_PATHS) { - if (packageName.startsWith(reservedPath)) { - return className; - } - } - final String convertedClassName = normalizeSpecificIdentifier(className, JavaIdentifier.CLASS); - - // if packageName contains class name at the end, then the className is name of inner class - final String basePackageName; - final int lastDot = packageName.lastIndexOf('.'); - if (lastDot != -1 && Character.isUpperCase(packageName.charAt(lastDot + 1))) { - // ignore class name in package name - inner class name has to be normalized according to original package - // of parent class - basePackageName = packageName.substring(0, lastDot); - } else { - basePackageName = packageName; - } - - return normalizeClassIdentifier(basePackageName, convertedClassName, convertedClassName, 1, context); - } - - /** - * Checking while there doesn't exist any class name with the same name - * (regardless of camel cases) in package. - * - * @param packageName - * - package of class name - * @param origClassName - * - original class name - * @param actualClassName - * - actual class name with rank (serial number) - * @param rank - * - actual rank (serial number) - * @return converted identifier - */ - private static String normalizeClassIdentifier(final String packageName, final String origClassName, - final String actualClassName, final int rank, final ModuleContext context) { - - final ListMultimap packagesMap = context.getPackagesMap(); - - synchronized (packagesMap) { - if (packagesMap.containsKey(packageName)) { - for (final String existingName : packagesMap.get(packageName)) { - if (actualClassName.equalsIgnoreCase(existingName)) { - return normalizeClassIdentifier(packageName, origClassName, origClassName + rank, - rank + 1, context); - } - } - } - context.putToPackagesMap(packageName, actualClassName); - return actualClassName; - } - } - - /** - * Find and convert non Java chars in identifiers of generated transfer objects, initially - * derived from corresponding YANG. - * - * @param identifier - * - name of identifier - * @param javaIdentifier - * - java type of identifier - * @return - java acceptable identifier - */ - public static String normalizeSpecificIdentifier(final String identifier, final JavaIdentifier javaIdentifier) { - // if identifier isn't PACKAGE type then check it by reserved keywords - if (javaIdentifier != JavaIdentifier.PACKAGE) { - final String lower = identifier.toLowerCase(); - if (BindingMapping.JAVA_RESERVED_WORDS.contains(lower) || WINDOWS_RESERVED_WORDS.contains(lower)) { - return fixCasesByJavaType(lower + UNDERSCORE + RESERVED_KEYWORD, javaIdentifier); - } - } - - // check and convert first char in identifier if there is non-java char - final StringBuilder sb = new StringBuilder(); - final char firstChar = identifier.charAt(0); - if (!Character.isJavaIdentifierStart(firstChar)) { - // converting first char of identifier - sb.append(convertFirst(firstChar, existNext(identifier, 0))); - } else { - sb.append(firstChar); - } - // check and convert other chars in identifier, if there is non-java char - for (int i = 1; i < identifier.length(); i++) { - final char actualChar = identifier.charAt(i); - // ignore single dash as non java char - if there is more dashes in a row or dash is as - // the last char in identifier then parse these dashes as non java chars - if (actualChar == DASH && existNext(identifier, i)) { - if (identifier.charAt(i - 1) != DASH && identifier.charAt(i + 1) != DASH) { - sb.append(UNDERSCORE); - continue; - } - } - if (!Character.isJavaIdentifierPart(actualChar)) { - // prepare actual string of sb for checking if underscore exist on position of the last char - sb.append(convert(actualChar, existNext(identifier, i), sb.charAt(sb.length() - 1))); - } else { - sb.append(actualChar); - } - } - - // apply camel case in appropriate way - return fixCasesByJavaType(DOUBLE_UNDERSCORE_PATTERN.matcher(sb).replaceAll("_").toLowerCase(), javaIdentifier); - } - - /** - * Fix cases of converted identifiers by Java type. - * - * @param convertedIdentifier - * - converted identifier - * @param javaIdentifier - * - java type of identifier - * @return converted identifier with right cases according to java type - */ - private static String fixCasesByJavaType(final String convertedIdentifier, final JavaIdentifier javaIdentifier) { - switch (javaIdentifier) { - case CLASS: - case ENUM: - case INTERFACE: - return capitalize(fixCases(convertedIdentifier)); - case ENUM_VALUE: - case CONSTANT: - return convertedIdentifier.toUpperCase(); - case METHOD: - case VARIABLE: - return fixCases(convertedIdentifier); - case PACKAGE: - return UNDERSCORE_MATCHER.removeFrom(convertedIdentifier); - default: - throw new IllegalArgumentException("Unknown java type of identifier : " + javaIdentifier.toString()); - } - } - - /** - * Delete unnecessary chars in converted identifier and apply camel case in appropriate way. - * - * @param convertedIdentifier - * - original converted identifier - * @return resolved identifier - */ - private static String fixCases(final String convertedIdentifier) { - if (convertedIdentifier.indexOf(UNDERSCORE) == -1) { - return convertedIdentifier; - } - - final StringBuilder sb = new StringBuilder(convertedIdentifier.length()); - final Iterator it = UNDERSCORE_SPLITTER.split(convertedIdentifier).iterator(); - sb.append(it.next()); - while (it.hasNext()) { - sb.append(capitalize(it.next())); - } - return sb.toString(); - } - - /** - * Check if there exist next char in identifier behind actual char position. - * - * @param identifier - * - original identifier - * @param actual - * - actual char position - * @return true if there is another char, false otherwise - */ - private static boolean existNext(final String identifier, final int actual) { - return identifier.length() > actual + 1; - } - - /** - * Converting first char of identifier. This happen only if this char is - * non-java char. - * - * @param firstChar - * - first char - * @param existNext - * - existing of next char behind actual char - * @return converted char - */ - private static String convertFirst(final char firstChar, final boolean existNext) { - final String name = DASH_OR_SPACE_MATCHER.replaceFrom(Character.getName(firstChar), UNDERSCORE); - return existNext ? name + '_' : name; - } - - /** - * Converting any char in java identifier, This happen only if this char is - * non-java char. - * - * @param actualChar - * - actual char - * @param existNext - * - existing of next char behind actual char - * @param partialLastChar - * - last char of partial converted identifier - * @return converted char - */ - private static String convert(final char actualChar, final boolean existNext, final char partialLastChar) { - return partialLastChar == '_' ? convertFirst(actualChar, existNext) : "_" + convertFirst(actualChar, existNext); - } - - /** - * Capitalize input string. - * - * @param identifier - * - string to be capitalized - */ - private static String capitalize(final String identifier) { - return identifier.substring(0, 1).toUpperCase() + identifier.substring(1); - } - - private static String convertIdentifierEnumValue(final String name, final String origName, final List values, - final int rank) { - String newName = name; - for (final Pair pair : values) { - if (name.equalsIgnoreCase(pair.getName()) || name.equalsIgnoreCase(pair.getMappedName())) { - int actualRank = rank; - final String actualName = origName + UNDERSCORE + actualRank; - newName = convertIdentifierEnumValue(actualName, origName, values, ++actualRank); - } - } - return normalizeSpecificIdentifier(newName, JavaIdentifier.ENUM_VALUE); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/ReferencedTypeImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/ReferencedTypeImpl.java deleted file mode 100644 index 2a326a46f8..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/ReferencedTypeImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; - -/** - * Wraps combination of packageName and name to the - * object representation. - * - */ -public final class ReferencedTypeImpl extends AbstractBaseType { - - /** - * Creates instance of this class with concrete package name and type name. - * - * @param packageName - * string with the package name - * @param name - * string with the name for referenced type - */ - public ReferencedTypeImpl(String packageName, String name, ModuleContext context) { - super(packageName, name, context); - } - - /** - * Creates instance of this class with concrete package name and type name - * for already normalized identifier. - * - * @param packageName - * string with the package name - * @param name - * string with the name for referenced type - * @param isNormalized - * indicates if identifier name is normalized - */ - public ReferencedTypeImpl(String packageName, String name, boolean isNormalized, ModuleContext context) { - super(packageName, name, isNormalized, context); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ReferencedTypeImpl [packageName="); - builder.append(getPackageName()); - builder.append(", name="); - builder.append(getName()); - builder.append(']'); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/TypeComments.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/TypeComments.java deleted file mode 100644 index 9543ea5646..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/TypeComments.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.replaceAllIllegalChars; -import static org.opendaylight.mdsal.binding.javav2.generator.util.FormattingUtils.formatToParagraph; - -import com.google.common.annotations.Beta; -import com.google.common.escape.Escaper; -import com.google.common.escape.Escapers; -import java.util.Optional; -import java.util.regex.Pattern; -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode; - -/** - * Utility methods for creating {@link TypeComment}s. - */ -@Beta -@NonNullByDefault -public final class TypeComments { - private static final Escaper ENTITY_ESCAPER = Escapers.builder() - .addEscape('<', "<") - .addEscape('>', ">") - .addEscape('&', "&") - .addEscape('@', "@").build(); - private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL); - - private TypeComments() { - //Defeat initialization. - } - - /** - * Create a {@link TypeComment} for a javadoc-compliant text snippet. This snippet must be eligible for direct - * inclusion in a Java comment without further escaping. - * - * @param javadoc Pre-formatted javadoc snippet - * @return {@link TypeComment}, or empty if the snippet was empty - */ - public static Optional javadoc(final String javadoc) { - return javadoc.isEmpty() ? Optional.empty() : Optional.of(() -> javadoc); - } - - /** - * Create a {@link TypeComment} for a {@link DocumentedNode}'s description string. - * - * @param node Documented node containing the description to be processed - * @return {@link TypeComment}, or empty if the node's description was empty or non-present. - */ - public static Optional description(final DocumentedNode node) { - final String description = node.getDescription().orElse(""); - return description.isEmpty() ? Optional.empty() : Optional.of(() -> replaceAllIllegalChars( - formatToParagraph( - TAIL_COMMENT_PATTERN.matcher(ENTITY_ESCAPER.escape(description)).replaceAll("*/"), 0))); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/Types.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/Types.java deleted file mode 100644 index ff58d6cffa..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/Types.java +++ /dev/null @@ -1,453 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.ImmutableList; -import com.google.common.collect.ImmutableRangeSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Range; -import com.google.common.collect.RangeSet; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.BaseTypeWithRestrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.WildcardType; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; -import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; -import org.w3c.dom.Document; - -@Beta -public final class Types { - private static final CacheLoader, ConcreteType> TYPE_LOADER = - new CacheLoader, ConcreteType>() { - - @Override - public ConcreteType load(@Nonnull final Class key) throws Exception { - return new ConcreteTypeImpl(key.getPackage().getName(), key.getSimpleName(), null); - } - }; - - private static final LoadingCache, ConcreteType> TYPE_CACHE = - CacheBuilder.newBuilder().weakKeys().build(TYPE_LOADER); - - public static final ConcreteType BOOLEAN = typeForClass(Boolean.class); - public static final ConcreteType CLASS = typeForClass(Class.class); - public static final ConcreteType STRING = typeForClass(String.class); - public static final ConcreteType VOID = typeForClass(Void.class); - public static final ConcreteType DOCUMENT = typeForClass(Document.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('.'); - private static final Type SET_TYPE = typeForClass(Set.class); - private static final Type LIST_TYPE = typeForClass(List.class); - private static final Type MAP_TYPE = typeForClass(Map.class); - - private Types() { - throw new UnsupportedOperationException("Utility class"); - } - - /** - * Creates the instance of type - * {@link ConcreteType - * ConcreteType} which represents JAVA void type. - * - * @return ConcreteType instance which represents JAVA - * void - */ - public static ConcreteType voidType() { - return VOID; - } - - /** - * Creates the instance of type - * {@link ConcreteType - * ConcreteType} which represents primitive JAVA type for which package - * doesn't exist. - * - * @param primitiveType string containing programmatic construction based on - * primitive type (e.g byte[]) - * @return ConcreteType instance which represents programmatic - * construction with primitive JAVA type - */ - public static ConcreteType primitiveType(final String primitiveType, final Restrictions restrictions) { - return new ConcreteTypeImpl("", primitiveType, restrictions); - } - - /** - * Returns an instance of {@link ConcreteType} describing the class. - * - * @param cls Class to describe - * @return Description of class - */ - public static ConcreteType typeForClass(final Class cls) { - return TYPE_CACHE.getUnchecked(cls); - } - - - public static ConcreteType typeForClass(final Class cls, final Restrictions restrictions) { - if (restrictions == null) { - return typeForClass(cls); - } - if (restrictions instanceof DefaultRestrictions) { - return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions); - } else { - return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions); - } - } - - public static ConcreteType typeForClass(final Class cls, final Restrictions restrictions, - final ModuleContext moduleContext) { - if (restrictions == null) { - return typeForClass(cls); - } - if (restrictions instanceof DefaultRestrictions) { - return new ConcreteTypeImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions); - } else { - return new BaseTypeWithRestrictionsImpl(cls.getPackage().getName(), cls.getSimpleName(), restrictions, - moduleContext); - } - } - - /** - * Returns an instance of {@link ParameterizedType} describing the typed. - * {@link Map}<K,V> - * - * @param keyType Key Type - * @param valueType Value Type - * @return Description of generic type instance - */ - public static ParameterizedType mapTypeFor(final Type keyType, final Type valueType) { - return parameterizedTypeFor(MAP_TYPE, keyType, valueType); - } - - /** - * Returns an instance of {@link ParameterizedType} describing the typed - * {@link Set}<V> with concrete type of value. - * - * @param valueType Value Type - * @return Description of generic type instance of Set - */ - public static ParameterizedType setTypeFor(final Type valueType) { - return parameterizedTypeFor(SET_TYPE, valueType); - } - - /** - * Returns an instance of {@link ParameterizedType} describing the typed - * {@link List}<V> with concrete type of value. - * - * @param valueType Value Type - * @return Description of type instance of List - */ - public static ParameterizedType listTypeFor(final Type valueType) { - return parameterizedTypeFor(LIST_TYPE, valueType); - } - - /** - * Creates instance of type {@link ParameterizedType ParameterizedType}. - * - * @param type JAVA Type for raw type - * @param parameters JAVA Types for actual parameter types - * @return ParametrizedType reprezentation of type - * and its parameters parameters - */ - public static ParameterizedType parameterizedTypeFor(final Type type, final Type... parameters) { - return new ParameterizedTypeImpl(type, parameters); - } - - /** - * Creates instance of type {@link WildcardType WildcardType}. - * - * @param packageName string with the package name - * @param typeName string with the type name - * @return WildcardType representation of - * packageName and typeName - */ - public static WildcardType wildcardTypeFor(final String packageName, final String typeName) { - return new WildcardTypeImpl(packageName, typeName); - } - - /** - * Creates instance of type {@link WildcardType WildcardType}. - * - * @param packageName string with the package name - * @param typeName string with the type name - * @param isPkNameNormalized if the package name has been normalized - * @param isTypeNormalized if the type name has been normalized - * @return WildcardType representation of - * packageName and typeName - */ - public static WildcardType wildcardTypeFor(final String packageName, final String typeName, - final boolean isPkNameNormalized, final boolean isTypeNormalized, - final ModuleContext context) { - return new WildcardTypeImpl(packageName, typeName, isPkNameNormalized, isTypeNormalized, context); - } - - /** - * Creates instance of - * {@link ParameterizedType - * ParameterizedType} where raw type is - * {@link Augmentable} and actual - * parameter is valueType. - * - * @param valueType JAVA Type with actual parameter - * @return ParametrizedType representation of raw type - * Augmentable with actual parameter - * valueType - */ - public static ParameterizedType augmentableTypeFor(final Type valueType) { - final Type augmentable = typeForClass(Augmentable.class); - return parameterizedTypeFor(augmentable, valueType); - } - - /** - * Creates instance of - * {@link ParameterizedType - * ParameterizedType} where raw type is - * {@link Augmentation} and actual - * parameter is valueType. - * - * @param valueType JAVA Type with actual parameter - * @return ParametrizedType reprezentation of raw type - * Augmentation with actual parameter - * valueType - */ - public static ParameterizedType augmentationTypeFor(final Type valueType) { - final Type augmentation = typeForClass(Augmentation.class); - return parameterizedTypeFor(augmentation, valueType); - } - - @Nullable - public static String getOuterClassName(final Type valueType) { - final String pkgName = valueType.getPackageName(); - final int index = CharMatcher.javaUpperCase().indexIn(pkgName); - if (index >= 0) { - // It is inner class. - return Iterables.getFirst(DOT_SPLITTER.split(pkgName.substring(index)), null); - } - return null; - } - - @Nullable - public static String getOuterClassPackageName(final Type valueType) { - final String pkgName = valueType.getPackageName(); - final int index = CharMatcher.javaUpperCase().indexIn(pkgName); - if (index >= 1) { - return pkgName.substring(0, index - 1); - } - return pkgName; - } - - /** - * Represents concrete JAVA type. - */ - private static final class ConcreteTypeImpl extends AbstractBaseType implements ConcreteType { - - private final Restrictions restrictions; - - /** - * Creates instance of this class with package pkName and - * with the type name name. - * - * @param pkName string with package name - * @param name string with the name of the type - */ - private ConcreteTypeImpl(final String pkName, final String name, final Restrictions restrictions) { - super(pkName, name, true, null); - this.restrictions = restrictions; - } - - @Override - public Restrictions getRestrictions() { - return this.restrictions; - } - } - - /** - * Represents concrete JAVA type with changed restriction values. - */ - private static final class BaseTypeWithRestrictionsImpl extends AbstractBaseType implements - BaseTypeWithRestrictions { - private final Restrictions restrictions; - - /** - * Creates instance of this class with package pkName and - * with the type name name. - * - * @param pkName string with package name - * @param name string with the name of the type - */ - private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions) { - super(pkName, name, null); - this.restrictions = requireNonNull(restrictions); - } - - private BaseTypeWithRestrictionsImpl(final String pkName, final String name, final Restrictions restrictions, - final ModuleContext moduleContext) { - super(pkName, name, moduleContext); - this.restrictions = requireNonNull(restrictions); - } - - @Override - public Restrictions getRestrictions() { - return this.restrictions; - } - } - - /** - * Represents parametrized JAVA type. - */ - private static class ParameterizedTypeImpl extends AbstractBaseType implements ParameterizedType { - /** - * Array of JAVA actual type parameters. - */ - private final Type[] actualTypes; - - /** - * JAVA raw type (like List, Set, Map...). - */ - private final Type rawType; - - /** - * Creates instance of this class with concrete rawType and array of - * actual parameters. - * - * @param rawType JAVA Type for raw type - * @param actTypes array of actual parameters - */ - ParameterizedTypeImpl(final Type rawType, final Type[] actTypes) { - super(rawType.getPackageName(), rawType.getName(), true, null); - this.rawType = rawType; - this.actualTypes = actTypes.clone(); - } - - @Override - public Type[] getActualTypeArguments() { - - return this.actualTypes; - } - - @Override - public Type getRawType() { - return this.rawType; - } - } - - /** - * Represents JAVA bounded wildcard type. - */ - private static class WildcardTypeImpl extends AbstractBaseType implements WildcardType { - /** - * Creates instance of this class with concrete package and type name. - * - * @param packageName string with the package name - * @param typeName string with the name of type - */ - //FIXME: doesn't seem to be called at all - WildcardTypeImpl(final String packageName, final String typeName) { - super(packageName, typeName, null); - } - - /** - * Creates instance of this class with concrete package and type name. - * - * @param packageName string with the package name - * @param typeName string with the name of type - * @param isPkNameNormalized if the package name has been normalized - * @param isTypeNormalized if the type name has been normalized - */ - WildcardTypeImpl(final String packageName, final String typeName, final boolean isPkNameNormalized, - final boolean isTypeNormalized, final ModuleContext context) { - super(packageName, typeName, isPkNameNormalized, isTypeNormalized, context); - } - } - - public static > DefaultRestrictions getDefaultRestrictions(final T min, - final T max) { - return new DefaultRestrictions<>(min, max); - } - - private static final class DefaultRestrictions> implements Restrictions { - private final RangeConstraint rangeConstraint; - - private DefaultRestrictions(final T min, final T max) { - requireNonNull(min); - requireNonNull(max); - this.rangeConstraint = new RangeConstraint() { - - @Override - public Optional getErrorAppTag() { - return Optional.empty(); - } - - @Override - public Optional getErrorMessage() { - return Optional.empty(); - } - - @Override - public Optional getDescription() { - return Optional.empty(); - } - - @Override - public Optional getReference() { - return Optional.empty(); - } - - @Override - public RangeSet getAllowedRanges() { - return ImmutableRangeSet.of(Range.closed(min, max)); - } - }; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Optional> getRangeConstraint() { - return Optional.ofNullable(rangeConstraint); - } - - @Override - public List getPatternConstraints() { - return ImmutableList.of(); - } - - @Override - public Optional getLengthConstraint() { - return Optional.empty(); - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleaner.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleaner.java deleted file mode 100644 index 8f60f22bdd..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleaner.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import com.google.common.annotations.Beta; -import java.util.regex.Pattern; -import javax.annotation.RegEx; -import org.apache.commons.lang3.StringUtils; - -/** - * Utility class for cleaning yang models of excess whitespaces. - */ -@Beta -public final class YangSnippetCleaner { - - private static final String[] RESERVED_LINES = { "yang-version", "namespace" }; - - @RegEx - private static final String NEW_LINE_REGEX = "\\r?\\n"; - private static final Pattern NEW_LINE_PATTERN = Pattern.compile(NEW_LINE_REGEX); - - @RegEx - private static final String WS_REGEX = "\\s+"; - private static final Pattern WS_PATTERN = Pattern.compile(WS_REGEX); - - private static final String START_BODY = "{"; - private static final String END_BODY = "}"; - private static final String KEY_PART = "key \""; - private static final String UNIQUE_PART = "unique \""; - private static final String SPECIAL_END_LINE = "\";"; - - private static final char NEW_LINE = '\n'; - private static final char SPACE = ' '; - - private static final int INDENT = 4; - - private YangSnippetCleaner() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Cleaning yang model of excess whitespaces, adding indentations. - * - * @param unformedYang - * - unformed yang model - * @return cleaned yang model - */ - public static String clean(final String unformedYang) { - int indentCount = 0; - final StringBuilder sb = new StringBuilder(); - final String[] splitter = NEW_LINE_PATTERN.split(unformedYang); - - for (int i = 0; i < splitter.length; i++) { - if (!StringUtils.isBlank(splitter[i])) { - String line = cleanLine(splitter[i]); - if (START_BODY.equals(line)) { - indentCount = mergeWithPrevious(sb, indentCount); - continue; - } - if ((line.contains(KEY_PART) || line.contains(UNIQUE_PART)) && line.endsWith(SPECIAL_END_LINE)) { - line = new StringBuilder(line.substring(0, line.indexOf(SPECIAL_END_LINE) - 1)) - .append(SPECIAL_END_LINE).toString(); - } - indentCount = lineIndent(sb, indentCount, line); - sb.append(line).append(NEW_LINE); - if (!StringUtils.startsWithAny(line, RESERVED_LINES) && indentCount == 1 && i != 0) { - sb.append(NEW_LINE); - } - } - } - if (sb.length() == 0) { - return ""; - } - if (sb.charAt(sb.length() - 4) == NEW_LINE && sb.charAt(sb.length() - 3) == NEW_LINE) { - sb.deleteCharAt(sb.length() - 3); - } - removeRemainingWhitespace(sb); - sb.append(NEW_LINE); - - return sb.toString(); - } - - private static int mergeWithPrevious(final StringBuilder sb, final int indentCount) { - removeRemainingWhitespace(sb); - sb.append(SPACE); - sb.append(START_BODY); - sb.append(NEW_LINE); - int newIndentCount = indentCount; - return ++newIndentCount; - } - - private static void removeRemainingWhitespace(final StringBuilder sb) { - while (StringUtils.isWhitespace(String.valueOf(sb.charAt(sb.length() - 1)))) { - sb.deleteCharAt(sb.length() - 1); - } - } - - private static String cleanLine(final String split) { - final StringBuilder sb = new StringBuilder(); - final String[] s = WS_PATTERN.split(split); - for (int i = 0; i < s.length; i++) { - if (!StringUtils.isBlank(s[i])) { - sb.append(s[i]); - if (i != s.length - 1) { - sb.append(SPACE); - } - } - } - return sb.toString(); - } - - private static int lineIndent(final StringBuilder sb, final int indentCount, final String line) { - int newIndentCount = indentCount; - if (line.contains(END_BODY) && !line.contains(START_BODY)) { - newIndentCount--; - } - for (int i = 0; i < newIndentCount * INDENT; i++) { - sb.append(SPACE); - } - - if (line.contains(START_BODY) && !line.contains(END_BODY)) { - newIndentCount++; - } - - return newIndentCount; - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedType.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedType.java deleted file mode 100755 index b0e6b22568..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedType.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -import org.opendaylight.mdsal.binding.javav2.generator.util.AbstractBaseType; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.AnnotationTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; - -@Beta -abstract class AbstractGeneratedType extends AbstractBaseType implements GeneratedType { - - private final Type parent; - private final Type parentTypeForBuilder; - private final TypeComment comment; - private final List annotations; - private final List implementsTypes; - private final List enumerations; - private final List constants; - private final List methodSignatures; - private final List enclosedTypes; - private final List properties; - private final boolean isAbstract; - private final YangSourceDefinition definition; - private final BindingNamespaceType namespaceType; - - AbstractGeneratedType(final AbstractGeneratedTypeBuilder builder) { - super(builder.getPackageName(), builder.getName(), true, null); - this.parent = builder.getParent(); - this.parentTypeForBuilder = builder.getParentTypeForBuilder(); - this.comment = builder.getComment(); - this.annotations = toUnmodifiableAnnotations(builder.getAnnotations()); - this.implementsTypes = makeUnmodifiable(builder.getImplementsTypes()); - this.constants = makeUnmodifiable(builder.getConstants()); - this.enumerations = toUnmodifiableEnumerations(builder.getEnumerations()); - this.methodSignatures = toUnmodifiableMethods(builder.getMethodDefinitions()); - this.enclosedTypes = toUnmodifiableEnclosedTypes(builder.getEnclosedTypes(), - builder.getEnclosedTransferObjects()); - this.properties = toUnmodifiableProperties(builder.getProperties()); - this.isAbstract = builder.isAbstract(); - this.definition = builder.getYangSourceDefinition().orElse(null); - this.namespaceType = builder.getBindingNamespaceType(); - } - - protected static final List makeUnmodifiable(final List list) { - switch (list.size()) { - case 0: - return ImmutableList.of(); - case 1: - return Collections.singletonList(list.get(0)); - default: - return Collections.unmodifiableList(list); - } - } - - private static List toUnmodifiableEnclosedTypes( - final List enclosedGenTypeBuilders, - final List enclosedGenTOBuilders) { - final ArrayList enclosedTypesList = new ArrayList<>(enclosedGenTypeBuilders.size() - + enclosedGenTOBuilders.size()); - enclosedTypesList.addAll(enclosedGenTypeBuilders.stream().filter(Objects::nonNull) - .map(GeneratedTypeBuilder::toInstance).collect(Collectors.toList())); - - enclosedTypesList.addAll(enclosedGenTOBuilders.stream().filter(Objects::nonNull) - .map(GeneratedTOBuilder::toInstance).collect(Collectors.toList())); - - return makeUnmodifiable(enclosedTypesList); - } - - protected static final List toUnmodifiableAnnotations(final List - annotationBuilders) { - final List annotationList = new ArrayList<>(annotationBuilders.size()); - annotationList.addAll(annotationBuilders.stream().map(AnnotationTypeBuilder::toInstance).collect(Collectors - .toList())); - return makeUnmodifiable(annotationList); - } - - protected final List toUnmodifiableMethods(final List methodBuilders) { - final List methods = new ArrayList<>(methodBuilders.size()); - methods.addAll(methodBuilders.stream().map(methodBuilder -> methodBuilder.toInstance(this)) - .collect(Collectors.toList())); - return makeUnmodifiable(methods); - } - - protected final List toUnmodifiableEnumerations(final List enumBuilders) { - final List enums = new ArrayList<>(enumBuilders.size()); - enums.addAll(enumBuilders.stream().map(enumBuilder -> enumBuilder.toInstance(this)) - .collect(Collectors.toList())); - return makeUnmodifiable(enums); - } - - protected final List toUnmodifiableProperties(final List - methodBuilders) { - final List methods = new ArrayList<>(methodBuilders.size()); - methods.addAll(methodBuilders.stream().map(methodBuilder -> methodBuilder.toInstance(this)) - .collect(Collectors.toList())); - return makeUnmodifiable(methods); - } - - @Override - public Type getParentType() { - return this.parent; - } - - @Override - public Type getParentTypeForBuilder() { - return this.parentTypeForBuilder; - } - - @Override - public final TypeComment getComment() { - return this.comment; - } - - @Override - public List getAnnotations() { - return this.annotations; - } - - @Override - public boolean isAbstract() { - return this.isAbstract; - } - - @Override - public List getImplements() { - return this.implementsTypes; - } - - @Override - public List getEnclosedTypes() { - return this.enclosedTypes; - } - - @Override - public List getEnumerations() { - return this.enumerations; - } - - @Override - public List getConstantDefinitions() { - return this.constants; - } - - @Override - public List getMethodDefinitions() { - return this.methodSignatures; - } - - @Override - public List getProperties() { - return this.properties; - } - - @Override - public final Optional getYangSourceDefinition() { - return Optional.ofNullable(definition); - } - - @Override - public BindingNamespaceType getBindingNamespaceType() { - return this.namespaceType; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("GeneratedType [packageName="); - builder.append(getPackageName()); - builder.append(", name="); - builder.append(getName()); - if (this.parent != null) { - builder.append(", parent="); - builder.append(this.parent.getFullyQualifiedName()); - } else { - builder.append(", parent=null"); - } - - if (getComment() != null) { - builder.append(", comment="); - builder.append(getComment().getJavadoc()); - } - builder.append(", annotations="); - builder.append(this.annotations); - builder.append(", enclosedTypes="); - builder.append(this.enclosedTypes); - builder.append(", enumerations="); - builder.append(this.enumerations); - builder.append(", constants="); - builder.append(this.constants); - builder.append(", methodSignatures="); - builder.append(this.methodSignatures); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java deleted file mode 100755 index fd3da8fbac..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractGeneratedTypeBuilder.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.AbstractBaseType; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.AnnotationTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.util.LazyCollections; - -@Beta -abstract class AbstractGeneratedTypeBuilder> extends AbstractBaseType - implements GeneratedTypeBuilderBase { - - private List annotationBuilders = ImmutableList.of(); - private List implementsTypes = ImmutableList.of(); - private List enumDefinitions = ImmutableList.of(); - private List constants = ImmutableList.of(); - private List methodDefinitions = ImmutableList.of(); - private final List enclosedTypes = ImmutableList.of(); - private List enclosedTransferObjects = ImmutableList.of(); - private List properties = ImmutableList.of(); - private TypeComment comment; - private boolean isAbstract; - private Type parentTypeForBuilder; - private YangSourceDefinition yangSourceDefinition; - private BindingNamespaceType namespaceType; - - protected AbstractGeneratedTypeBuilder(final String packageName, final String name, ModuleContext context) { - super(packageName, name, context); - } - - protected AbstractGeneratedTypeBuilder(final String packageName, final String name, final boolean isNormalized, - ModuleContext context) { - super(packageName, name, true, null); - } - - protected AbstractGeneratedTypeBuilder(final String packageName, final String name, - final boolean isPkNameNormalized, final boolean isTypeNormalized, ModuleContext context) { - super(packageName, name, isPkNameNormalized, isTypeNormalized, context); - } - - protected TypeComment getComment() { - return this.comment; - } - - protected List getAnnotations() { - return annotationBuilders; - } - - @Override - public boolean isAbstract() { - return isAbstract; - } - - @Override - public List getImplementsTypes() { - return implementsTypes; - } - - protected List getEnumerations() { - return enumDefinitions; - } - - protected List getConstants() { - return constants; - } - - @Override - public List getMethodDefinitions() { - return methodDefinitions; - } - - protected List getEnclosedTypes() { - return enclosedTypes; - } - - protected List getEnclosedTransferObjects() { - return enclosedTransferObjects; - } - - protected abstract T thisInstance(); - - @Override - public GeneratedTOBuilder addEnclosingTransferObject(final String name) { - Preconditions.checkArgument(name != null, "Name for Enclosing Generated Transfer Object cannot be null!"); - GeneratedTOBuilder builder = new GeneratedTOBuilderImpl(getFullyQualifiedName(), name, true); - - Preconditions.checkArgument(!enclosedTransferObjects.contains(builder), - "This generated type already contains equal enclosing transfer object."); - enclosedTransferObjects = LazyCollections.lazyAdd(enclosedTransferObjects, builder); - return builder; - } - - @Override - public T addEnclosingTransferObject(final GeneratedTOBuilder genTOBuilder) { - Preconditions.checkArgument(genTOBuilder != null, "Parameter genTOBuilder cannot be null!"); - Preconditions.checkArgument(!enclosedTransferObjects.contains(genTOBuilder), - "This generated type already contains equal enclosing transfer object."); - enclosedTransferObjects = LazyCollections.lazyAdd(enclosedTransferObjects, genTOBuilder); - return thisInstance(); - } - - @Override - public T addComment(final TypeComment typeComment) { - this.comment = requireNonNull(typeComment); - return thisInstance(); - } - - @Override - public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) { - Preconditions.checkArgument(packageName != null, "Package Name for Annotation Type cannot be null!"); - Preconditions.checkArgument(name != null, "Name of Annotation Type cannot be null!"); - - final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, name); - - Preconditions.checkArgument(!annotationBuilders.contains(builder), - "This generated type already contains equal annotation."); - annotationBuilders = LazyCollections.lazyAdd(annotationBuilders, builder); - return builder; - } - - @Override - public T setAbstract(final boolean isabstract) { - this.isAbstract = isabstract; - return thisInstance(); - } - - @Override - public T addImplementsType(final Type genType) { - Preconditions.checkArgument(genType != null, "Type cannot be null"); - Preconditions.checkArgument(!implementsTypes.contains(genType), - "This generated type already contains equal implements type."); - implementsTypes = LazyCollections.lazyAdd(implementsTypes, genType); - return thisInstance(); - } - - @Override - public Constant addConstant(final Type type, final String name, final Object value) { - Preconditions.checkArgument(type != null, "Returning Type for Constant cannot be null!"); - Preconditions.checkArgument(name != null, "Name of constant cannot be null!"); - Preconditions.checkArgument(!containsConstant(name), - "This generated type already contains constant with the same name."); - - final Constant constant = new ConstantImpl(this, type, name, value); - constants = LazyCollections.lazyAdd(constants, constant); - return constant; - } - - - @Override - public Type setParentTypeForBuilder(Type type) { - return this.parentTypeForBuilder = type; - } - - @Override - public BindingNamespaceType getBindingNamespaceType() { - return namespaceType; - } - - @Override - public void setBindingNamespaceType(BindingNamespaceType type) { - this.namespaceType = type; - } - - public boolean containsConstant(final String name) { - Preconditions.checkArgument(name != null, "Parameter name can't be null"); - for (Constant constant : constants) { - if (name.equals(constant.getName())) { - return true; - } - } - return false; - } - - @Override - public EnumBuilder addEnumeration(final String name, ModuleContext context) { - Preconditions.checkArgument(name != null, "Name of enumeration cannot be null!"); - final EnumBuilder builder = new EnumerationBuilderImpl(getFullyQualifiedName(), name, true, false, - context); - - Preconditions.checkArgument(!enumDefinitions.contains(builder), - "This generated type already contains equal enumeration."); - enumDefinitions = LazyCollections.lazyAdd(enumDefinitions, builder); - return builder; - } - - @Override - public MethodSignatureBuilder addMethod(final String name) { - Preconditions.checkArgument(name != null, "Name of method cannot be null!"); - final MethodSignatureBuilder builder = new MethodSignatureBuilderImpl(name); - builder.setAccessModifier(AccessModifier.PUBLIC); - builder.setAbstract(true); - methodDefinitions = LazyCollections.lazyAdd(methodDefinitions, builder); - return builder; - } - - @Override - public boolean containsMethod(final String name) { - Preconditions.checkArgument(name != null, "Parameter name can't be null"); - for (MethodSignatureBuilder methodDefinition : methodDefinitions) { - if (name.equals(methodDefinition.getName())) { - return true; - } - } - return false; - } - - @Override - public GeneratedPropertyBuilder addProperty(final String name) { - Preconditions.checkArgument(name != null, "Parameter name can't be null"); - Preconditions.checkArgument(!containsProperty(name), - "This generated type already contains property with the same name."); - - final GeneratedPropertyBuilder builder = new GeneratedPropertyBuilderImpl(name); - builder.setAccessModifier(AccessModifier.PUBLIC); - properties = LazyCollections.lazyAdd(properties, builder); - return builder; - } - - @Override - public boolean containsProperty(final String name) { - Preconditions.checkArgument(name != null, "Parameter name can't be null"); - for (GeneratedPropertyBuilder property : properties) { - if (name.equals(property.getName())) { - return true; - } - } - return false; - } - - @Override - public Optional getYangSourceDefinition() { - return Optional.ofNullable(yangSourceDefinition); - } - - - @Override - public void setYangSourceDefinition(final YangSourceDefinition definition) { - yangSourceDefinition = requireNonNull(definition); - } - - @Override - public int hashCode() { - return Objects.hash(getName(), getPackageName()); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - if (!(obj instanceof AbstractGeneratedTypeBuilder)) { - return false; - } - - AbstractGeneratedTypeBuilder other = (AbstractGeneratedTypeBuilder) obj; - return Objects.equals(getFullyQualifiedName(), other.getFullyQualifiedName()); - } - - public Type getParent() { - return null; - } - - @Override - public Type getParentTypeForBuilder() { - return parentTypeForBuilder; - } - - @Override - public List getProperties() { - return properties; - } - -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMember.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMember.java deleted file mode 100644 index 4a71d3d821..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMember.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeMember; - -@Beta -abstract class AbstractTypeMember implements TypeMember { - - private final String name; - private final String comment; - private final Type definingType; - private final Type returnType; - private final List annotations; - private final boolean isFinal; - private final boolean isStatic; - private final AccessModifier accessModifier; - - protected AbstractTypeMember(final Type definingType, final String name, final List annotations, - final String comment, final AccessModifier accessModifier, final Type returnType, - final boolean isFinal, final boolean isStatic) { - - this.definingType = definingType; - this.name = name; - this.annotations = annotations; - this.comment = comment; - this.accessModifier = accessModifier; - this.returnType = returnType; - this.isFinal = isFinal; - this.isStatic = isStatic; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getComment() { - return comment; - } - - @Override - public Type getDefiningType() { - return definingType; - } - - @Override - public AccessModifier getAccessModifier() { - return accessModifier; - } - - @Override - public Type getReturnType() { - return returnType; - } - - @Override - public boolean isFinal() { - return isFinal; - } - - @Override - public boolean isStatic() { - return isStatic; - } - - @Override - public int hashCode() { - return Objects.hash(name, returnType); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - if (!(obj instanceof AbstractTypeMember)) { - return false; - } - - AbstractTypeMember other = (AbstractTypeMember) obj; - return Objects.equals(getName(), other.getName()) && Objects.equals(getReturnType(), other.getReturnType()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("MethodSignatureImpl [name="); - builder.append(getName()); - builder.append(", comment="); - builder.append(getComment()); - if (getDefiningType() != null) { - builder.append(", definingType="); - builder.append(getDefiningType().getPackageName()); - builder.append("."); - builder.append(getDefiningType().getName()); - } else { - builder.append(", definingType= null"); - } - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", annotations="); - builder.append(getAnnotations()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java deleted file mode 100644 index 24dd66f49f..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AbstractTypeMemberBuilder.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.AnnotationTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.TypeMemberBuilder; -import org.opendaylight.yangtools.util.LazyCollections; - -@Beta -abstract class AbstractTypeMemberBuilder> implements TypeMemberBuilder { - - private final String name; - private String comment = ""; - private boolean isFinal; - private boolean isStatic; - private Type returnType; - private AccessModifier accessModifier; - private List annotationBuilders = ImmutableList.of(); - - AbstractTypeMemberBuilder(final String name) { - this.name = name; - } - - @Override - public AnnotationTypeBuilder addAnnotation(final String packageName, final String typeName) { - Preconditions.checkArgument(packageName != null, "Annotation Type cannot have package name null!"); - Preconditions.checkArgument(typeName != null, "Annotation Type cannot have name as null!"); - - final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, typeName); - annotationBuilders = LazyCollections.lazyAdd(annotationBuilders, builder); - return builder; - } - - protected abstract T thisInstance(); - - protected Iterable getAnnotationBuilders() { - return annotationBuilders; - } - - @Override - public AccessModifier getAccessModifier() { - return accessModifier; - } - - @Override - public String getName() { - return name; - } - - protected String getComment() { - return comment; - } - - protected boolean isFinal() { - return isFinal; - } - - protected boolean isStatic() { - return isStatic; - } - - public Type getReturnType() { - return returnType; - } - - @Override - public T setReturnType(final Type retType) { - Preconditions.checkArgument(retType != null, "Return Type of member cannot be null!"); - this.returnType = retType; - return thisInstance(); - } - - @Override - public T setAccessModifier(final AccessModifier modifier) { - Preconditions.checkArgument(modifier != null, "Access Modifier for member type cannot be null!"); - this.accessModifier = modifier; - return thisInstance(); - } - - @Override - public T setComment(final String commentText) { - if (commentText == null) { - this.comment = ""; - } - this.comment = commentText; - return thisInstance(); - } - - @Override - public T setFinal(final boolean finalOrNot) { - this.isFinal = finalOrNot; - return thisInstance(); - } - - @Override - public T setStatic(final boolean staticOrNot) { - this.isStatic = staticOrNot; - return thisInstance(); - } - - protected List toAnnotationTypes() { - final List annotations = new ArrayList<>(); - for (final AnnotationTypeBuilder annotBuilder : getAnnotationBuilders()) { - if (annotBuilder != null) { - annotations.add(annotBuilder.toInstance()); - } - } - - return ImmutableList.copyOf(annotations); - } - - @Override - public int hashCode() { - return Objects.hash(getName(), getReturnType()); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - - if (!(obj instanceof AbstractTypeMemberBuilder)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - AbstractTypeMemberBuilder other = (AbstractTypeMemberBuilder) obj; - return Objects.equals(getName(), other.getName()) && Objects.equals(getReturnType(), other.getReturnType()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedPropertyImpl [name="); - builder.append(getName()); - builder.append(", annotations="); - builder.append(getAnnotationBuilders()); - builder.append(", comment="); - builder.append(getComment()); - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", isFinal="); - builder.append(isFinal()); - builder.append(", modifier="); - builder.append(getAccessModifier()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AnnotationTypeBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AnnotationTypeBuilderImpl.java deleted file mode 100644 index 526437f6c4..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/AnnotationTypeBuilderImpl.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Ordering; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.generator.util.AbstractBaseType; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.AnnotationTypeBuilder; -import org.opendaylight.yangtools.util.LazyCollections; - -@Beta -final class AnnotationTypeBuilderImpl extends AbstractBaseType implements AnnotationTypeBuilder { - - private final String packageName; - private final String name; - private List annotationBuilders = ImmutableList.of(); - private List parameters = ImmutableList.of(); - - AnnotationTypeBuilderImpl(final String packageName, final String name) { - super(packageName, name, true, null); - this.packageName = packageName; - this.name = name; - } - - @Override - public AnnotationTypeBuilder addAnnotation(final String pkgName, final String typeName) { - if (pkgName != null && typeName != null) { - final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(pkgName, typeName); - if (!annotationBuilders.contains(builder)) { - annotationBuilders = LazyCollections.lazyAdd(annotationBuilders, builder); - return builder; - } - } - return null; - } - - private boolean addParameter(final ParameterImpl param) { - if (!parameters.contains(param)) { - parameters = LazyCollections.lazyAdd(parameters, param); - return true; - } else { - return false; - } - } - - @Override - public boolean addParameter(final String paramName, final String value) { - if (paramName != null && value != null) { - final ParameterImpl param = new ParameterImpl(paramName, value); - return addParameter(param); - } - return false; - } - - @Override - public boolean addParameters(final String paramName, final List values) { - if (paramName != null && values != null) { - final ParameterImpl param = new ParameterImpl(paramName, values); - return addParameter(param); - } - return false; - } - - @Override - public AnnotationType toInstance() { - return new AnnotationTypeImpl(packageName, name, annotationBuilders, parameters); - } - - @Override - public int hashCode() { - return Objects.hash(name, packageName); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!(obj instanceof AnnotationTypeBuilderImpl)) { - return false; - } - - AnnotationTypeBuilderImpl other = (AnnotationTypeBuilderImpl) obj; - return Objects.equals(name, other.name) && Objects.equals(packageName, other.packageName); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AnnotationTypeBuilder [packageName="); - builder.append(packageName); - builder.append(", name="); - builder.append(name); - builder.append(", annotationBuilders="); - builder.append(annotationBuilders); - builder.append(", parameters="); - builder.append(parameters); - builder.append("]"); - return builder.toString(); - } - - private static final class AnnotationTypeImpl implements AnnotationType { - - private final String packageName; - private final String name; - private final List annotations; - private final List parameters; - private final List paramNames; - - AnnotationTypeImpl(final String packageName, final String name, - final List annotationBuilders, - final List parameters) { - this.packageName = packageName; - this.name = name; - - final List a = new ArrayList<>(); - for (final AnnotationTypeBuilder builder : annotationBuilders) { - a.add(builder.toInstance()); - } - this.annotations = ImmutableList.copyOf(a); - - final List p = new ArrayList<>(); - for (final AnnotationType.Parameter parameter : parameters) { - p.add(parameter.getName()); - } - this.paramNames = ImmutableList.copyOf(p); - - this.parameters = parameters.isEmpty() ? ImmutableList.of() - : Collections.unmodifiableList(parameters); - } - - @Override - public String getPackageName() { - return packageName; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getFullyQualifiedName() { - return packageName + "." + name; - } - - @Override - public List getAnnotations() { - return annotations; - } - - @Override - public Parameter getParameter(final String paramName) { - if (paramName != null) { - for (final AnnotationType.Parameter parameter : parameters) { - if (parameter.getName().equals(paramName)) { - return parameter; - } - } - } - return null; - } - - @Override - public List getParameters() { - return parameters; - } - - @Override - public List getParameterNames() { - return paramNames; - } - - @Override - public boolean containsParameters() { - return !parameters.isEmpty(); - } - - @Override - public int hashCode() { - return Objects.hash(name, packageName); - } - - @Override - public int compareTo(AnnotationType other) { - return ComparisonChain.start() - .compare(this.name, other.getName()) - .compare(this.packageName, other.getPackageName()) - //FIXME: what is natural ordering for AnnotationType? - .compare(this.annotations, other.getAnnotations(), - Ordering.natural().lexicographical()) - .compare(this.paramNames, other.getParameterNames(), Ordering.natural().lexicographical()) - .result(); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!(obj instanceof AnnotationTypeImpl)) { - return false; - } - - AnnotationTypeImpl other = (AnnotationTypeImpl) obj; - return Objects.equals(name, other.name) && Objects.equals(packageName, other.packageName); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AnnotationType [packageName="); - builder.append(packageName); - builder.append(", name="); - builder.append(name); - builder.append(", annotations="); - builder.append(annotations); - builder.append(", parameters="); - builder.append(parameters); - builder.append("]"); - return builder.toString(); - } - } - - private static final class ParameterImpl implements AnnotationType.Parameter { - - private final String name; - private final String value; - private final List values; - - ParameterImpl(final String name, final String value) { - this.name = name; - this.value = value; - this.values = ImmutableList.of(); - } - - ParameterImpl(final String name, final List values) { - this.name = name; - this.values = values; - this.value = null; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getSingleValue() { - return value; - } - - @Override - public List getValues() { - return values; - } - - @Override - public int hashCode() { - return Objects.hash(name); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!(obj instanceof ParameterImpl)) { - return false; - } - ParameterImpl other = (ParameterImpl) obj; - return Objects.equals(name, other.name); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ParameterImpl [name="); - builder.append(name); - builder.append(", value="); - builder.append(value); - builder.append(", values="); - builder.append(values); - builder.append("]"); - return builder.toString(); - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/ConstantImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/ConstantImpl.java deleted file mode 100644 index c1658b30c4..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/ConstantImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -final class ConstantImpl implements Constant { - - private final Type definingType; - private final Type type; - private final String name; - private final Object value; - - ConstantImpl(final Type definingType, final Type type, final String name, final Object value) { - this.definingType = definingType; - this.type = type; - this.name = name; - this.value = value; - } - - @Override - public Type getDefiningType() { - return definingType; - } - - @Override - public Type getType() { - return type; - } - - @Override - public String getName() { - return name; - } - - @Override - public Object getValue() { - return value; - } - - @Override - public String toFormattedString() { - return type + " " + name + " " + value; - } - - @Override - public int hashCode() { - return Objects.hash(name, type); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - if (!(obj instanceof ConstantImpl)) { - return false; - } - - ConstantImpl other = (ConstantImpl) obj; - return Objects.equals(name, other.name) && Objects.equals(type, other.type) - && Objects.equals(value, other.value); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Constant [type="); - builder.append(type); - builder.append(", name="); - builder.append(name); - builder.append(", value="); - builder.append(value); - if (definingType != null) { - builder.append(", definingType="); - builder.append(definingType.getPackageName()); - builder.append("."); - builder.append(definingType.getName()); - } else { - builder.append(", definingType= null"); - } - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImpl.java deleted file mode 100755 index 90c31dc5d2..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImpl.java +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; - -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.AbstractBaseType; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration.Pair; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.AnnotationTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.util.LazyCollections; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.Status; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; - -@Beta -public class EnumerationBuilderImpl extends AbstractBaseType implements EnumBuilder { - - private List values = ImmutableList.of(); - private List annotationBuilders = ImmutableList.of(); - private String description; - private String reference; - private String moduleName; - private List schemaPath; - - public EnumerationBuilderImpl(final String packageName, final String name, final ModuleContext context) { - super(packageName, name, context); - } - - public EnumerationBuilderImpl(final String packageName, final String name, final boolean isPkNameNormalized, - final boolean isTypeNormalized, final ModuleContext context) { - super(packageName, name, isPkNameNormalized, isTypeNormalized, context); - } - - public void setReference(final String reference) { - this.reference = reference; - } - - public void setModuleName(final String moduleName) { - this.moduleName = moduleName; - } - - public void setSchemaPath(final List schemaPath) { - this.schemaPath = schemaPath; - } - - @Override - public void setDescription(final String description) { - this.description = description; - } - - @Override - public AnnotationTypeBuilder addAnnotation(final String packageName, final String name) { - final AnnotationTypeBuilder builder = new AnnotationTypeBuilderImpl(packageName, name); - if (!this.annotationBuilders.contains(builder)) { - this.annotationBuilders = LazyCollections.lazyAdd(this.annotationBuilders, builder); - } - return builder; - } - - @Override - public void addValue(final String name, final int value, final String desc, final String ref, - final Status status) { - final EnumPairImpl p = new EnumPairImpl(name, value, desc, ref, status, this.values); - this.values = LazyCollections.lazyAdd(this.values, p); - } - - @Override - public Enumeration toInstance(final Type definingType) { - return new EnumerationImpl(definingType, this.annotationBuilders, this.packageName, this.name, this.values, - this.description, this.reference, this.moduleName, this.schemaPath); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("EnumerationBuilderImpl [packageName="); - builder.append(this.packageName); - builder.append(", name="); - builder.append(this.name); - builder.append(", values="); - builder.append(this.values); - builder.append(']'); - return builder.toString(); - } - - @Override - public void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef) { - enumTypeDef.getValues().stream().filter(Objects::nonNull).forEach(enumPair -> this.addValue(enumPair.getName(), - enumPair.getValue(), enumPair.getDescription().orElse(null), enumPair.getReference().orElse(null), - enumPair.getStatus())); - } - - private static final class EnumPairImpl implements Enumeration.Pair { - - private final String name; - private final String mappedName; - private final int value; - private final String description; - private final String reference; - private final Status status; - - EnumPairImpl(final String name, final int value, final String description, - final String reference, final Status status, final List values) { - - this.name = name; - this.mappedName = JavaIdentifierNormalizer.normalizeEnumValueIdentifier(name, values); - this.value = value; - this.description = description; - this.reference = reference; - this.status = status; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getMappedName() { - return this.mappedName; - } - - @Override - public int getValue() { - return this.value; - } - - @Nullable - @Override - public Optional getDescription() { - return Optional.ofNullable(this.description); - } - - @Nullable - @Override - public Optional getReference() { - return Optional.ofNullable(this.reference); - } - - @Nonnull - @Override - public Status getStatus() { - return this.status; - } - - @Override - public int hashCode() { - return Objects.hash(this.name, this.value); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - if (!(obj instanceof EnumPairImpl)) { - return false; - } - - final EnumPairImpl other = (EnumPairImpl) obj; - - return Objects.equals(this.name, other.name) && Objects.equals(this.value, other.value); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("EnumPair [name="); - builder.append(this.name); - builder.append(", mappedName="); - builder.append(getMappedName()); - builder.append(", value="); - builder.append(this.value); - builder.append(']'); - return builder.toString(); - } - } - - private static final class EnumerationImpl extends AbstractBaseType implements Enumeration { - - private final Type definingType; - private final String description; - private final String reference; - private final String moduleName; - private final List schemaPath; - private final List values; - private final List annotations; - - EnumerationImpl(final Type definingType, final List annotationBuilders, - final String packageName, final String name, final List values, final String - description, - final String reference, final String moduleName, final List schemaPath) { - super(packageName, name, true, null); - this.definingType = definingType; - this.values = values; - this.description = description; - this.reference = reference; - this.moduleName = moduleName; - this.schemaPath = schemaPath; - - final List a = annotationBuilders.stream().map(AnnotationTypeBuilder::toInstance) - .collect(Collectors.toList()); - this.annotations = ImmutableList.copyOf(a); - } - - @Override - public List getAnnotations() { - return this.annotations; - } - - @Override - public Type getParentType() { - return this.definingType; - } - - @Override - public Optional getDescription() { - return Optional.ofNullable(this.description); - } - - @Override - public List getValues() { - return this.values; - } - - @Override - public String toFormattedString() { - final StringBuilder builder = new StringBuilder(); - builder.append("public enum"); - builder.append(' '); - builder.append(getName()); - builder.append(" {"); - builder.append("\n"); - - int count = 0; - for (final Enumeration.Pair valPair : this.values) { - builder.append("\t"); - builder.append(' '); - builder.append(valPair.getMappedName()); - builder.append(" ("); - builder.append(valPair.getValue()); - - if (count == this.values.size() - 1) { - builder.append(" );"); - } else { - builder.append(" ),"); - } - ++count; - } - builder.append("\n}"); - return builder.toString(); - } - - @Override - public Optional getReference() { - return Optional.ofNullable(this.reference); - } - - @Override - public List getSchemaPath() { - return this.schemaPath; - } - - @Override - public String getModuleName() { - return this.moduleName; - } - - @Override - public TypeComment getComment() { - //noop - return null; - } - - @Override - public boolean isAbstract() { - return false; - } - - @Override - public List getImplements() { - return ImmutableList.of(); - } - - @Override - public List getEnclosedTypes() { - return ImmutableList.of(); - } - - @Override - public List getEnumerations() { - return ImmutableList.of(); - } - - @Override - public List getConstantDefinitions() { - return ImmutableList.of(); - } - - @Override - public List getMethodDefinitions() { - return ImmutableList.of(); - } - - @Override - public List getProperties() { - return ImmutableList.of(); - } - - @Override - public Type getParentTypeForBuilder() { - return null; - } - - @Override - public Optional getYangSourceDefinition() { - // TODO Auto-generated method stub - return Optional.empty(); - } - - @Override - public BindingNamespaceType getBindingNamespaceType() { - return BindingNamespaceType.Data; - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java deleted file mode 100644 index d3b7769c10..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyBuilderImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; - -@Beta -public final class GeneratedPropertyBuilderImpl extends AbstractTypeMemberBuilder implements - GeneratedPropertyBuilder { - - private String value; - private boolean isReadOnly; - - public GeneratedPropertyBuilderImpl(String name) { - super(name); - this.isReadOnly = true; - } - - @Override - public GeneratedPropertyBuilder setValue(String valueString) { - this.value = valueString; - return this; - } - - @Override - public GeneratedPropertyBuilder setReadOnly(boolean readOnlyOrNot) { - this.isReadOnly = readOnlyOrNot; - return this; - } - - @Override - protected GeneratedPropertyBuilderImpl thisInstance() { - return this; - } - - @Override - public GeneratedProperty toInstance(Type definingType) { - final List annotations = toAnnotationTypes(); - return new GeneratedPropertyImpl(definingType, getName(), annotations, getComment(), getAccessModifier(), - getReturnType(), isFinal(), isStatic(), isReadOnly, value); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedPropertyImpl [name="); - builder.append(getName()); - builder.append(", annotations="); - builder.append(getAnnotationBuilders()); - builder.append(", comment="); - builder.append(getComment()); - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", isFinal="); - builder.append(isFinal()); - builder.append(", isReadOnly="); - builder.append(isReadOnly); - builder.append(", modifier="); - builder.append(getAccessModifier()); - builder.append("]"); - return builder.toString(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyImpl.java deleted file mode 100644 index b7a8195c5f..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedPropertyImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -@Beta -final class GeneratedPropertyImpl extends AbstractTypeMember implements GeneratedProperty { - - private String value; - private boolean isReadOnly; - - GeneratedPropertyImpl(Type definingType, String name, List annotations, String comment, - AccessModifier accessModifier, Type returnType, boolean isFinal, boolean isStatic, - boolean isReadOnly, String value) { - super(definingType, name, annotations, comment, accessModifier, returnType, isFinal, isStatic); - this.value = value; - this.isReadOnly = isReadOnly; - } - - @Override - public String getValue() { - return value; - } - - @Override - public boolean isReadOnly() { - return isReadOnly; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedPropertyImpl [name="); - builder.append(getName()); - builder.append(", annotations="); - builder.append(getAnnotations()); - builder.append(", comment="); - builder.append(getComment()); - if (getDefiningType() != null) { - builder.append(", parent="); - builder.append(getDefiningType().getPackageName()); - builder.append("."); - builder.append(getDefiningType().getName()); - } else { - builder.append(", parent=null"); - } - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", isFinal="); - builder.append(isFinal()); - builder.append(", isReadOnly="); - builder.append(isReadOnly); - builder.append(", modifier="); - builder.append(getAccessModifier()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java deleted file mode 100644 index db0e54ccf6..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTOBuilderImpl.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - -import java.util.List; -import java.util.Optional; - -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.yangtools.util.LazyCollections; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.TypeDefinition; - -@Beta -public final class GeneratedTOBuilderImpl extends AbstractGeneratedTypeBuilder implements - GeneratedTOBuilder { - - private GeneratedTransferObject extendsType; - private List equalsProperties = ImmutableList.of(); - private List hashProperties = ImmutableList.of(); - private List toStringProperties = ImmutableList.of(); - private boolean isTypedef = false; - private boolean isUnionType = false; - private boolean isUnionTypeBuilder = false; - private TypeDefinition baseType = null; - private Restrictions restrictions; - private GeneratedPropertyBuilder suid; - private String reference; - private String description; - private String moduleName; - private List schemaPath; - - public GeneratedTOBuilderImpl(final String packageName, final String name, ModuleContext context) { - super(packageName, name, context); - setAbstract(false); - } - - public GeneratedTOBuilderImpl(final String packageName, final String name, final boolean isNormalized) { - super(packageName, name, true, null); - } - - public GeneratedTOBuilderImpl(final String packageName, final String name, final boolean isPkNameNormalized, - final boolean isTypeNormalized, ModuleContext context) { - super(packageName, name, isPkNameNormalized, isTypeNormalized, context); - setAbstract(false); - } - - @Override - public GeneratedTOBuilder setExtendsType(GeneratedTransferObject genTransObj) { - Preconditions.checkArgument(genTransObj != null, "Generated Transfer Object cannot be null!"); - extendsType = genTransObj; - return this; - } - - /** - * Add new MethodSignature definition for GeneratedTypeBuilder and - * returns MethodSignatureBuilder for specifying all Method parameters.
- * Name of Method cannot be null, if it is null - * the method SHOULD throw {@link IllegalArgumentException}
- * By Default the MethodSignatureBuilder SHOULD be pre-set as - * {@link MethodSignatureBuilder#setAbstract(boolean)}, - * {TypeMemberBuilder#setFinal(boolean)} and - * {TypeMemberBuilder#setAccessModifier(boolean)} - * - * @param name Name of Method - * @return new instance of Method Signature Builder. - */ - @Override - public MethodSignatureBuilder addMethod(final String name) { - final MethodSignatureBuilder builder = super.addMethod(name); - builder.setAbstract(false); - return builder; - } - - @Override - public GeneratedTOBuilder addEqualsIdentity(GeneratedPropertyBuilder property) { - equalsProperties = LazyCollections.lazyAdd(equalsProperties, property); - return this; - } - - @Override - public GeneratedTOBuilder addHashIdentity(GeneratedPropertyBuilder property) { - hashProperties = LazyCollections.lazyAdd(hashProperties, property); - return this; - } - - @Override - public GeneratedTOBuilder addToStringProperty(GeneratedPropertyBuilder property) { - toStringProperties = LazyCollections.lazyAdd(toStringProperties, property); - return this; - } - - @Override - public void setRestrictions(Restrictions restrictions) { - this.restrictions = restrictions; - } - - @Override - public GeneratedTransferObject toInstance() { - return new GeneratedTransferObjectImpl(this); - } - - @Override - public void setTypedef(boolean typedefOrNot) { - this.isTypedef = typedefOrNot; - } - - @Override - public void setBaseType(TypeDefinition typeDef) { - this.baseType = typeDef; - } - - @Override - public void setIsUnion(boolean isUnion) { - this.isUnionType = isUnion; - } - - @Override - public void setIsUnionBuilder(boolean unionTypeBuilderOrNot) { - this.isUnionTypeBuilder = unionTypeBuilderOrNot; - } - - @Override - public void setSUID(GeneratedPropertyBuilder suidBuilder) { - this.suid = suidBuilder; - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - @Override - public void setSchemaPath(List schemaPath) { - this.schemaPath = schemaPath; - } - - @Override - public void setReference(String reference) { - this.reference = reference; - } - - @Override - protected GeneratedTOBuilderImpl thisInstance() { - return this; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedTransferObject [packageName="); - builder.append(getPackageName()); - builder.append(", name="); - builder.append(getName()); - builder.append(", comment="); - builder.append(getComment()); - builder.append(", constants="); - builder.append(getConstants()); - builder.append(", enumerations="); - builder.append(getEnumerations()); - builder.append(", equalsProperties="); - builder.append(equalsProperties); - builder.append(", hashCodeProperties="); - builder.append(hashProperties); - builder.append(", stringProperties="); - builder.append(toStringProperties); - builder.append(", annotations="); - builder.append(getAnnotations()); - builder.append(", methods="); - builder.append(getMethodDefinitions()); - builder.append("]"); - return builder.toString(); - } - - private static final class GeneratedTransferObjectImpl extends AbstractGeneratedType implements - GeneratedTransferObject { - - private final List equalsProperties; - private final List hashCodeProperties; - private final List stringProperties; - private final GeneratedTransferObject extendsType; - private final boolean isTypedef; - private final TypeDefinition baseType; - private final boolean isUnionType; - private final boolean isUnionTypeBuilder; - private final Restrictions restrictions; - private final GeneratedProperty innerSuid; - private final String reference; - private final String description; - private final String moduleName; - private final List schemaPath; - - GeneratedTransferObjectImpl(final GeneratedTOBuilderImpl builder) { - super(builder); - - this.extendsType = builder.extendsType; - this.equalsProperties = toUnmodifiableProperties(builder.equalsProperties); - this.hashCodeProperties = toUnmodifiableProperties(builder.hashProperties); - this.stringProperties = toUnmodifiableProperties(builder.toStringProperties); - - this.isTypedef = builder.isTypedef; - this.baseType = builder.baseType; - this.isUnionType = builder.isUnionType; - this.isUnionTypeBuilder = builder.isUnionTypeBuilder; - this.restrictions = builder.restrictions; - this.reference = builder.reference; - this.description = builder.description; - this.moduleName = builder.moduleName; - this.schemaPath = builder.schemaPath; - - if (builder.suid == null) { - this.innerSuid = null; - } else { - this.innerSuid = builder.suid.toInstance(GeneratedTransferObjectImpl.this); - } - } - - @Override - public GeneratedProperty getSUID() { - return innerSuid; - } - - @Override - public GeneratedTransferObject getSuperType() { - return extendsType; - } - - @Override - public List getEqualsIdentifiers() { - return equalsProperties; - } - - @Override - public List getHashCodeIdentifiers() { - return hashCodeProperties; - } - - @Override - public List getToStringIdentifiers() { - return stringProperties; - } - - @Override - public boolean isTypedef() { - return isTypedef; - } - - @Override - public TypeDefinition getBaseType() { - return baseType; - } - - @Override - public boolean isUnionType() { - return isUnionType; - } - - @Override - public boolean isUnionTypeBuilder() { - return isUnionTypeBuilder; - } - - @Override - public Restrictions getRestrictions() { - return restrictions; - } - - @Override - public Optional getDescription() { - return Optional.ofNullable(this.description); - } - - @Override - public Optional getReference() { - return Optional.ofNullable(this.reference); - } - - @Override - public List getSchemaPath() { - return schemaPath; - } - - @Override - public String getModuleName() { - return moduleName; - } - - @Override - public String toString() { - if (isTypedef) { - return serializeTypedef(this); - } - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedTransferObject [packageName="); - builder.append(getPackageName()); - builder.append(", name="); - builder.append(getName()); - builder.append(", annotations="); - builder.append(getAnnotations()); - final TypeComment comment = getComment(); - if (comment != null) { - builder.append(", comment="); - builder.append(comment.getJavadoc()); - } - builder.append(", extends="); - builder.append(getSuperType()); - builder.append(", implements="); - builder.append(getImplements()); - builder.append(", enclosedTypes="); - builder.append(getEnclosedTypes()); - builder.append(", constants="); - builder.append(getConstantDefinitions()); - builder.append(", enumerations="); - builder.append(getEnumerations()); - builder.append(", properties="); - builder.append(getProperties()); - builder.append(", equalsProperties="); - builder.append(equalsProperties); - builder.append(", hashCodeProperties="); - builder.append(hashCodeProperties); - builder.append(", stringProperties="); - builder.append(stringProperties); - builder.append(", methods="); - builder.append(getMethodDefinitions()); - builder.append("]"); - return builder.toString(); - } - - private String serializeTypedef(final Type type) { - if (type instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) type; - StringBuilder sb = new StringBuilder(); - sb.append(parameterizedType.getRawType().getFullyQualifiedName()); - sb.append('<'); - boolean first = true; - for (Type parameter : parameterizedType.getActualTypeArguments()) { - if (first) { - first = false; - } else { - sb.append(','); - } - sb.append(serializeTypedef(parameter)); - } - sb.append('>'); - return sb.toString(); - } else { - return type.getFullyQualifiedName(); - } - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java deleted file mode 100755 index e18bf9a7c4..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/GeneratedTypeBuilderImpl.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.util.List; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; - -@Beta -public final class GeneratedTypeBuilderImpl extends AbstractGeneratedTypeBuilder implements - GeneratedTypeBuilder { - - private String description; - private String reference; - private String moduleName; - private List schemaPath; - private boolean isWithBuilder = false; - private String basePackageName = null; - - public GeneratedTypeBuilderImpl(final String packageName, final String name, ModuleContext context) { - super(packageName, name, context); - setAbstract(true); - } - - public GeneratedTypeBuilderImpl(final String packageName, final String name, final boolean isPkNameNormalized, - final boolean isTypeNormalized, ModuleContext context) { - super(packageName, name, isPkNameNormalized, isTypeNormalized, context); - setAbstract(true); - } - - @Override - public GeneratedType toInstance() { - if (this.isWithBuilder()) { - return new GeneratedTypeWithBuilderImpl(this); - } else { - return new GeneratedTypeImpl(this); - } - } - - @Override - public void setDescription(String description) { - this.description = description; - } - - @Override - public void setModuleName(String moduleName) { - this.moduleName = moduleName; - } - - @Override - public void setSchemaPath(List schemaPath) { - this.schemaPath = schemaPath; - } - - @Override - public void setReference(String reference) { - this.reference = reference; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("GeneratedTransferObject [packageName="); - builder.append(getPackageName()); - builder.append(", name="); - builder.append(getName()); - final TypeComment comment = getComment(); - if (comment != null) { - builder.append(", comment="); - builder.append(comment.getJavadoc()); - } - builder.append(", annotations="); - builder.append(getAnnotations()); - builder.append(", implements="); - builder.append(getImplementsTypes()); - builder.append(", enclosedTypes="); - builder.append(getEnclosedTypes()); - builder.append(", constants="); - builder.append(getConstants()); - builder.append(", enumerations="); - builder.append(getEnumerations()); - builder.append(", properties="); - builder.append(", methods="); - builder.append(getMethodDefinitions()); - builder.append("]"); - return builder.toString(); - } - - @Override - protected GeneratedTypeBuilderImpl thisInstance() { - return this; - } - - public boolean isWithBuilder() { - return isWithBuilder; - } - - public void setWithBuilder(boolean withBuilder) { - isWithBuilder = withBuilder; - } - - public String getBasePackageName() { - return basePackageName; - } - - public void setBasePackageName(String basePackageName) { - this.basePackageName = basePackageName; - } - - private static class GeneratedTypeImpl extends AbstractGeneratedType { - - private final String description; - private final String reference; - private final String moduleName; - private final List schemaPath; - - GeneratedTypeImpl(final GeneratedTypeBuilderImpl builder) { - super(builder); - - this.description = builder.description; - this.reference = builder.reference; - this.moduleName = builder.moduleName; - this.schemaPath = builder.schemaPath; - } - - @Override - public Optional getDescription() { - return Optional.ofNullable(this.description); - } - - @Override - public Optional getReference() { - return Optional.ofNullable(this.reference); - } - - @Override - public List getSchemaPath() { - return schemaPath; - } - - @Override - public String getModuleName() { - return moduleName; - } - } - - private static final class GeneratedTypeWithBuilderImpl extends GeneratedTypeImpl - implements GeneratedTypeForBuilder { - - private final String basePackageName; - private final String builderPackageName; - - GeneratedTypeWithBuilderImpl(GeneratedTypeBuilderImpl builder) { - super(builder); - Preconditions.checkState(builder.getBasePackageName() != null, - "Base package name can not be null for type with builder!"); - this.basePackageName = builder.getBasePackageName(); - this.builderPackageName = generatePackageNameForBuilder(); - } - - private String generatePackageNameForBuilder() { - return BindingGeneratorUtil.replacePackageTopNamespace(this.basePackageName, this.getPackageName(), - BindingNamespaceType.Data, BindingNamespaceType.Builder); - } - - @Override - public String getPackageNameForBuilder() { - return this.builderPackageName; - } - - @Override - public String getBasePackageName() { - return this.basePackageName; - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodParameterImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodParameterImpl.java deleted file mode 100644 index e9aea315d7..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodParameterImpl.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature.Parameter; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -@Beta -final class MethodParameterImpl implements Parameter { - - private final String name; - private final Type type; - - MethodParameterImpl(final String name, final Type type) { - this.name = name; - this.type = type; - } - - @Override - public String getName() { - return name; - } - - @Override - public Type getType() { - return type; - } - - @Override - public int hashCode() { - return Objects.hash(name, type); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - if (!(obj instanceof MethodParameterImpl)) { - return false; - } - MethodParameterImpl other = (MethodParameterImpl) obj; - return Objects.equals(name, other.name) && Objects.equals(type, other.type); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("MethodParameter [name="); - builder.append(name); - builder.append(", type="); - builder.append(type.getPackageName()); - builder.append("."); - builder.append(type.getName()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureBuilderImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureBuilderImpl.java deleted file mode 100644 index 33acc4d927..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureBuilderImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableList; - -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder; -import org.opendaylight.yangtools.util.LazyCollections; - -@Beta -final class MethodSignatureBuilderImpl extends AbstractTypeMemberBuilder implements - MethodSignatureBuilder { - - private List parameters = ImmutableList.of(); - private List unmodifiableParams = ImmutableList.of(); - private boolean isAbstract; - - MethodSignatureBuilderImpl(final String name) { - super(name); - } - - @Override - public MethodSignatureBuilder setAbstract(final boolean abstractOrNot) { - this.isAbstract = abstractOrNot; - return this; - } - - @Override - public MethodSignatureBuilder addParameter(final Type type, final String name) { - parameters = LazyCollections.lazyAdd(parameters, new MethodParameterImpl(name, type)); - unmodifiableParams = Collections.unmodifiableList(parameters); - return this; - } - - @Override - protected MethodSignatureBuilder thisInstance() { - return this; - } - - @Override - public MethodSignature toInstance(final Type definingType) { - final List annotations = toAnnotationTypes(); - return new MethodSignatureImpl(definingType, getName(), annotations, getComment(), getAccessModifier(), - getReturnType(), unmodifiableParams, isFinal(), isAbstract, isStatic()); - } - - @Override - public int hashCode() { - return Objects.hash(getName(), parameters, getReturnType()); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MethodSignatureBuilderImpl other = (MethodSignatureBuilderImpl) obj; - if (!Objects.equals(getName(), other.getName())) { - return false; - } - if (!Objects.equals(parameters, other.parameters)) { - return false; - } - if (!Objects.equals(getReturnType(), other.getReturnType())) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("MethodSignatureBuilderImpl [name="); - builder.append(getName()); - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", parameters="); - builder.append(parameters); - builder.append(", annotationBuilders="); - builder.append(getAnnotationBuilders()); - builder.append(", comment="); - builder.append(getComment()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureImpl.java b/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureImpl.java deleted file mode 100644 index fd27b98530..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/main/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/MethodSignatureImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import com.google.common.annotations.Beta; -import java.util.List; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -@Beta -class MethodSignatureImpl extends AbstractTypeMember implements MethodSignature { - - private final List params; - private final boolean isAbstract; - - MethodSignatureImpl(final Type definingType, final String name, - final List annotations, - final String comment, final AccessModifier accessModifier, - final Type returnType, final List params, final boolean isFinal, - final boolean isAbstract, final boolean isStatic) { - super(definingType, name, annotations, comment, accessModifier, returnType, isFinal, isStatic); - this.params = params; - this.isAbstract = isAbstract; - } - - @Override - public boolean isAbstract() { - return isAbstract; - } - - @Override - public List getParameters() { - return params; - } - - @Override - public int hashCode() { - return Objects.hash(getName(), params, getReturnType()); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MethodSignatureImpl other = (MethodSignatureImpl) obj; - if (!Objects.equals(getName(), other.getName())) { - return false; - } - if (!Objects.equals(params, other.params)) { - return false; - } - if (!Objects.equals(getReturnType(), other.getReturnType())) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("MethodSignatureImpl [name="); - builder.append(getName()); - builder.append(", comment="); - builder.append(getComment()); - if (getDefiningType() != null) { - builder.append(", definingType="); - builder.append(getDefiningType().getPackageName()); - builder.append("."); - builder.append(getDefiningType().getName()); - } else { - builder.append(", definingType= null"); - } - builder.append(", returnType="); - builder.append(getReturnType()); - builder.append(", params="); - builder.append(params); - builder.append(", annotations="); - builder.append(getAnnotations()); - builder.append("]"); - return builder.toString(); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizerTest.java b/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizerTest.java deleted file mode 100644 index 78888460ed..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/JavaIdentifierNormalizerTest.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; - -public class JavaIdentifierNormalizerTest { - - @Test - public void specialPathsTest() { - ModuleContext context = new ModuleContext(); - // QName - reserved & non reserved - String normalizeIdentifier = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.opendaylight.yangtools.yang.common", - "QName", context); - assertEquals("QName", normalizeIdentifier); - // again reserved - normalizeIdentifier = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.opendaylight.yangtools.yang.common", - "QName", context); - assertEquals("QName", normalizeIdentifier); - // non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("qname.non.reserved", "QName", context); - assertEquals("Qname", normalizeIdentifier); - // again non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("qname.non.reserved", "QName", context); - assertEquals("Qname1", normalizeIdentifier); - - // Augmentable - reserved & non reserved - normalizeIdentifier = JavaIdentifierNormalizer - .normalizeClassIdentifier("org.opendaylight.mdsal.binding.javav2.spec.structural", "Augmentable", - context); - assertEquals("Augmentable", normalizeIdentifier); - // again reserved - normalizeIdentifier = JavaIdentifierNormalizer - .normalizeClassIdentifier("org.opendaylight.mdsal.binding.javav2.spec.structural", "Augmentable", - context); - assertEquals("Augmentable", normalizeIdentifier); - // non reserved - normalizeIdentifier = JavaIdentifierNormalizer - .normalizeClassIdentifier("augmentable.non.reserved", "Augmentable", context); - assertEquals("Augmentable", normalizeIdentifier); - // again non reserved - normalizeIdentifier = - JavaIdentifierNormalizer.normalizeClassIdentifier("augmentable.non.reserved", "Augmentable", context); - assertEquals("Augmentable1", normalizeIdentifier); - - // List - reserved & non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("java.util", "List", context); - assertEquals("List", normalizeIdentifier); - // again reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("java.util", "List", context); - assertEquals("List", normalizeIdentifier); - // non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("list.non.reserved", "List", context); - assertEquals("List", normalizeIdentifier); - // again non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("list.non.reserved", "List", context); - assertEquals("List1", normalizeIdentifier); - - // String - reserved & non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("java.lang", "String", context); - assertEquals("String", normalizeIdentifier); - // again reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("java.lang", "String", context); - assertEquals("String", normalizeIdentifier); - // non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("string.non.reserved", "String", - context); - assertEquals("String", normalizeIdentifier); - // again non reserved - normalizeIdentifier = JavaIdentifierNormalizer.normalizeClassIdentifier("string.non.reserved", "String", - context); - assertEquals("String1", normalizeIdentifier); - } - - /** - * This test tests normalizing of enum and interface identifiers too. - */ - @Test - public void sameClassNamesSamePackageTest() { - ModuleContext context = new ModuleContext(); - String normalizeIdentifier1 = JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.same.package", - "Foo", context); - String normalizeIdentifier2 = JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.same.package", - "fOo", context); - final String normalizeIdentifier3 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.same.package", "foo", context); - assertEquals(normalizeIdentifier1, "Foo"); - assertEquals(normalizeIdentifier2, "Foo1"); - assertEquals(normalizeIdentifier3, "Foo2"); - - normalizeIdentifier1 = JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.same.package", "*", - context); - normalizeIdentifier2 = JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.same.package", - "asterisk", context); - assertEquals(normalizeIdentifier1, "Asterisk"); - assertEquals(normalizeIdentifier2, "Asterisk1"); - } - - /** - * This test tests normalizing of enum and interface identifiers too. - */ - @Test - public void sameClassNamesOtherPackageTest() { - ModuleContext context = new ModuleContext(); - String normalizeIdentifier1 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.other.package", "Foo", context); - String normalizeIdentifier2 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.other.package.next", "fOo", context); - final String normalizeIdentifier3 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.other.package.next.next", "foo", - context); - assertEquals(normalizeIdentifier1, "Foo"); - assertEquals(normalizeIdentifier2, "Foo"); - assertEquals(normalizeIdentifier3, "Foo"); - - normalizeIdentifier1 = JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.other.package", "*", - context); - normalizeIdentifier2 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.other.package.next", "asterisk", - context); - assertEquals(normalizeIdentifier1, "Asterisk"); - assertEquals(normalizeIdentifier2, "Asterisk"); - } - - /** - * This test tests normalizing of enum and interface identifiers too. - */ - @Test - public void sameClassNamesSamePackageReservedWordsTest() { - ModuleContext context = new ModuleContext(); - final String normalizeIdentifier1 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.same.package", "int", context); - final String normalizeIdentifier2 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.same.package", "InT", context); - final String normalizeIdentifier3 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.same.package", "inT", context); - assertEquals(normalizeIdentifier1, "IntReservedKeyword"); - assertEquals(normalizeIdentifier2, "IntReservedKeyword1"); - assertEquals(normalizeIdentifier3, "IntReservedKeyword2"); - } - - /** - * This test tests normalizing of enum and interface identifiers too. - */ - @Test - public void sameClassNamesOtherPackageReservedWordsTest() { - ModuleContext context = new ModuleContext(); - final String normalizeIdentifier1 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.other.package", "int", context); - final String normalizeIdentifier2 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.other.package.next", "InT", - context); - final String normalizeIdentifier3 = - JavaIdentifierNormalizer.normalizeClassIdentifier("org.example.keywords.other.package.next.next", - "inT", context); - assertEquals(normalizeIdentifier1, "IntReservedKeyword"); - assertEquals(normalizeIdentifier2, "IntReservedKeyword"); - assertEquals(normalizeIdentifier3, "IntReservedKeyword"); - } - - /** - * This test tests converting of reserved keywords like class and interface identifiers too. - */ - @Test - public void identifierReservedKeyWordsEnumConverterTest() throws Exception { - for (final String reservedKeyword : BindingMapping.JAVA_RESERVED_WORDS) { - testIdentifierReservedKeywordEnum(reservedKeyword); - } - for (final String reservedKeyword : BindingMapping.WINDOWS_RESERVED_WORDS) { - testIdentifierReservedKeywordEnum(reservedKeyword); - } - testIdentifierReservedKeywordEnum("iNt"); - testIdentifierReservedKeywordEnum("cOn"); - } - - private void testIdentifierReservedKeywordEnum(final String reservedKeyword) { - final StringBuilder expected = - new StringBuilder(reservedKeyword.substring(0, 1).toUpperCase()) - .append(reservedKeyword.substring(1).toLowerCase()) - .append("ReservedKeyword"); - assertTest(reservedKeyword, expected.toString(), JavaIdentifier.ENUM); - } - - /** - * This test tests converting of reserved keywords like constant identifier too. - */ - @Test - public void identifierReservedKeyWordsEnumValueConverterTest() throws Exception { - for (final String reservedKeyword : BindingMapping.JAVA_RESERVED_WORDS) { - testIdentifierReservedKeywordEnumValue(reservedKeyword); - } - for (final String reservedKeyword : BindingMapping.WINDOWS_RESERVED_WORDS) { - testIdentifierReservedKeywordEnumValue(reservedKeyword); - } - testIdentifierReservedKeywordEnumValue("iNt"); - testIdentifierReservedKeywordEnumValue("cOn"); - } - - private void testIdentifierReservedKeywordEnumValue(final String reservedKeyword) { - final StringBuilder expected = new StringBuilder(reservedKeyword.toUpperCase()).append("_RESERVED_KEYWORD"); - assertTest(reservedKeyword, expected.toString(), JavaIdentifier.ENUM_VALUE); - } - - /** - * This test tests converting of reserved keywords like variable identifier too. - */ - @Test - public void identifierReservedKeyWordsMethodConverterTest() throws Exception { - for (final String reservedKeyword : BindingMapping.JAVA_RESERVED_WORDS) { - testIdentifierReservedKeywordMethod(reservedKeyword); - } - for (final String reservedKeyword : BindingMapping.WINDOWS_RESERVED_WORDS) { - testIdentifierReservedKeywordMethod(reservedKeyword); - } - testIdentifierReservedKeywordMethod("iNt"); - testIdentifierReservedKeywordMethod("cOn"); - } - - private void testIdentifierReservedKeywordMethod(final String reservedKeyword) { - final StringBuilder expected = new StringBuilder(reservedKeyword.toLowerCase()).append("ReservedKeyword"); - assertTest(reservedKeyword, expected.toString(), JavaIdentifier.METHOD); - } - - @Test - public void acceptableCharsEnumTest() throws Exception { - assertTest("Acceptable", "Acceptable", JavaIdentifier.ENUM); - } - - /** - * This test tests converting of class and interface identifiers too. - */ - @Test - public void nonAcceptableCharsEnumTest() throws Exception { - assertTest("acceptable", "Acceptable", JavaIdentifier.ENUM); - assertTest("acc*", "AccAsterisk", JavaIdentifier.ENUM); - assertTest("Acc*", "AccAsterisk", JavaIdentifier.ENUM); - assertTest("Acc*acc", "AccAsteriskAcc", JavaIdentifier.ENUM); - assertTest("*acc", "AsteriskAcc", JavaIdentifier.ENUM); - assertTest("*Acc", "AsteriskAcc", JavaIdentifier.ENUM); - assertTest("*", "Asterisk", JavaIdentifier.ENUM); - assertTest("\\acc", "ReverseSolidusAcc", JavaIdentifier.ENUM); - assertTest("\\Acc", "ReverseSolidusAcc", JavaIdentifier.ENUM); - assertTest("\\", "ReverseSolidus", JavaIdentifier.ENUM); - assertTest("/acc", "SolidusAcc", JavaIdentifier.ENUM); - assertTest("/Acc", "SolidusAcc", JavaIdentifier.ENUM); - assertTest("/", "Solidus", JavaIdentifier.ENUM); - assertTest("1acc", "DigitOneAcc", JavaIdentifier.ENUM); - assertTest("1Acc", "DigitOneAcc", JavaIdentifier.ENUM); - assertTest("acc1", "Acc1", JavaIdentifier.ENUM); - assertTest("Acc1", "Acc1", JavaIdentifier.ENUM); - assertTest("1", "DigitOne", JavaIdentifier.ENUM); - assertTest("%", "PercentSign", JavaIdentifier.ENUM); - assertTest("foo-bar", "FooBar", JavaIdentifier.ENUM); - assertTest("foo--bar", "FooHyphenMinusHyphenMinusBar", JavaIdentifier.ENUM); - assertTest("-foo", "HyphenMinusFoo", JavaIdentifier.ENUM); - assertTest("--foo", "HyphenMinusHyphenMinusFoo", JavaIdentifier.ENUM); - assertTest("foo-", "FooHyphenMinus", JavaIdentifier.ENUM); - assertTest("foo--", "FooHyphenMinusHyphenMinus", JavaIdentifier.ENUM); - assertTest("-foo-", "HyphenMinusFooHyphenMinus", JavaIdentifier.ENUM); - assertTest("-foo-bar-", "HyphenMinusFooBarHyphenMinus", JavaIdentifier.ENUM); - assertTest("-foo--bar-", "HyphenMinusFooHyphenMinusHyphenMinusBarHyphenMinus", JavaIdentifier.ENUM); - assertTest("foo.", "FooFullStop", JavaIdentifier.ENUM); - assertTest(".foo", "FullStopFoo", JavaIdentifier.ENUM); - assertTest("bar.foo", "BarFullStopFoo", JavaIdentifier.ENUM); - } - - @Test - public void acceptableCharsEnumValueTest() throws Exception { - assertTest("ACCEPTABLE", "ACCEPTABLE", JavaIdentifier.ENUM_VALUE); - } - - /** - * This test tests converting of constant identifier too. - */ - @Test - public void nonAcceptableCharsEnumValueTest() throws Exception { - assertTest("acceptable", "ACCEPTABLE", JavaIdentifier.ENUM_VALUE); - assertTest("Acceptable", "ACCEPTABLE", JavaIdentifier.ENUM_VALUE); - assertTest("Acce_ptable", "ACCE_PTABLE", JavaIdentifier.ENUM_VALUE); - assertTest("acc*", "ACC_ASTERISK", JavaIdentifier.ENUM_VALUE); - assertTest("Acc*", "ACC_ASTERISK", JavaIdentifier.ENUM_VALUE); - assertTest("*acc", "ASTERISK_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("*Acc", "ASTERISK_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("*", "ASTERISK", JavaIdentifier.ENUM_VALUE); - assertTest("\\acc", "REVERSE_SOLIDUS_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("\\Acc", "REVERSE_SOLIDUS_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("\\", "REVERSE_SOLIDUS", JavaIdentifier.ENUM_VALUE); - assertTest("/acc", "SOLIDUS_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("/Acc", "SOLIDUS_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("/", "SOLIDUS", JavaIdentifier.ENUM_VALUE); - assertTest("1acc", "DIGIT_ONE_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("1Acc", "DIGIT_ONE_ACC", JavaIdentifier.ENUM_VALUE); - assertTest("acc1", "ACC1", JavaIdentifier.ENUM_VALUE); - assertTest("Acc1", "ACC1", JavaIdentifier.ENUM_VALUE); - assertTest("1", "DIGIT_ONE", JavaIdentifier.ENUM_VALUE); - assertTest("%", "PERCENT_SIGN", JavaIdentifier.ENUM_VALUE); - assertTest("foo-bar", "FOO_BAR", JavaIdentifier.ENUM_VALUE); - assertTest("foo--bar", "FOO_HYPHEN_MINUS_HYPHEN_MINUS_BAR", JavaIdentifier.ENUM_VALUE); - assertTest("-foo", "HYPHEN_MINUS_FOO", JavaIdentifier.ENUM_VALUE); - assertTest("--foo", "HYPHEN_MINUS_HYPHEN_MINUS_FOO", JavaIdentifier.ENUM_VALUE); - assertTest("foo-", "FOO_HYPHEN_MINUS", JavaIdentifier.ENUM_VALUE); - assertTest("foo--", "FOO_HYPHEN_MINUS_HYPHEN_MINUS", JavaIdentifier.ENUM_VALUE); - assertTest("-foo-", "HYPHEN_MINUS_FOO_HYPHEN_MINUS", JavaIdentifier.ENUM_VALUE); - assertTest("-foo-bar-", "HYPHEN_MINUS_FOO_BAR_HYPHEN_MINUS", JavaIdentifier.ENUM_VALUE); - assertTest("-foo--bar-", "HYPHEN_MINUS_FOO_HYPHEN_MINUS_HYPHEN_MINUS_BAR_HYPHEN_MINUS", - JavaIdentifier.ENUM_VALUE); - assertTest("foo.", "FOO_FULL_STOP", JavaIdentifier.ENUM_VALUE); - assertTest(".foo", "FULL_STOP_FOO", JavaIdentifier.ENUM_VALUE); - assertTest("bar.foo", "BAR_FULL_STOP_FOO", JavaIdentifier.ENUM_VALUE); - } - - @Test - public void acceptableCharsMethodTest() throws Exception { - assertTest("acceptable", "acceptable", JavaIdentifier.METHOD); - } - - /** - * This test tests converting of variable identifier too. - */ - @Test - public void nonAcceptableCharsMethodTest() throws Exception { - assertTest("acc*", "accAsterisk", JavaIdentifier.METHOD); - assertTest("Acc*", "accAsterisk", JavaIdentifier.METHOD); - assertTest("*acc", "asteriskAcc", JavaIdentifier.METHOD); - assertTest("*Acc", "asteriskAcc", JavaIdentifier.METHOD); - assertTest("*", "asterisk", JavaIdentifier.METHOD); - assertTest("\\acc", "reverseSolidusAcc", JavaIdentifier.METHOD); - assertTest("\\Acc", "reverseSolidusAcc", JavaIdentifier.METHOD); - assertTest("\\", "reverseSolidus", JavaIdentifier.METHOD); - assertTest("/acc", "solidusAcc", JavaIdentifier.METHOD); - assertTest("/Acc", "solidusAcc", JavaIdentifier.METHOD); - assertTest("/", "solidus", JavaIdentifier.METHOD); - assertTest("1acc", "digitOneAcc", JavaIdentifier.METHOD); - assertTest("1Acc", "digitOneAcc", JavaIdentifier.METHOD); - assertTest("acc1", "acc1", JavaIdentifier.METHOD); - assertTest("Acc1", "acc1", JavaIdentifier.METHOD); - assertTest("1", "digitOne", JavaIdentifier.METHOD); - assertTest("%", "percentSign", JavaIdentifier.METHOD); - assertTest("foo-bar", "fooBar", JavaIdentifier.METHOD); - assertTest("foo--bar", "fooHyphenMinusHyphenMinusBar", JavaIdentifier.METHOD); - assertTest("-foo", "hyphenMinusFoo", JavaIdentifier.METHOD); - assertTest("--foo", "hyphenMinusHyphenMinusFoo", JavaIdentifier.METHOD); - assertTest("foo-", "fooHyphenMinus", JavaIdentifier.METHOD); - assertTest("foo--", "fooHyphenMinusHyphenMinus", JavaIdentifier.METHOD); - assertTest("-foo-", "hyphenMinusFooHyphenMinus", JavaIdentifier.METHOD); - assertTest("-foo-bar-", "hyphenMinusFooBarHyphenMinus", JavaIdentifier.METHOD); - assertTest("-foo--bar-", "hyphenMinusFooHyphenMinusHyphenMinusBarHyphenMinus", JavaIdentifier.METHOD); - assertTest("foo.", "fooFullStop", JavaIdentifier.METHOD); - assertTest(".foo", "fullStopFoo", JavaIdentifier.METHOD); - assertTest("foo.bar", "fooFullStopBar", JavaIdentifier.METHOD); - } - - - @Test - public void packageReservedKeyWordsTest() { - for (final String reservedKeyword : BindingMapping.JAVA_RESERVED_WORDS) { - testPackageReservedKeyword(reservedKeyword); - } - for (final String reservedKeyword : BindingMapping.WINDOWS_RESERVED_WORDS) { - testPackageReservedKeyword(reservedKeyword); - } - } - - private void testPackageReservedKeyword(final String reservedKeyword) { - final String packageNameNormalizer = JavaIdentifierNormalizer.normalizePartialPackageName(reservedKeyword); - final StringBuilder expected = new StringBuilder(reservedKeyword).append('_'); - assertEquals(expected.toString().toLowerCase(), packageNameNormalizer); - } - - @Test - public void digitAtStartTest() { - for (int i = 0; i < 10; i++) { - final String str_i = String.valueOf(i); - final String packageNameNormalizer = JavaIdentifierNormalizer.normalizePartialPackageName(str_i); - final String expected = Character.getName(str_i.charAt(0)).replaceAll(" ", "").toLowerCase(); - assertEquals(expected, packageNameNormalizer); - } - } - - @Test - public void normalizePackageNameDashTest() { - dashTest("foo-bar", "foo_bar"); - dashTest("foo--bar", "foo__bar"); - dashTest("-foo", "_foo"); - dashTest("--foo", "__foo"); - dashTest("foo-", "foo_"); - dashTest("foo--", "foo__"); - dashTest("-foo-bar", "_foo_bar"); - dashTest("foo-bar-", "foo_bar_"); - dashTest("-foo-bar-", "_foo_bar_"); - dashTest("-foo--bar-", "_foo__bar_"); - } - - private void dashTest(final String tested, final String expected) { - final String actual = JavaIdentifierNormalizer.normalizePartialPackageName(tested); - assertEquals(expected, actual); - } - - @Test - public void normalizePackageNameTest() { - normalizePackageNameTest("*foo", "asteriskfoo"); - normalizePackageNameTest("/foo", "solidusfoo"); - normalizePackageNameTest("\\foo", "reversesolidusfoo"); - normalizePackageNameTest(":foo", "colonfoo"); - - normalizePackageNameTest("f*oo", "fasteriskoo"); - normalizePackageNameTest("f/oo", "fsolidusoo"); - normalizePackageNameTest("f\\oo", "freversesolidusoo"); - normalizePackageNameTest("f:oo", "fcolonoo"); - - normalizePackageNameTest("foo*", "fooasterisk"); - normalizePackageNameTest("foo/", "foosolidus"); - normalizePackageNameTest("foo\\", "fooreversesolidus"); - normalizePackageNameTest("foo:", "foocolon"); - - normalizePackageNameTest("_foo_", "_foo_"); - normalizePackageNameTest("f_oo", "f_oo"); - } - - private void normalizePackageNameTest(final String tested, final Object expected) { - final String packageNameNormalizer = JavaIdentifierNormalizer.normalizePartialPackageName(tested); - assertEquals(expected, packageNameNormalizer); - } - - private void assertTest(final String testedIdentifier, final String acceptable, - final JavaIdentifier javaTypeOfIdentifier) { - final String convertedIdentifier = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(testedIdentifier, javaTypeOfIdentifier); - assertNotNull(convertedIdentifier); - assertTrue(!convertedIdentifier.isEmpty()); - assertEquals(acceptable, convertedIdentifier); - } - - @Test - public void realPackageNameExampleTest() { - String tested = "org.opendaylight.example.test.rev000000.data.foo"; - String expected = "org.opendaylight.example.test.rev000000.data.foo"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo*"; - expected = "org.opendaylight.example.test.rev000000.data.fooasterisk"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo*bar"; - expected = "org.opendaylight.example.test.rev000000.data.fooasteriskbar"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo.bar"; - expected = "org.opendaylight.example.test.rev000000.data.foo.bar"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo-bar"; - expected = "org.opendaylight.example.test.rev000000.data.foo_bar"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo_"; - expected = "org.opendaylight.example.test.rev000000.data.foo_"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data._foo"; - expected = "org.opendaylight.example.test.rev000000.data._foo"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.foo*.*"; - expected = "org.opendaylight.example.test.rev000000.data.fooasterisk.asterisk"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.int"; - expected = "org.opendaylight.example.test.rev000000.data.int_"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.iNt"; - expected = "org.opendaylight.example.test.rev000000.data.int_"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.con"; - expected = "org.opendaylight.example.test.rev000000.data.con_"; - testRealPackageNameExample(tested, expected); - - tested = "org.opendaylight.example.test.rev000000.data.CON"; - expected = "org.opendaylight.example.test.rev000000.data.con_"; - testRealPackageNameExample(tested, expected); - } - - private void testRealPackageNameExample(final String tested, final String expected) { - final String actual = JavaIdentifierNormalizer.normalizeFullPackageName(tested); - assertEquals(expected, actual); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleanerTest.java b/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleanerTest.java deleted file mode 100644 index fa48a3301e..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/YangSnippetCleanerTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import org.junit.Assert; -import org.junit.Test; - -public class YangSnippetCleanerTest { - - @Test - public void cleanerTest() throws Exception { - final String badWs = readFile(this.getClass().getResourceAsStream("/yangs/break_ws/bad-ws.yang")); - final String fixedBadWs = readFile(this.getClass().getResourceAsStream("/yangs/break_ws/fixed-bad-ws.yang")); - final String cleanBadWs = YangSnippetCleaner.clean(badWs); - Assert.assertEquals(fixedBadWs, cleanBadWs); - } - - private String readFile(final InputStream inputStream) throws IOException { - final BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); - try { - final StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - if (!line.contains("//")) { - sb.append(line); - } - sb.append("\n"); - line = br.readLine(); - } - return sb.toString(); - } finally { - br.close(); - } - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImplTest.java b/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImplTest.java deleted file mode 100644 index 5788a3899e..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/test/java/org/opendaylight/mdsal/binding/javav2/generator/util/generated/type/builder/EnumerationBuilderImplTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.yangtools.yang.model.api.Status; - -public class EnumerationBuilderImplTest { - - @Test - public void sameEnumTest() { - ModuleContext context = new ModuleContext(); - EnumerationBuilderImpl enumerationBuilderImpl = new EnumerationBuilderImpl("package.same.test", "test", - context); - Enumeration enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - String formattedString = enumeration.toFormattedString(); - - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("Test")); - - enumerationBuilderImpl = new EnumerationBuilderImpl("package.same.test", "Test", context); - enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - formattedString = enumeration.toFormattedString(); - - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("Test1")); - } - - @Test - public void enumTest() { - final EnumerationBuilderImpl enumerationBuilderImpl = - new EnumerationBuilderImpl("package.test", "test**", new ModuleContext()); - enumerationBuilderImpl.addValue("value", 1, "des", "ref", Status.CURRENT); - final Enumeration enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - final String formattedString = enumeration.toFormattedString(); - - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("public enum TestAsteriskAsterisk {")); - assertTrue(formattedString.contains("VALUE")); - } - - @Test - public void enumUniqueTest() { - final EnumerationBuilderImpl enumerationBuilderImpl = - new EnumerationBuilderImpl("package.ex.ex.ex.test", "test", new ModuleContext()); - enumerationBuilderImpl.addValue("foo", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("Foo", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("foo1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("Foo1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("FOO1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("FOO", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("foO1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("foO2", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("foO2", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("Foo*", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("foo*", 1, "des", "ref", Status.CURRENT); - - enumerationBuilderImpl.addValue("f__11", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("f__1_1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("f__1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("F__1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("f_1_1", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("F_1_1", 1, "des", "ref", Status.CURRENT); - - enumerationBuilderImpl.addValue("fo", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("Fo", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("fO", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("FO", 1, "des", "ref", Status.CURRENT); - - final Enumeration enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - final String formattedString = enumeration.toFormattedString(); - - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("FOO")); - assertTrue(formattedString.contains("FOO_1")); - assertTrue(formattedString.contains("FOO1")); - assertTrue(formattedString.contains("FOO1_1")); - assertTrue(formattedString.contains("FOO1_2")); - assertTrue(formattedString.contains("FOO_2")); - assertTrue(formattedString.contains("FOO1_3")); - assertTrue(formattedString.contains("FOO2")); - assertTrue(formattedString.contains("FOO2_1")); - assertTrue(formattedString.contains("FOO_ASTERISK")); - assertTrue(formattedString.contains("FOO_ASTERISK_1")); - - assertTrue(formattedString.contains("F_11")); - assertTrue(formattedString.contains("F_1_1")); - assertTrue(formattedString.contains("F_1")); - assertTrue(formattedString.contains("F_1_2")); - assertTrue(formattedString.contains("F_1_1_1")); - assertTrue(formattedString.contains("F_1_1_2")); - - assertTrue(formattedString.contains("FO")); - assertTrue(formattedString.contains("FO_1")); - assertTrue(formattedString.contains("FO_2")); - assertTrue(formattedString.contains("FO_3")); - } - - @Test - public void asteriskInEnumTest() { - final EnumerationBuilderImpl enumerationBuilderImpl = - new EnumerationBuilderImpl("package.ex.test", "test**", new ModuleContext()); - enumerationBuilderImpl.addValue("val**ue", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("val*ue", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("*value*", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("*", 1, "des", "ref", Status.CURRENT); - final Enumeration enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - final String formattedString = enumeration.toFormattedString(); - - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("public enum TestAsteriskAsterisk {")); - assertTrue(formattedString.contains("VAL_ASTERISK_ASTERISK_UE")); - assertTrue(formattedString.contains("VAL_ASTERISK_UE")); - assertTrue(formattedString.contains("ASTERISK_VALUE_ASTERISK")); - assertTrue(formattedString.contains("ASTERISK")); - } - - @Test - public void reverseSolidusInEnumTest() { - final EnumerationBuilderImpl enumerationBuilderImpl = - new EnumerationBuilderImpl("package.ex.ex.test", "test\\\\", new ModuleContext()); - enumerationBuilderImpl.addValue("val\\\\ue", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("val\\ue", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("\\value\\", 1, "des", "ref", Status.CURRENT); - enumerationBuilderImpl.addValue("\\", 1, "des", "ref", Status.CURRENT); - final Enumeration enumeration = enumerationBuilderImpl.toInstance(enumerationBuilderImpl); - final String formattedString = enumeration.toFormattedString(); - assertNotNull(formattedString); - assertTrue(!formattedString.isEmpty()); - assertTrue(formattedString.contains("public enum TestReverseSolidusReverseSolidus {")); - assertTrue(formattedString.contains("VAL_REVERSE_SOLIDUS_REVERSE_SOLIDUS_UE")); - assertTrue(formattedString.contains("VAL_REVERSE_SOLIDUS_UE")); - assertTrue(formattedString.contains("REVERSE_SOLIDUS_VALUE_REVERSE_SOLIDUS")); - assertTrue(formattedString.contains("REVERSE_SOLIDUS")); - } -} diff --git a/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/bad-ws.yang b/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/bad-ws.yang deleted file mode 100644 index d840826631..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/bad-ws.yang +++ /dev/null @@ -1,48 +0,0 @@ -module test { -//excess whitespaces for testing of YangSnippetCleaner - - - - yang-version 1; - - - - - - - namespace "urn:test:simple:test"; - prefix test; - - - - - - organization "test.org"; - revision "2017-03-10"; - - - - container my-cont { - - - -} - - - container my-cont2 { - - - - leaf my-leaf { - type string; - - } - - - leaf my-leaf2 - { - type string; - - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/fixed-bad-ws.yang b/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/fixed-bad-ws.yang deleted file mode 100644 index 473d695ee8..0000000000 --- a/binding2/mdsal-binding2-generator-util/src/test/resources/yangs/break_ws/fixed-bad-ws.yang +++ /dev/null @@ -1,21 +0,0 @@ -module test { - yang-version 1; - namespace "urn:test:simple:test"; - prefix test; - - organization "test.org"; - - revision "2017-03-10"; - - container my-cont { - } - - container my-cont2 { - leaf my-leaf { - type string; - } - leaf my-leaf2 { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/pom.xml b/binding2/mdsal-binding2-java-api-generator/pom.xml deleted file mode 100644 index bfafa8e05d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-java-api-generator - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - test - - - org.opendaylight.mdsal - mdsal-binding2-generator-util - - - org.opendaylight.mdsal - mdsal-binding2-util - - - org.opendaylight.yangtools - yang-model-export - - - org.opendaylight.yangtools - yang-test-util - - - com.typesafe.play - twirl-api_2.12 - 1.3.15 - - - org.apache.commons - commons-text - - - com.google.guava - guava - - - org.sonatype.plexus - plexus-build-api - - - org.codehaus.plexus - plexus-container-default - 1.6 - provided - - - - org.codehaus.plexus - plexus-utils - - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.groupId}.${project.artifactId} - - !org.sonatype.plexus.build.incremental, - * - - - - - - - - com.jakewharton.twirl - twirl-maven-plugin - 1.1.0 - - - twirl-to-scala-first - generate-sources - - compile - - - - - - - - org.scala-lang - scala-compiler - 2.11.12 - - - org.scala-lang - scala-library - 2.11.12 - - - - - - - net.alchim31.maven - scala-maven-plugin - 3.3.2 - - - scala-compile-second - process-resources - - add-source - compile - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - - - - - javadoc-java11-disable - - [11,) - - - true - - - - diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/BuilderGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/BuilderGenerator.java deleted file mode 100644 index c053732e72..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/BuilderGenerator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.BuilderRenderer; - -import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.UnitName; -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * Transformer of the data from the virtual form to JAVA programming language. - * The result source code represent java class. For generation of the source - * code is used the template written in Twirl (Scala based) language. - */ -@Beta -public final class BuilderGenerator implements CodeGenerator { - - /** - * Constant used as suffix for builder name. - */ - public static final String BUILDER = "Builder"; - - @Override - public String generate(Type type) { - if (type instanceof GeneratedTypeForBuilder) { - final GeneratedType genType = (GeneratedType) type; - return new BuilderRenderer(genType).generateTemplate(); - } else { - return ""; - } - } - - @Override - public boolean isAcceptable(Type type) { - return type instanceof GeneratedTypeForBuilder; - } - - @Override - public Identifier getUnitName(Type type) { - return new UnitName(type.getName() + BUILDER); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/EnumGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/EnumGenerator.java deleted file mode 100644 index 87b2604278..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/EnumGenerator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.EnumRenderer; -import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.UnitName; -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * Transformer of the data from the virtual form to JAVA source code. The - * result source code represents JAVA enumeration. For generation of the source - * code is used the template written in Twirl (Scala based) language. - */ -@Beta -public class EnumGenerator implements CodeGenerator { - - @Override - public String generate(Type type) { - if (type instanceof Enumeration) { - final Enumeration enums = (Enumeration) type; - return new EnumRenderer(enums).generateTemplate(); - } - return ""; - } - - @Override - public boolean isAcceptable(Type type) { - return type instanceof Enumeration; - } - - @Override - public Identifier getUnitName(Type type) { - return new UnitName(type.getName()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFile.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFile.java deleted file mode 100644 index 48900090a3..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFile.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.base.Splitter; -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.JavaCodePrettyPrint; -import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.UnitName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonatype.plexus.build.incremental.BuildContext; - -/** - * Generates files with JAVA source code for every specified type. - */ -@Beta -public final class GeneratorJavaFile { - - private static final Logger LOG = LoggerFactory.getLogger(GeneratorJavaFile.class); - private static final Splitter BSDOT_SPLITTER = Splitter.on("."); - - /** - * List of CodeGenerator instances. - */ - private final List generators = new ArrayList<>(); - - /** - * Set of Type instances for which the JAVA code is generated. - */ - private final Collection types; - - /** - * BuildContext used for instantiating files. - */ - private final BuildContext buildContext; - - /** - * Creates instance of this class with the set of types for - * which the JAVA code is generated. - * - *

- * The instances of concrete JAVA code generator are created. - * - * @param buildContext - * build context to use for accessing files - * @param types - * set of types for which JAVA code should be generated - */ - public GeneratorJavaFile(final BuildContext buildContext, final Collection types) { - this.buildContext = requireNonNull(buildContext); - this.types = requireNonNull(types); - this.generators.add(new EnumGenerator()); - this.generators.add(new InterfaceGenerator()); - this.generators.add(new BuilderGenerator()); - this.generators.add(new TOGenerator()); - } - - /** - * Generates List of files for collection of types. All files are stored - * to sub-folders of base directory persistentSourcesDirectory. Subdirectories - * are generated according to packages to which the type belongs (e. g. if - * type belongs to the package org.pcg then in persistentSourcesDirectory - * is created directory org which contains pcg). - * - * @param generatedSourcesDirectory expected output directory for generated sources configured by - * user - * @param persistentSourcesDirectory base directory - * @return list of generated files - * @throws IOException thrown in case of I/O error - */ - public List generateToFile(final File generatedSourcesDirectory, final File persistentSourcesDirectory) - throws IOException { - final List result = new ArrayList<>(); - for (final Type type : this.types) { - if (type != null) { - for (final CodeGenerator generator : this.generators) { - File generatedJavaFile = null; - if (type instanceof GeneratedTransferObject - && ((GeneratedTransferObject) type).isUnionTypeBuilder()) { - final File packageDir = packageToDirectory(persistentSourcesDirectory, type.getPackageName()); - final File file = new File(packageDir, generator.getUnitName(type) + ".java"); - if (!file.exists()) { - generatedJavaFile = generateTypeToJavaFile(persistentSourcesDirectory, type, generator); - } - } else { - generatedJavaFile = generateTypeToJavaFile(generatedSourcesDirectory, type, generator); - } - if (generatedJavaFile != null) { - result.add(generatedJavaFile); - } - } - } - } - return result; - } - - /** - * Creates the package directory path as concatenation of - * parentDirectory and parsed packageName. The - * parsing of packageName is realized as replacement of the - * package name dots with the file system separator. - * - * @param parentDirectory - * File object with reference to parent directory - * @param packageName - * string with the name of the package - * @return File object which refers to the new directory for - * package packageName - */ - public static File packageToDirectory(final File parentDirectory, final String packageName) { - if (packageName == null) { - throw new IllegalArgumentException("Package Name cannot be NULL!"); - } - - final StringBuilder dirPathBuilder = new StringBuilder(); - final Iterator packageElementsItr = BSDOT_SPLITTER.split(packageName).iterator(); - if (packageElementsItr.hasNext()) { - dirPathBuilder.append(packageElementsItr.next()); - } - - while (packageElementsItr.hasNext()) { - dirPathBuilder.append(File.separator); - dirPathBuilder.append(packageElementsItr.next()); - } - - return new File(parentDirectory, dirPathBuilder.toString()); - } - - /** - * Generates File for type. All files are stored - * to sub-folders of base directory parentDir. Subdirectories - * are generated according to packages to which the type belongs (e. g. if - * type belongs to the package org.pcg then in parentDir - * is created directory org which contains pcg). - * - * @param parentDir - * directory where should be the new file generated - * @param type - * JAVA Type for which should be JAVA source code - * generated - * @param generator - * code generator which is used for generating of the source code - * @return file which contains JAVA source code - * @throws IOException - * if the error during writing to the file occurs - * @throws IllegalArgumentException - * if type equals null - * @throws IllegalStateException - * if string with generated code is empty - */ - private File generateTypeToJavaFile(final File parentDir, final Type type, final CodeGenerator generator) - throws IOException { - if (parentDir == null) { - LOG.warn("Parent Directory not specified, files will be generated " - + "accordingly to generated Type package path."); - } - if (type == null) { - LOG.error("Cannot generate Type into Java File because " + "Generated Type is NULL!"); - throw new IllegalArgumentException("Generated Type Cannot be NULL!"); - } - if (generator == null) { - LOG.error("Cannot generate Type into Java File because " + "Code Generator instance is NULL!"); - throw new IllegalArgumentException("Code Generator Cannot be NULL!"); - } - - if (generator.isAcceptable(type)) { - File packageDir; - if (generator instanceof BuilderGenerator) { - packageDir = packageToDirectory(parentDir, ((GeneratedTypeForBuilder)type).getPackageNameForBuilder()); - } else { - packageDir = packageToDirectory(parentDir, type.getPackageName()); - } - - if (!packageDir.exists()) { - packageDir.mkdirs(); - } - - final String generatedCode = JavaCodePrettyPrint.perform(generator.generate(type)); - Preconditions.checkState(!generatedCode.isEmpty(), "Generated code should not be empty!"); - final File file = new File(packageDir, ((UnitName) generator.getUnitName(type)).getValue() + ".java"); - - if (file.exists()) { - LOG.warn("Naming conflict for type '{}': file with same name already exists and will not be generated.", - type.getFullyQualifiedName()); - return null; - } - - try (OutputStream stream = this.buildContext.newFileOutputStream(file)) { - try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) { - try (BufferedWriter bw = new BufferedWriter(fw)) { - bw.write(generatedCode); - } - } catch (final IOException e) { - LOG.error("Failed to write generate output into {}", file.getPath(), e); - throw e; - } - } - return file; - - } - return null; - } - -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/InterfaceGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/InterfaceGenerator.java deleted file mode 100644 index 12147fe10d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/InterfaceGenerator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.InterfaceRenderer; -import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.UnitName; -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * Transforms data from virtual form to JAVA source code. Resulting source code represents JAVA - * interface. Source code generation process is supported by interface template written - * in Twirl (Scala based) language. - */ -@Beta -public final class InterfaceGenerator implements CodeGenerator { - - @Override - public String generate(Type type) { - if ((type instanceof GeneratedType) && !(type instanceof GeneratedTransferObject)) { - final GeneratedType genType = (GeneratedType) type; - return new InterfaceRenderer(genType).generateTemplate(); - } else { - return ""; - } - } - - @Override - public boolean isAcceptable(Type type) { - return type instanceof GeneratedType && !(type instanceof GeneratedTransferObject) - && !(type instanceof Enumeration); - } - - @Override - public Identifier getUnitName(Type type) { - return new UnitName(type.getName()); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/TOGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/TOGenerator.java deleted file mode 100644 index 97e9846ef2..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/TOGenerator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.ClassRenderer; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.UnionBuilderRenderer; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.UnionRenderer; -import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.UnitName; -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * Transformer of the data from the virtual form to JAVA source code. The - * result source code represents JAVA class. For generating of the source code - * is used the template written in Twirl (Scala based) language. - */ -@Beta -public class TOGenerator implements CodeGenerator { - - @Override - public String generate(Type type) { - if (type instanceof GeneratedTransferObject) { - final GeneratedTransferObject genTO = (GeneratedTransferObject) type; - if (genTO.isUnionType()) { - return new UnionRenderer(genTO).generateTemplate(); - } else if (genTO.isUnionTypeBuilder()) { - return new UnionBuilderRenderer(genTO).generateTemplate(); - } else { - return new ClassRenderer(genTO).generateTemplate(); - } - } - return ""; - } - - @Override - public boolean isAcceptable(Type type) { - return type instanceof GeneratedTransferObject; - } - - @Override - public Identifier getUnitName(Type type) { - return new UnitName(type.getName()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractBigRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractBigRangeGenerator.java deleted file mode 100644 index b2e2c8642f..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractBigRangeGenerator.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import com.google.common.collect.Range; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; - -/** - * Abstract base for generators which require instantiation of boundary values to check. - * These are implemented by generating an array constant within the class, which contains - * {@link Range} instances, which hold pre-instantiated boundary values. - * - * @param type of the class - */ -abstract class AbstractBigRangeGenerator> extends AbstractRangeGenerator { - private static final String RANGE = Range.class.getName(); - - protected AbstractBigRangeGenerator(final Class typeClass) { - super(typeClass); - } - - private StringBuilder itemType() { - return new StringBuilder(RANGE).append('<').append(getTypeName()).append('>'); - } - - private StringBuilder arrayType() { - return new StringBuilder(itemType()).append("[]"); - } - - @Override - protected final String generateRangeCheckerImplementation(final String checkerName, - @Nonnull final RangeConstraint constraint) { - final Set> constraints = constraint.getAllowedRanges().asRanges(); - final String fieldName = checkerName.toUpperCase() + "_RANGES"; - final StringBuilder sb = new StringBuilder(); - - // Field to hold the Range objects in an array - sb.append("private static final ").append(arrayType()).append(' ').append(fieldName).append(";\n"); - - // Static initializer block for the array - sb.append("static {\n"); - sb.append(" @SuppressWarnings(\"unchecked\")\n"); - sb.append(" final ").append(arrayType()).append(" a = (").append(arrayType()) - .append(") java.lang.reflect.Array.newInstance(").append(RANGE).append(".class, ") - .append(constraints.size()).append(");\n"); - - int count = 0; - for (Range r : constraints) { - final String min = format(getValue(r.lowerEndpoint())); - final String max = format(getValue(r.upperEndpoint())); - sb.append(" a[").append(count++).append("] = ").append(RANGE).append(".closed(").append(min).append(", ") - .append(max).append(");\n"); - } - - sb.append(" ").append(fieldName).append(" = a;\n"); - sb.append("}\n"); - - // Static enforcement method - sb.append("private static void ").append(checkerName).append("(final ").append(getTypeName()) - .append(" value) {\n"); - sb.append(" for (").append(itemType()).append(" r : ").append(fieldName).append(") {\n"); - sb.append(" if (r.contains(value)) {\n"); - sb.append(" return;\n"); - sb.append(" }\n"); - sb.append(" }\n"); - sb.append(" throw new IllegalArgumentException(String.format(\"Invalid range: %s, expected: %s.\", " - + "value, java.util.Arrays.asList(").append(fieldName).append(")));\n"); - sb.append("}\n"); - - return sb.toString(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractPrimitiveRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractPrimitiveRangeGenerator.java deleted file mode 100644 index 15120b42fd..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractPrimitiveRangeGenerator.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import static java.util.Objects.requireNonNull; - -import com.google.common.collect.Range; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Set; -import javax.annotation.Nonnull; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -abstract class AbstractPrimitiveRangeGenerator> extends AbstractRangeGenerator { - private static final Logger LOG = LoggerFactory.getLogger(AbstractPrimitiveRangeGenerator.class); - private final String primitiveName; - private final T minValue; - private final T maxValue; - - protected AbstractPrimitiveRangeGenerator(final Class typeClass, final String primitiveName, final T minValue, - final T maxValue) { - super(typeClass); - this.primitiveName = requireNonNull(primitiveName); - this.minValue = requireNonNull(minValue); - this.maxValue = requireNonNull(maxValue); - } - - /** - * Return the name of the primitive type, as known by the Java language. - * - * @return Primitive type name - */ - @Nonnull protected final String getPrimitiveName() { - return primitiveName; - } - - private boolean needsMaximumEnforcement(final T maxToEnforce) { - return maxValue.compareTo(maxToEnforce) > 0; - } - - private boolean needsMinimumEnforcement(final T minToEnforce) { - return minValue.compareTo(minToEnforce) < 0; - } - - /** - * Format a value into a Java-compilable 'greater equal' compare expression. - * The method would be overrided by {@link AbstractUnsignedIntegerRangeGenerator}. - * - * @param value Number value - * @return Java language compare string representation - */ - @Nonnull protected String gtExpression(T value) { - return "value >= " + format(value); - } - - /** - * Format a value into a Java-compilable 'less equal' compare expression. - * The method would be overrided by {@link AbstractUnsignedIntegerRangeGenerator}. - * - * @param value Number value - * @return Java language compare string representation - */ - @Nonnull protected String ltExpression(T value) { - return "value <= " + format(value); - } - - private Collection createExpressions(final RangeConstraint constraint) { - final Set> constraints = constraint.getAllowedRanges().asRanges(); - final Collection ret = new ArrayList<>(constraints.size()); - - for (Range r : constraints) { - final T min = getValue(r.lowerEndpoint()); - final boolean needMin = needsMinimumEnforcement(min); - - final T max = getValue(r.upperEndpoint()); - final boolean needMax = needsMaximumEnforcement(max); - - if (!needMin && !needMax) { - LOG.debug("Type {} indicates [{}, {}] does not require enforcement", getTypeName(), min, max); - continue; - } - - final StringBuilder sb = new StringBuilder(); - if (needMin) { - sb.append(gtExpression(min)); - } - if (needMax) { - if (needMin) { - sb.append(" && "); - } - sb.append(ltExpression(max)); - } - - ret.add(sb.toString()); - } - - return ret; - } - - private static String createRangeString(final RangeConstraint constraints) { - return constraints.getAllowedRanges().toString(); - } - - @Override - protected final String generateRangeCheckerImplementation(final String checkerName, - final RangeConstraint constraint) { - final StringBuilder sb = new StringBuilder(); - final Collection expressions = createExpressions(constraint); - - sb.append("private static void ").append(checkerName).append("(final ").append(primitiveName) - .append(" value) {\n"); - - if (!expressions.isEmpty()) { - for (String exp : expressions) { - sb.append(" if (").append(exp).append(") {\n"); - sb.append(" return;\n"); - sb.append(" }\n"); - } - - sb.append(" throw new IllegalArgumentException(String.format(\"Invalid range: %s, expected: ") - .append(createRangeString(constraint)).append(".\", value));\n"); - } - - sb.append("}\n"); - - return sb.toString(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractRangeGenerator.java deleted file mode 100644 index 007e39b868..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractRangeGenerator.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import static java.util.Objects.requireNonNull; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import java.util.Map; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractRangeGenerator> { - private static final Logger LOG = LoggerFactory.getLogger(AbstractRangeGenerator.class); - private static final Map> GENERATORS; - - private static void addGenerator(final Builder> builder, - final AbstractRangeGenerator generator) { - builder.put(generator.getTypeClass().getCanonicalName(), generator); - } - - static { - final Builder> b = ImmutableMap.builder(); - addGenerator(b, new ByteRangeGenerator()); - addGenerator(b, new ShortRangeGenerator()); - addGenerator(b, new IntegerRangeGenerator()); - addGenerator(b, new LongRangeGenerator()); - addGenerator(b, new Uint8RangeGenerator()); - addGenerator(b, new Uint16RangeGenerator()); - addGenerator(b, new Uint32RangeGenerator()); - addGenerator(b, new Uint64RangeGenerator()); - addGenerator(b, new BigDecimalRangeGenerator()); - addGenerator(b, new BigIntegerRangeGenerator()); - GENERATORS = b.build(); - } - - private final Class type; - - protected AbstractRangeGenerator(final Class typeClass) { - this.type = requireNonNull(typeClass); - } - - public static AbstractRangeGenerator forType(@Nonnull final Type type) { - final ConcreteType javaType = TypeUtils.getBaseYangType(type); - return GENERATORS.get(javaType.getFullyQualifiedName()); - } - - /** - * Return the type's class. - * - * @return A class object - */ - @Nonnull protected final Class getTypeClass() { - return type; - } - - /** - * Return the type's fully-qualified name. - * - * @return Fully-qualified name - */ - @Nonnull protected final String getTypeName() { - return type.getName(); - } - - /** - * Return the value in the native type from a particular Number instance. - * - * @param value Value as a Number - * @return Value in native format. - */ - @Nonnull protected final T getValue(final Number value) { - if (type.isInstance(value)) { - return type.cast(value); - } - - LOG.debug("Converting value {} from {} to {}", value, value.getClass(), type); - final T ret = convert(value); - - // Check if the conversion lost any precision by performing conversion the other way around - final AbstractRangeGenerator gen = GENERATORS.get(value.getClass().getName()); - final Number check = gen.convert(ret); - if (!value.equals(check)) { - LOG.warn("Number class conversion from {} to {} truncated value {} to {}", value.getClass(), - type, value, ret); - } - - return ret; - } - - // FIXME: Once BUG-3399 is fixed, we should never need this - protected abstract T convert(Number value); - - /** - * Format a value into a Java-compilable expression which results in the appropriate - * type. - * - * @param value Number value - * @return Java language string representation - */ - @Nonnull protected abstract String format(T value); - - /** - * Generate the checker method source code. - * @param checkerName Name of the checker method. - * @param constraint Restrictions which need to be applied. - * @return Method source code. - */ - @Nonnull protected abstract String generateRangeCheckerImplementation(@Nonnull String checkerName, - @Nonnull RangeConstraint constraint); - - private static String rangeCheckerName(final String member) { - return "check" + member + "Range"; - } - - public String generateRangeChecker(@Nonnull final String member, @Nonnull final RangeConstraint constraint) { - return generateRangeCheckerImplementation(rangeCheckerName(member), constraint); - } - - public String generateRangeCheckerCall(@Nonnull final String member, @Nonnull final String valueReference) { - return rangeCheckerName(member) + '(' + valueReference + ");\n"; - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractSubIntegerRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractSubIntegerRangeGenerator.java deleted file mode 100644 index d012b37d67..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractSubIntegerRangeGenerator.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -abstract class AbstractSubIntegerRangeGenerator> extends - AbstractPrimitiveRangeGenerator { - protected AbstractSubIntegerRangeGenerator(final Class typeClass, final String primitiveName, final T - minValue, final T maxValue) { - super(typeClass, primitiveName, minValue, maxValue); - } - - @Override - protected final String format(final T value) { - // Make sure the number constant is cast to the corresponding primitive type - return '(' + getPrimitiveName() + ')' + value; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractUnsignedIntegerRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractUnsignedIntegerRangeGenerator.java deleted file mode 100644 index 00190a4513..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/AbstractUnsignedIntegerRangeGenerator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import javax.annotation.Nonnull; - -abstract class AbstractUnsignedIntegerRangeGenerator> - extends AbstractPrimitiveRangeGenerator { - protected AbstractUnsignedIntegerRangeGenerator(final Class typeClass, final String primitiveName, - final T minValue, final T maxValue) { - super(typeClass, primitiveName, minValue, maxValue); - } - - @Override - protected final String format(final T value) { - // Make sure the number constant is cast to the corresponding primitive type - return getPrimitiveName() + ".valueOf(" + value + ")"; - } - - @Nonnull - @Override - protected String gtExpression(T value) { - return "value.compareTo(" + format(value) + ") >= 0"; - } - - @Nonnull - @Override - protected String ltExpression(T value) { - return "value.compareTo(" + format(value) + ") <= 0"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigDecimalRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigDecimalRangeGenerator.java deleted file mode 100644 index fcdd75b1b4..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigDecimalRangeGenerator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import java.math.BigDecimal; -import java.math.BigInteger; - -final class BigDecimalRangeGenerator extends AbstractBigRangeGenerator { - BigDecimalRangeGenerator() { - super(BigDecimal.class); - } - - @Override - protected String format(final BigDecimal value) { - if (BigDecimal.ZERO.equals(value)) { - return "java.math.BigDecimal.ZERO"; - } - if (BigDecimal.ONE.equals(value)) { - return "java.math.BigDecimal.ONE"; - } - if (BigDecimal.TEN.equals(value)) { - return "java.math.BigDecimal.TEN"; - } - - // FIXME: can we do something better? - return "new java.math.BigDecimal(\"" + value + "\")"; - } - - @Override - protected BigDecimal convert(final Number value) { - if (value instanceof BigInteger) { - return new BigDecimal((BigInteger)value); - } else if (value instanceof Byte) { - return new BigDecimal(value.intValue()); - } else if (value instanceof Short) { - return new BigDecimal(value.intValue()); - } else if (value instanceof Integer) { - return new BigDecimal(value.intValue()); - } else { - return BigDecimal.valueOf(value.longValue()); - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigIntegerRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigIntegerRangeGenerator.java deleted file mode 100644 index 11d3b9919e..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/BigIntegerRangeGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import java.math.BigInteger; - -final class BigIntegerRangeGenerator extends AbstractBigRangeGenerator { - BigIntegerRangeGenerator() { - super(BigInteger.class); - } - - @Override - protected String format(final BigInteger value) { - if (BigInteger.ZERO.equals(value)) { - return "java.math.BigInteger.ZERO"; - } - if (BigInteger.ONE.equals(value)) { - return "java.math.BigInteger.ONE"; - } - if (BigInteger.TEN.equals(value)) { - return "java.math.BigInteger.TEN"; - } - - // Check for conversion to long - final long l = value.longValue(); - if (value.equals(BigInteger.valueOf(l))) { - return "java.math.BigInteger.valueOf(" + l + "L)"; - } else { - return "new java.math.BigInteger(\"" + value.toString() + "\")"; - } - } - - @Override - protected BigInteger convert(final Number value) { - return BigInteger.valueOf(value.longValue()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ByteRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ByteRangeGenerator.java deleted file mode 100644 index 0e5a2044f8..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ByteRangeGenerator.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -final class ByteRangeGenerator extends AbstractSubIntegerRangeGenerator { - ByteRangeGenerator() { - super(Byte.class, byte.class.getName(), Byte.MIN_VALUE, Byte.MAX_VALUE); - } - - @Override - protected Byte convert(final Number value) { - return value.byteValue(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/IntegerRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/IntegerRangeGenerator.java deleted file mode 100644 index 1399eb8fac..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/IntegerRangeGenerator.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -final class IntegerRangeGenerator extends AbstractPrimitiveRangeGenerator { - IntegerRangeGenerator() { - super(Integer.class, int.class.getName(), Integer.MIN_VALUE, Integer.MAX_VALUE); - } - - @Override - protected String format(final Integer value) { - return value.toString(); - } - - @Override - protected Integer convert(final Number value) { - return value.intValue(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LengthGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LengthGenerator.java deleted file mode 100644 index 5dadc18cdd..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LengthGenerator.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import com.google.common.collect.Range; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint; - -public final class LengthGenerator { - private LengthGenerator() { - throw new UnsupportedOperationException(); - } - - private static String lengthCheckerName(final String member) { - return "check" + member + "Length"; - } - - private static Collection createExpressions(final LengthConstraint constraint) { - final Set> constraints = constraint.getAllowedRanges().asRanges(); - final Collection ret = new ArrayList<>(constraints.size()); - - for (Range l : constraints) { - final StringBuilder sb = new StringBuilder("length >"); - - // We have to deal with restrictions being out of integer's range - if (l.lowerEndpoint() <= Integer.MAX_VALUE) { - sb.append('='); - } - sb.append(' ').append(l.lowerEndpoint()); - - final int max = l.upperEndpoint(); - if (max < Integer.MAX_VALUE) { - sb.append(" && length <= ").append(max); - } - - ret.add(sb.toString()); - } - - return ret; - } - - private static String createLengthString(final LengthConstraint constraint) { - return new ArrayList<>(constraint.getAllowedRanges().asRanges()).toString(); - } - - private static String generateArrayLengthChecker(final String member, final LengthConstraint constraint) { - final StringBuilder sb = new StringBuilder(); - final Collection expressions = createExpressions(constraint); - - sb.append("private static void ").append(lengthCheckerName(member)).append("(final byte[] value) {\n"); - - if (!expressions.isEmpty()) { - sb.append(" final int length = value.length;\n"); - - for (String exp : expressions) { - sb.append(" if (").append(exp).append(") {\n"); - sb.append(" return;\n"); - sb.append(" }\n"); - } - - sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ") - .append(createLengthString(constraint)).append(".\", java.util.Arrays.toString(value)));\n"); - } - - sb.append("}\n"); - - return sb.toString(); - } - - private static String generateStringLengthChecker(final String member, final LengthConstraint constraint) { - final StringBuilder sb = new StringBuilder(); - final Collection expressions = createExpressions(constraint); - - sb.append("private static void ").append(lengthCheckerName(member)).append("(final String value) {\n"); - - if (!expressions.isEmpty()) { - sb.append(" final int length = value.length();\n"); - - for (String exp : expressions) { - sb.append(" if (").append(exp).append(") {\n"); - sb.append(" return;\n"); - sb.append(" }\n"); - } - - sb.append(" throw new IllegalArgumentException(String.format(\"Invalid length: %s, expected: ") - .append(createLengthString(constraint)).append(".\", value));\n"); - } - - sb.append("}\n"); - - return sb.toString(); - } - - public static String generateLengthChecker(final String member, final Type type, - final LengthConstraint constraint) { - if (TypeUtils.getBaseYangType(type).getName().contains("[")) { - return generateArrayLengthChecker(member, constraint); - } else { - return generateStringLengthChecker(member, constraint); - } - } - - public static String generateLengthCheckerCall(@Nullable final String member, - @Nonnull final String valueReference) { - return lengthCheckerName(member) + '(' + valueReference + ");\n"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LongRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LongRangeGenerator.java deleted file mode 100644 index 689560aedf..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/LongRangeGenerator.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -final class LongRangeGenerator extends AbstractPrimitiveRangeGenerator { - - protected LongRangeGenerator() { - super(Long.class, long.class.getName(), Long.MIN_VALUE, Long.MAX_VALUE); - } - - @Override - protected String format(final Long value) { - return value.toString() + 'L'; - } - - @Override - protected Long convert(final Number value) { - return value.longValue(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ShortRangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ShortRangeGenerator.java deleted file mode 100644 index 857bac01cb..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/ShortRangeGenerator.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -final class ShortRangeGenerator extends AbstractSubIntegerRangeGenerator { - ShortRangeGenerator() { - super(Short.class, short.class.getName(), Short.MIN_VALUE, Short.MAX_VALUE); - } - - @Override - protected Short convert(final Number value) { - return value.shortValue(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/TypeUtils.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/TypeUtils.java deleted file mode 100644 index e4e12689ad..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/TypeUtils.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -/** - * Random utility methods for dealing with {@link Type} objects. - */ -final class TypeUtils { - private static final String VALUE_PROP = "value"; - - private TypeUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Given a {@link Type} object lookup the base Java type which sits at the top - * of its type hierarchy. - * - * @param type Input Type object - * @return Resolved {@link ConcreteType} instance. - */ - static ConcreteType getBaseYangType(@Nonnull final Type type) { - // Already the correct type - if (type instanceof ConcreteType) { - return (ConcreteType) type; - } - - Preconditions.checkArgument(type instanceof GeneratedTransferObject, "Unsupported type %s", type); - - // Need to walk up the GTO chain to the root - GeneratedTransferObject rootGto = (GeneratedTransferObject) type; - while (rootGto.getSuperType() != null) { - rootGto = rootGto.getSuperType(); - } - - // Look for the 'value' property and return its type - for (GeneratedProperty s : rootGto.getProperties()) { - if (VALUE_PROP.equals(s.getName())) { - return (ConcreteType) s.getReturnType(); - } - } - - // Should never happen - throw new IllegalArgumentException(String.format("Type %s root %s properties %s do not include \"%s\"", - type, rootGto, rootGto.getProperties(), VALUE_PROP)); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint16RangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint16RangeGenerator.java deleted file mode 100644 index 814e1e5c69..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint16RangeGenerator.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import org.opendaylight.yangtools.yang.common.Uint16; - -final class Uint16RangeGenerator extends AbstractUnsignedIntegerRangeGenerator { - Uint16RangeGenerator() { - super(Uint16.class, Uint16.class.getName(), Uint16.valueOf(0), Uint16.valueOf(65535)); - } - - @Override - protected Uint16 convert(final Number value) { - return Uint16.valueOf(value.intValue()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint32RangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint32RangeGenerator.java deleted file mode 100644 index 4c7b832105..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint32RangeGenerator.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import org.opendaylight.yangtools.yang.common.Uint32; - -final class Uint32RangeGenerator extends AbstractUnsignedIntegerRangeGenerator { - Uint32RangeGenerator() { - super(Uint32.class, Uint32.class.getName(), Uint32.valueOf(0), - Uint32.valueOf(0xffffffffL)); - } - - @Override - protected Uint32 convert(final Number value) { - return Uint32.valueOf(value.longValue()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint64RangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint64RangeGenerator.java deleted file mode 100644 index cbd71e6a82..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint64RangeGenerator.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import com.google.common.primitives.UnsignedLong; -import java.math.BigInteger; -import org.opendaylight.yangtools.yang.common.Uint64; - -final class Uint64RangeGenerator extends AbstractUnsignedIntegerRangeGenerator { - Uint64RangeGenerator() { - super(Uint64.class, Uint64.class.getName(), Uint64.valueOf(0), Uint64.fromUnsignedLong( - UnsignedLong.fromLongBits(0xffffffffffffffffL))); - } - - @Override - protected Uint64 convert(final Number value) { - return Uint64.valueOf(BigInteger.class.cast(value)); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint8RangeGenerator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint8RangeGenerator.java deleted file mode 100644 index fabbd99e1a..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/range_generators/Uint8RangeGenerator.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators; - -import org.opendaylight.yangtools.yang.common.Uint8; - -final class Uint8RangeGenerator extends AbstractUnsignedIntegerRangeGenerator { - Uint8RangeGenerator() { - super(Uint8.class, Uint8.class.getName(), Uint8.valueOf(0), Uint8.valueOf(255)); - } - - @Override - protected Uint8 convert(final Number value) { - return Uint8.valueOf(value.shortValue()); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BaseRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BaseRenderer.java deleted file mode 100644 index e81dd9d84a..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BaseRenderer.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; - -import com.google.common.collect.ImmutableMap; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.eclipse.jdt.annotation.NonNull; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.WildcardType; - - - -public abstract class BaseRenderer { - private static final String COMMA = ","; - private static final String DOT = "."; - - private final GeneratedType genType; - private final Map importMap; - /** - * list of all imported names for template. - */ - private final Map importedNames = new HashMap<>(); - - protected BaseRenderer(final GeneratedType type) { - this.genType = requireNonNull(type); - this.importMap = new HashMap<>(); - } - - /** - * Implementation needs to call Scala template render() method to generate string body. - * @return rendered body - */ - protected abstract String body(); - - protected GeneratedType getType() { - return genType; - } - - protected Map getImportedNames() { - return importedNames; - } - - protected String getFromImportMap(@NonNull final String typeName) { - return importMap.get(typeName); - } - - protected void putToImportMap(@NonNull final String typeName, final String typePackageName) { - importMap.put(typeName, typePackageName); - } - - protected void putAllToImportMap(@NonNull final Map imports) { - importMap.putAll(imports); - } - - protected Map getImportMap() { - return ImmutableMap.copyOf(importMap); - } - - /** - * Return string with type name for type in the full format or in the short format. - * @param intype type to format and add to imports - * @return formatted type - */ - protected String importedName(final Type intype) { - putTypeIntoImports(genType, intype); - return getExplicitType(genType, intype); - } - - protected String importedName(final Class cls) { - return importedName(Types.typeForClass(cls)); - } - - /** - * Generate package definition for template. - * @return package definition for template - */ - protected String packageDefinition() { - final StringBuilder sb = new StringBuilder(); - sb.append("package ") - .append(genType.getPackageName()) - .append(";\n\n"); - return sb.toString(); - } - - /** - * walks through map of imports. - * @return string of imports for template - */ - private String imports() { - final StringBuilder sb = new StringBuilder(); - if (!importMap.isEmpty()) { - for (Map.Entry entry : importMap.entrySet()) { - if (!hasSamePackage(entry.getValue())) { - sb.append("import ") - .append(entry.getValue()) - .append('.') - .append(entry.getKey()) - .append(";\n"); - } - } - } - return sb.toString(); - } - - /** - * Template method which generates method parameters with their types from parameters. - * - * @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 - */ - protected String asArgumentsDeclaration(final Collection parameters) { - final List strings = new LinkedList<>(); - if (parameters.iterator().hasNext()) { - for (GeneratedProperty parameter : parameters) { - final StringBuilder sb = new StringBuilder(); - sb.append(importedName(parameter.getReturnType())); - sb.append(' '); - sb.append(TextTemplateUtil.fieldName(parameter)); - strings.add(sb); - } - } - return String.join(", ", strings); - } - - /** - * Checks if package of generated type and imported type is the same. - * @param importedTypePackageName imported types package name - * @return equals packages - */ - protected boolean hasSamePackage(final String importedTypePackageName) { - return genType.getPackageName().equals(importedTypePackageName); - } - - /** - * Evaluates if it is necessary to add the package name for type to the map of imports for parentGenType - * If it is so the package name is saved to the map imports. - * - * @param parentGenType generated type for which is the map of necessary imports build - * @param type JAVA type for which is the necessary of the package import evaluated - */ - private void putTypeIntoImports(final GeneratedType parentGenType, final Type type) { - checkArgument(parentGenType != null, "Parent Generated Type parameter MUST be specified and cannot be NULL!"); - checkArgument(type != null, "Type parameter MUST be specified and cannot be NULL!"); - checkArgument(parentGenType.getPackageName() != null, - "Parent Generated Type cannot have Package Name referenced as NULL!"); - - final String typeName = requireNonNull(type.getName()); - final String typePackageName = requireNonNull(type.getPackageName()); - final String parentTypeName = requireNonNull(parentGenType.getName()); - if (typeName.equals(parentTypeName) || typePackageName.startsWith("java.lang") || typePackageName.isEmpty()) { - return; - } - if (!importMap.containsKey(typeName)) { - importMap.put(typeName, typePackageName); - } - if (type instanceof ParameterizedType) { - final ParameterizedType paramType = (ParameterizedType) type; - final Type[] params = paramType.getActualTypeArguments(); - if (params != null) { - for (Type param : params) { - putTypeIntoImports(parentGenType, param); - } - } - } - } - - /** - * Builds the string which contains either the full path to the type (package name with type) or only type name - * if the package is among imports. - * - * @param parentGenType generated type which contains type - * @param type JAVA type for which is the string with type info generated - * @return string with type name for type in the full format or in the short format - */ - private String getExplicitType(final GeneratedType parentGenType, final Type type) { - checkArgument(type != null, "Type parameter MUST be specified and cannot be NULL!"); - checkArgument(importMap != null, "Imports Map cannot be NULL!"); - - final String typePackageName = requireNonNull(type.getPackageName()); - final String typeName = requireNonNull(type.getName()); - final String importedPackageName = importMap.get(typeName); - final StringBuilder sb; - if (typePackageName.equals(importedPackageName)) { - sb = new StringBuilder(typeName); - addActualTypeParameters(sb, type, parentGenType); - if (sb.toString().equals("Void")) { - return "void"; - } - } else { - sb = new StringBuilder(); - if (!typePackageName.isEmpty()) { - sb.append(typePackageName).append(DOT).append(typeName); - } else { - sb.append(type.getName()); - } - if (type.equals(Types.voidType())) { - return "void"; - } - addActualTypeParameters(sb, type, parentGenType); - } - return sb.toString(); - } - - /** - * Adds actual type parameters from type to builder if type is ParametrizedType. - * - * @param sb string builder which contains type name - * @param type JAVA Type for which is the string with type info generated - * @param parentGenType generated type which contains type - * @return adds actual type parameters to builder - */ - private StringBuilder addActualTypeParameters(final StringBuilder sb, final Type type, - final GeneratedType parentGenType) { - if (type instanceof ParameterizedType) { - final ParameterizedType pType = (ParameterizedType) type; - final Type[] pTypes = pType.getActualTypeArguments(); - sb.append('<'); - sb.append(getParameters(parentGenType, pTypes)); - sb.append('>'); - } - return sb; - } - - protected GeneratedProperty findProperty(final GeneratedTransferObject gto, final String name) { - for (GeneratedProperty prop : gto.getProperties()) { - if (name.equals(prop.getName())) { - return prop; - } - } - final GeneratedTransferObject parent = gto.getSuperType(); - if (parent != null) { - return findProperty(parent, name); - } - return null; - } - - /** - * Generates the string with all actual type parameters from. - * - * @param parentGenType generated type for which is the JAVA code generated - * @param types array of Type instances = actual type parameters - * @return string with all actual type parameters from types - */ - private String getParameters(final GeneratedType parentGenType, final Type[] types) { - if (types == null || types.length == 0) { - return "?"; - } - final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < types.length; i++) { - final Type t = types[i]; - - String separator = COMMA; - if (i == types.length - 1) { - separator = ""; - } - - - if (t.equals(Types.voidType())) { - sb.append("java.lang.Void") - .append(separator); - continue; - } else { - - String wildcardParam = ""; - if (t instanceof WildcardType) { - wildcardParam = "? extends "; - } - - sb.append(wildcardParam).append(getExplicitType(parentGenType, t)).append(separator); - } - } - return sb.toString(); - } - - /** - * Template method which generates method parameters with their types from parameters. - * InterfaceTemplate / UnionTemaplate - * - * @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 - */ - protected String generateParameters(final List parameters) { - final List strings = new LinkedList<>(); - if (!parameters.isEmpty()) { - for (MethodSignature.Parameter parameter : parameters) { - final StringBuilder sb = new StringBuilder(); - sb.append(importedName(parameter.getType())); - sb.append(' '); - sb.append(parameter.getName()); - strings.add(sb); - } - } - return String.join(", ", strings); - } - - /** - * Template method which generates the getter method for 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 - */ - protected String getterMethod(final GeneratedProperty field) { - final StringBuilder sb = new StringBuilder(); - final String name = TextTemplateUtil.fieldName(field); - final String importedName = requireNonNull(importedName(field.getReturnType())); - sb.append("public ") - .append(importedName) - .append(' ') - .append(TextTemplateUtil.getterMethodName(field)) - .append("() {") - .append("return ") - .append(name); - if (!(field.getReturnType() instanceof ParameterizedType) - && importedName.contains("[]")) { - sb.append(" == null ? null : ") - .append(name) - .append(".clone()"); - } - sb.append(";}\n"); - return sb.toString(); - } - - /** - * builds template. - * @return generated final template - */ - public String generateTemplate() { - final StringBuilder sb = new StringBuilder(); - /* sb body must be filled before imports method call */ - final String templateBody = body(); - sb.append(packageDefinition()) - .append(imports()) - .append(templateBody); - return sb.toString(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRenderer.java deleted file mode 100755 index ac4d63fb09..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRenderer.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.typeForClass; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.DOT; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getPropertyList; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.toFirstLower; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.common.collect.ClassToInstanceMap; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSortedSet; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.regex.Pattern; - -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes; -import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.builderConstructorHelperTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.builderTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.constantsTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.AlphabeticallyTypeMemberComparator; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.CodeHelpers; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder; -import org.opendaylight.yangtools.concepts.Builder; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.yang.common.QName; - -public class BuilderRenderer extends BaseRenderer { - - /** - * Set of class attributes (fields) which are derived from the getter methods names. - */ - private final Set properties; - - /** - * Set of name from properties. - */ - private final Map importedNamesForProperties = new HashMap<>(); - - /** - * Generated property is set if among methods is found one with the name GET_AUGMENTATION_METHOD_NAME. - */ - private GeneratedProperty augmentField; - - boolean instantiable = false; - - public BuilderRenderer(final GeneratedType type) { - super(type); - this.properties = propertiesFromMethods(createMethods()); - putToImportMap(Builder.class.getSimpleName(), Builder.class.getPackage().getName()); - putToImportMap(type.getName(), type.getPackageName()); - } - - @Override - protected String packageDefinition() { - final StringBuilder sb = new StringBuilder(); - sb.append("package ") - .append(((GeneratedTypeForBuilder) getType()).getPackageNameForBuilder()) - .append(";\n\n"); - return sb.toString(); - } - - @Override - protected boolean hasSamePackage(final String importedTypePackageName) { - return ((GeneratedTypeForBuilder) getType()).getPackageNameForBuilder() - .equals(importedTypePackageName); - } - - /** - * Creates set of generated property instances from getter methods. - * - * @param methods set of method signature instances which should be transformed to list of properties - * @return set of generated property instances which represents the getter methods - */ - private Set propertiesFromMethods(final Collection methods) { - if (methods == null || methods.isEmpty()) { - return Collections.emptySet(); - } - final Set result = new LinkedHashSet<>(); - for (MethodSignature method : methods) { - final GeneratedProperty createdField = propertyFromGetter(method); - if (createdField != null) { - result.add(createdField); - importedNamesForProperties.put(createdField, importedName(createdField.getReturnType())); - if (createdField.getReturnType().equals(typeForClass(List.class))) { - getImportedNames().put("arrayList", importedName(ArrayList.class)); - } - } - } - return result; - } - - /** - * Creates generated property instance from the getter method 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 method - * @throws IllegalArgumentException

  • if the method equals null
  • - *
  • if the name of the method equals null
  • - *
  • if the name of the method is empty
  • - *
  • if the return type of the method equals null
  • - */ - private GeneratedProperty propertyFromGetter(final MethodSignature method) { - Preconditions.checkArgument(method != null, "Method cannot be NULL"); - Preconditions.checkArgument(!Strings.isNullOrEmpty(method.getName()), - "Method name cannot be NULL or empty"); - Preconditions.checkArgument(method.getReturnType() != null, - "Method return type reference cannot be NULL"); - final String prefix = Types.BOOLEAN.equals(method.getReturnType()) ? "is" : "get"; - if (method.getName().startsWith(prefix)) { - final String fieldName = toFirstLower(method.getName().substring(prefix.length())); - final GeneratedTOBuilderImpl tmpGenTO = - new GeneratedTOBuilderImpl("foo", "foo", true); - tmpGenTO.addProperty(fieldName).setReturnType(method.getReturnType()); - return tmpGenTO.toInstance().getProperties().get(0); - } - return null; - } - - /** - * Returns set of method signature instances which contains all the methods of the genType - * and all the methods of the implemented interfaces. - * - * @returns set of method signature instances - */ - private Set createMethods() { - final Set methods = new LinkedHashSet<>(); - methods.addAll(getType().getMethodDefinitions()); - collectImplementedMethods(methods, getType().getImplements()); - final Set sortedMethods = ImmutableSortedSet.orderedBy( - new AlphabeticallyTypeMemberComparator()) - .addAll(methods) - .build(); - return sortedMethods; - } - - /** - * Adds to the methods set all the methods of the implementedIfcs - * and recursively their implemented interfaces. - * - * @param methods set of method signatures - * @param implementedIfcs list of implemented interfaces - */ - private void collectImplementedMethods(final Set methods, List implementedIfcs) { - if (implementedIfcs != null && !implementedIfcs.isEmpty()) { - for (Type implementedIfc : implementedIfcs) { - if ((implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject))) { - final GeneratedType ifc = (GeneratedType) implementedIfc; - if (implementedIfc instanceof GeneratedTypeForBuilder) { - methods.addAll(ifc.getMethodDefinitions()); - } - collectImplementedMethods(methods, ifc.getImplements()); - } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) { - for (Method method : Augmentable.class.getMethods()) { - if ("getAugmentation".equals(method.getName())) { - final String fullyQualifiedName = method.getReturnType().getName(); - final String aPackage = getPackage(fullyQualifiedName); - final String name = getName(fullyQualifiedName); - final GeneratedTOBuilderImpl generatedTOBuilder = new GeneratedTOBuilderImpl(aPackage, - name, true); - final ReferencedTypeImpl referencedType = new ReferencedTypeImpl(aPackage, name, - true, null); - final ReferencedTypeImpl generic = new ReferencedTypeImpl(getType().getPackageName(), - getType().getName(), true, null); - final ParameterizedType parametrizedReturnType = - Types.parameterizedTypeFor(referencedType, generic); - generatedTOBuilder.addMethod(method.getName()).setReturnType(parametrizedReturnType); - augmentField = propertyFromGetter(generatedTOBuilder.toInstance().getMethodDefinitions() - .get(0)); - getImportedNames().put("map", importedName(Map.class)); - getImportedNames().put("hashMap", importedName(HashMap.class)); - getImportedNames().put("class", importedName(Class.class)); -// To do This is for third party, is it needed ? - getImportedNames().put("augmentationHolder", importedName(AugmentationHolder.class)); - getImportedNames().put("collections", importedName(Collections.class)); - getImportedNames().put("augmentFieldReturnType", importedName( - augmentField.getReturnType())); - } - } - } else if (Instantiable.class.getName().equals(implementedIfc.getFullyQualifiedName())) { - getImportedNames().put("class", importedName(Class.class)); - instantiable = true; - } - } - } - } - - /** - * Returns the name of the package from fullyQualifiedName. - * - * @param fullyQualifiedName string with fully qualified type name (package + type) - * @return string with the package name - */ - private String getPackage(final String fullyQualifiedName) { - final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT); - return (lastDotIndex == -1) ? "" : fullyQualifiedName.substring(0, lastDotIndex); - } - - /** - * Returns the name of the type from fullyQualifiedName. - * - * @param fullyQualifiedName string with fully qualified type name (package + type) - * @return string with the name of the type - */ - private String getName(final String fullyQualifiedName) { - final int lastDotIndex = fullyQualifiedName.lastIndexOf(DOT); - return (lastDotIndex == -1) ? fullyQualifiedName : fullyQualifiedName.substring(lastDotIndex + 1); - } - - public static Set getAllIfcs(final Type type) { - final Set baseIfcs = new HashSet<>(); - if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) { - for (Type impl : ((GeneratedType) type).getImplements()) { - if (impl instanceof GeneratedType && !(((GeneratedType) impl).getMethodDefinitions().isEmpty())) { - baseIfcs.add(impl); - } - baseIfcs.addAll(getAllIfcs(impl)); - } - } - return baseIfcs; - } - - /** - * Method is used to find out if given type implements any interface from uses. - * - * @param type type to inspect - * @return has implements from uses-stmt true/false - */ - public static boolean hasImplementsFromUses(GeneratedType type) { - for (Type impl : getAllIfcs(type)) { - if ((impl instanceof GeneratedType) && !(((GeneratedType) impl).getMethodDefinitions().isEmpty())) { - return true; - } - } - return false; - } - - public static Set toListOfNames(final Set types) { - final Set names = new HashSet<>(); - for (Type currentType : types) { - names.add(currentType.getFullyQualifiedName()); - } - return names; - } - - @Override - protected String body() { - final String parentTypeForBuilderName; - getImportedNames().put("genType", importedName(getType())); - getImportedNames().put("objects", importedName(Objects.class)); - getImportedNames().put("object", importedName(Object.class)); - getImportedNames().put("string", importedName(String.class)); - getImportedNames().put("arrays", importedName(Arrays.class)); - getImportedNames().put("stringBuilder", importedName(StringBuilder.class)); - getImportedNames().put("treeNode", importedName(TreeNode.class)); - getImportedNames().put("instantiable", importedName(Instantiable.class)); - getImportedNames().put("item", importedName(Item.class)); - getImportedNames().put("identifiableItem", importedName(IdentifiableItem.class)); - getImportedNames().put("qname", importedName(QName.class)); - getImportedNames().put("codeHelpers", importedName(CodeHelpers.class)); - getImportedNames().put("list", importedName(List.class)); - getImportedNames().put("immutableList", importedName(ImmutableList.class)); - getImportedNames().put("pattern", importedName(Pattern.class)); - - if (getType().getParentType() != null) { - getImportedNames().put("parent", importedName(getType().getParentType())); - parentTypeForBuilderName = getType().getParentType().getFullyQualifiedName(); - } else if (getType().getParentTypeForBuilder() != null) { - getImportedNames().put("parentTypeForBuilder", importedName(getType().getParentTypeForBuilder())); - parentTypeForBuilderName = getType().getParentTypeForBuilder().getFullyQualifiedName(); - } else { - parentTypeForBuilderName = null; - } - - boolean childTreeNode = false; - boolean childTreeNodeIdent = false; - String keyTypeName = null; - if (getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) { - childTreeNode = true; - if (getType().getImplements().contains(BindingTypes.IDENTIFIABLE)) { - childTreeNodeIdent = true; - final ParameterizedType pType = (ParameterizedType) getType().getImplements().get(getType() - .getImplements().indexOf(BindingTypes.IDENTIFIABLE)); - keyTypeName = pType.getActualTypeArguments()[0].getName(); - } - } - - getImportedNames().put("augmentation", importedName(Augmentation.class)); - getImportedNames().put("classInstMap", importedName(ClassToInstanceMap.class)); - - final String constants = constantsTemplate.render(getType(), getImportedNames(), this::importedName, false) - .body(); - - // list for generate copy constructor - final String copyConstructorHelper = generateListForCopyConstructor(); - List getterMethods = new ArrayList<>(Collections2.transform(properties, this::getterMethod)); - - return builderTemplate.render(getType(), properties, getImportedNames(), importedNamesForProperties, - augmentField, - copyConstructorHelper, getterMethods, parentTypeForBuilderName, childTreeNode, childTreeNodeIdent, - keyTypeName, instantiable, constants).body(); - } - - private String generateListForCopyConstructor() { - final List allProps = new ArrayList<>(properties); - final boolean isList = implementsIfc(getType(), - Types.parameterizedTypeFor(typeForClass(Identifiable.class), getType())); - final Type keyType = getKey(getType()); - if (isList && keyType != null) { - final List keyProps = ((GeneratedTransferObject) keyType).getProperties(); - for (GeneratedProperty keyProp : keyProps) { - removeProperty(allProps, keyProp.getName()); - } - removeProperty(allProps, "key"); - getImportedNames().put("keyTypeConstructor", importedName(keyType)); - return builderConstructorHelperTemplate.render(allProps, keyProps, getImportedNames(), - getPropertyList(keyProps)).body(); - } - return builderConstructorHelperTemplate.render(allProps, null, getImportedNames(), null).body(); - } - - private Type getKey(final GeneratedType genType) { - for (MethodSignature methodSignature : genType.getMethodDefinitions()) { - if ("getKey".equals(methodSignature.getName())) { - return methodSignature.getReturnType(); - } - } - return null; - } - - private boolean implementsIfc(final GeneratedType type, final Type impl) { - return type.getImplements().contains(impl); - } - - private void removeProperty(final Collection props, final String name) { - for (final GeneratedProperty property : props) { - if (name.equals(property.getName())) { - props.remove(property); - break; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/ClassRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/ClassRenderer.java deleted file mode 100644 index 962955900d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/ClassRenderer.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.setterMethod; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Collections2; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.io.BaseEncoding; - -import java.beans.ConstructorProperties; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; - -import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.AbstractRangeGenerator; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.LengthGenerator; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.classTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.classTemplateConstructors; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.classTemplateRestrictions; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.classTemplateUnionConstr; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.constantsTemplate; -import org.opendaylight.mdsal.binding.javav2.model.api.Constant; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.Uint16; -import org.opendaylight.yangtools.yang.common.Uint32; -import org.opendaylight.yangtools.yang.common.Uint64; -import org.opendaylight.yangtools.yang.common.Uint8; - -public class ClassRenderer extends BaseRenderer { - protected final GeneratedTransferObject genTO; - protected final Restrictions restrictions; - private final List properties; - private final List finalProperties; - private final List parentProperties; - private final List enums; - private final List consts; - private final List enclosedGeneratedTypes; - private final List allProperties; - - private final AbstractRangeGenerator rangeGenerator; - - public ClassRenderer(final GeneratedTransferObject genType) { - super(genType); - genTO = genType; - properties = ImmutableList.copyOf(genTO.getProperties()); - finalProperties = ImmutableList.copyOf(resolveReadOnlyPropertiesFromTO(genTO.getProperties())); - parentProperties = ImmutableList.copyOf(getPropertiesOfAllParents(genTO)); - enums = ImmutableList.copyOf(genTO.getEnumerations()); - consts = ImmutableList.copyOf(genTO.getConstantDefinitions()); - enclosedGeneratedTypes = ImmutableList.copyOf(genTO.getEnclosedTypes()); - restrictions = genTO.getRestrictions(); - - final List sorted = new ArrayList<>(); - sorted.addAll(properties); - sorted.addAll(parentProperties); - final Comparator function = (GeneratedProperty p1, GeneratedProperty p2) -> { - final String name = p1.getName(); - final String name1 = p2.getName(); - return name.compareTo(name1); - }; - sorted.sort(function); - allProperties = ImmutableList.copyOf(sorted); - - if (restrictions != null && restrictions.getRangeConstraint().isPresent()) { - rangeGenerator = AbstractRangeGenerator.forType(findProperty(genType, "value").getReturnType()); - requireNonNull(rangeGenerator); - } else { - rangeGenerator = null; - } - } - - protected List getProperties() { - return properties; - } - - protected List getFinalProperties() { - return finalProperties; - } - - protected List getParentProperties() { - return parentProperties; - } - - protected List getEnums() { - return enums; - } - - protected List getConsts() { - return consts; - } - - protected List getEnclosedGeneratedTypes() { - return enclosedGeneratedTypes; - } - - protected Collection getAllProperties() { - return allProperties; - } - - protected String generateAsInnerClass() { - return generateBody(true); - } - - @Override - protected String body() { - return generateBody(false); - } - - protected String generateInnerClassBody(final GeneratedTransferObject innerClass) { - final ClassRenderer classRenderer = new ClassRenderer(innerClass); - final String body = classRenderer.generateAsInnerClass(); - this.putAllToImportMap(classRenderer.getImportMap()); - return body; - } - - protected String generateBody(final boolean isInnerClass) { - getImportedNames().put("type", importedName(getType())); - getImportedNames().put("arrays", importedName(Arrays.class)); - getImportedNames().put("objects", importedName(Objects.class)); - getImportedNames().put("string", importedName(String.class)); - getImportedNames().put("byte", importedName(Byte.class)); - getImportedNames().put("short", importedName(Short.class)); - getImportedNames().put("integer", importedName(Integer.class)); - getImportedNames().put("long", importedName(Long.class)); - getImportedNames().put("uint8", importedName(Uint8.class)); - getImportedNames().put("uint16", importedName(Uint16.class)); - getImportedNames().put("uint32", importedName(Uint32.class)); - getImportedNames().put("uint64", importedName(Uint64.class)); - getImportedNames().put("stringBuilder", importedName(StringBuilder.class)); - getImportedNames().put("list", importedName(List.class)); - getImportedNames().put("lists", importedName(Lists.class)); - getImportedNames().put("illegalArgumentException", importedName(IllegalArgumentException.class)); - getImportedNames().put("boolean", importedName(Boolean.class)); - getImportedNames().put("qname", importedName(QName.class)); - - final List implementsListBuilder = new LinkedList<>(); - if (!getType().getImplements().isEmpty()) { - for (Type impl : getType().getImplements()) { - implementsListBuilder.add((importedName(impl))); - } - } - final String implementsList = String.join(", ", implementsListBuilder); - - final List classTemplateBuilder = new LinkedList<>(); - if (!enclosedGeneratedTypes.isEmpty()) { - for (GeneratedType innerClass : enclosedGeneratedTypes) { - if (innerClass instanceof GeneratedTransferObject) { - classTemplateBuilder.add(generateInnerClassBody((GeneratedTransferObject) innerClass)); - } - } - } - final String innerClasses = String.join("\n", classTemplateBuilder); - - final List enumList = new LinkedList<>(); - if (!enums.isEmpty()) { - for (Enumeration enumeration : enums) { - enumList.add(new EnumRenderer(enumeration).body()); - } - } - final String enumerations = String.join("\n", enumList); - - final String constants = constantsTemplate.render(getType(), getImportedNames(), this::importedName, false) - .body(); - - if (genTO.getSuperType() != null) { - getImportedNames().put("superType", importedName(genTO.getSuperType())); - } - - for (GeneratedProperty property : properties) { - getImportedNames().put(property.getReturnType().toString(), importedName(property.getReturnType())); - } - - final String constructors = generateConstructors(); - - final StringBuilder lengthRangeCheckerBuilder = new StringBuilder(); - if (restrictions != null) { - if (restrictions.getLengthConstraint().isPresent()) { - lengthRangeCheckerBuilder.append(LengthGenerator.generateLengthChecker("_value", findProperty(genTO, - "value").getReturnType(), restrictions.getLengthConstraint().get())) - .append("\n"); - } - if (restrictions.getRangeConstraint().isPresent()) { - lengthRangeCheckerBuilder.append(rangeGenerator.generateRangeChecker("_value", restrictions - .getRangeConstraint().get())) - .append("\n"); - } - } - final String lengthRangeChecker = lengthRangeCheckerBuilder.toString(); - - final StringBuilder sb2 = new StringBuilder(); - if (!properties.isEmpty()) { - for (GeneratedProperty property : properties) { - final String isFinal = property.isReadOnly() ? " final " : " "; - sb2.append("private") - .append(isFinal) - .append(importedName(property.getReturnType())) - .append(' ') - .append(fieldName(property)) - .append(";\n"); - } - } - final String fields = sb2.toString(); - getImportedNames().put("baseEncoding", importedName(BaseEncoding.class)); - if (!allProperties.isEmpty()) { - getImportedNames().put("defProp", importedName(((GeneratedProperty) ((List) allProperties).get(0)) - .getReturnType())); - } - - final StringBuilder sb3 = new StringBuilder(); - for (GeneratedProperty property : properties) { - sb3.append(getterMethod(property)); - if (!property.isReadOnly()) { - sb3.append(setterMethod(property, getType().getName(), importedName(property - .getReturnType()))); - } - } - final String propertyMethod = sb3.toString(); - - return classTemplate.render(getType(), genTO, getImportedNames(), implementsList, innerClasses, enumerations, - constants, constructors, lengthRangeChecker, fields, allProperties, propertyMethod, - isInnerClass).body(); - } - - protected String generateConstructors() { - getImportedNames().put("constructorProperties", importedName(ConstructorProperties.class)); - getImportedNames().put("preconditions", importedName(Preconditions.class)); - - final StringBuilder sb1 = new StringBuilder(); - for (GeneratedProperty allProperty : allProperties) { - sb1.append(classTemplateRestrictions.render(getType(), fieldName(allProperty), allProperty - .getReturnType(), rangeGenerator).body()); - } - final String genRestrictions = sb1.toString(); - - final StringBuilder sb2 = new StringBuilder(); - if (genTO.isUnionType()) { - for (GeneratedProperty allProperty : allProperties) { - final List other = new ArrayList<>(properties); - if (other.remove(allProperty)) { - sb2.append(classTemplateUnionConstr.render(getType(), parentProperties, allProperty, - other, importedName(allProperty.getReturnType()), genRestrictions).body()); - } - } - } - final String unionConstructor = sb2.toString(); - - final String argumentsDeclaration = asArgumentsDeclaration(allProperties); - return classTemplateConstructors.render(genTO, allProperties, properties, parentProperties, - getImportedNames(), argumentsDeclaration, unionConstructor, genRestrictions).body(); - } - - /** - * Selects from input list of properties only those which have read only - * attribute set to true. - * - * @param props list of properties of generated transfer object - * @return subset of properties which have read only attribute - * set to true - */ - private List resolveReadOnlyPropertiesFromTO(final List props) { - return new ArrayList<>(Collections2.filter(props, GeneratedProperty::isReadOnly)); - } - - /** - * Returns the list of the read only properties of all extending generated - * transfer object from genTO to highest parent generated - * transfer object. - * - * @param transferObject generated transfer object for which is the list of read only - * properties generated - * @return list of all read only properties from actual to highest parent - * generated transfer object. In case when extension exists the - * method is recursive called. - */ - private List getPropertiesOfAllParents(final GeneratedTransferObject transferObject) { - final List propertiesOfAllParents = new ArrayList<>(); - if (transferObject.getSuperType() != null) { - final List allPropertiesOfTO = transferObject.getSuperType().getProperties(); - List readOnlyPropertiesOfTO = resolveReadOnlyPropertiesFromTO(allPropertiesOfTO); - propertiesOfAllParents.addAll(readOnlyPropertiesOfTO); - propertiesOfAllParents.addAll(getPropertiesOfAllParents(transferObject.getSuperType())); - } - return propertiesOfAllParents; - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/EnumRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/EnumRenderer.java deleted file mode 100644 index c6b6856419..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/EnumRenderer.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.asJavadoc; -import static org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.encodeAngleBrackets; - -import java.util.LinkedList; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.enumTemplate; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; - -public class EnumRenderer extends BaseRenderer { - private final Enumeration enums; - - public EnumRenderer(final Enumeration type) { - super(type); - enums = type; - } - - @Override - protected String body() { - String importedName = importedName(String.class); - return enumTemplate.render(enums, importedName).body(); - } - - /** - * Return list of enumeration pairs with javadoc. - * @param enumeration enumeration to write. - * @return List of enumeration pairs with javadoc - */ - public static String writeEnumeration(final Enumeration enumeration) { - final List strings = new LinkedList<>(); - if (!enumeration.getValues().isEmpty()) { - for (Enumeration.Pair pair : enumeration.getValues()) { - final StringBuilder sb = new StringBuilder(); - sb.append(asJavadoc(encodeAngleBrackets(pair.getDescription().orElse(null)))); - sb.append("\n"); - sb.append(pair.getMappedName()); - sb.append('('); - sb.append(pair.getValue()); - sb.append(", \""); - sb.append(pair.getName()); - sb.append("\")"); - strings.add(sb); - } - } - return String.join(",\n", strings).concat(";"); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/InterfaceRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/InterfaceRenderer.java deleted file mode 100755 index 6ac8d53cb1..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/InterfaceRenderer.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static java.util.Objects.requireNonNull; - -import java.util.AbstractMap.SimpleEntry; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingTypes; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.constantsTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.enumTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.interfaceTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil; -import org.opendaylight.mdsal.binding.javav2.model.api.AnnotationType; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.yang.common.QName; - -public class InterfaceRenderer extends BaseRenderer { - - private static final char NEW_LINE = '\n'; - - /** - * Creates the instance of this class which is used for generating the interface file source - * code from type. - * @param type generated type - */ - public InterfaceRenderer(final GeneratedType type) { - super(type); - requireNonNull(type, "Generated type reference cannot be NULL!"); - } - - @Override - protected String body() { - // mainAnnotations string with annotations for whole interface - final String mainAnnotations = generateAnnotations(getType().getAnnotations()); - // StringBuilder string with the declaration of methods source code in JAVA format - final StringBuilder sb1 = new StringBuilder(); - for (MethodSignature method : getType().getMethodDefinitions()) { - if (isAccessor(method)) { - sb1.append(TextTemplateUtil.asJavadoc(method.getComment())); - } else { - sb1.append(TextTemplateUtil.getJavaDocForInterface(method)); - } - sb1.append(generateAnnotations(method.getAnnotations())) - .append(importedName(method.getReturnType())) - .append(' ') - .append(method.getName()) - .append('(') - .append(generateParameters(method.getParameters())) - .append(");") - .append(NEW_LINE); - } - final String methodList = sb1.toString(); - - // enums string with rendered enums from template - final StringBuilder sb2 = new StringBuilder(); - for (Enumeration enumeration : getType().getEnumerations()) { - final String importedName = importedName(String.class); - final String enumBody = enumTemplate.render(enumeration, importedName).body(); - sb2.append(enumBody); - } - final String enums = sb2.toString(); - - final String generatedImports = generateImports(getType().getImplements()); - - getImportedNames().put("qname", importedName(QName.class)); - final String generatedConstants = constantsTemplate.render(getType(), getImportedNames(), - this::importedName, true).body(); - - final Entry identifier = generateInstanceIdentifier(); - - final List innerClasses = new ArrayList<>(getType().getEnclosedTypes().size()); - for (GeneratedType innerClass : getType().getEnclosedTypes()) { - if (innerClass instanceof GeneratedTransferObject) { - if (((GeneratedTransferObject) innerClass).isUnionType()) { - final UnionRenderer unionRenderer = new UnionRenderer((GeneratedTransferObject) innerClass); - innerClasses.add(unionRenderer.generateAsInnerClass()); - this.putAllToImportMap(unionRenderer.getImportMap()); - } else { - final ClassRenderer classRenderer = new ClassRenderer((GeneratedTransferObject) innerClass); - innerClasses.add(classRenderer.generateAsInnerClass()); - this.putAllToImportMap(classRenderer.getImportMap()); - } - } - } - final String generatedInnerClasses = String.join("\n", innerClasses); - - return interfaceTemplate.render(getType(), enums, mainAnnotations, methodList, generatedImports, - generatedConstants, generatedInnerClasses, identifier.getKey(), identifier.getValue()).body(); - } - - private static boolean isAccessor(final MethodSignature maybeGetter) { - return maybeGetter.getName().startsWith("is") || maybeGetter.getName().startsWith("get"); - } - - /** - * Return string of annotations. - * @param annotationTypeList list of annotations - * @return String of annotations in format: - * "@"annotation - * (parameterName1=ParameterSingleValue1,...) - * - */ - private String generateAnnotations(final List annotationTypeList) { - final StringBuilder sb1 = new StringBuilder(); - for (AnnotationType annotationType : annotationTypeList) { - sb1.append('@').append(importedName(annotationType)); - if (!annotationType.getParameters().isEmpty()) { - sb1.append('('); - } - final List parameterList = new ArrayList<>(annotationType.getParameters().size()); - for (AnnotationType.Parameter parameter : annotationType.getParameters()) { - final StringBuilder sb2 = new StringBuilder(); - sb2.append(parameter.getName()).append('=').append(parameter.getSingleValue()); - parameterList.add(sb2.toString()); - } - sb1.append(String.join(",", parameterList)); - if (!annotationType.getParameters().isEmpty()) { - sb1.append(')'); - } - sb1.append(NEW_LINE); - } - return sb1.toString(); - } - - /** - * Generate default method getInstanceIdentifier. - * @return string pair of instance identifier and key parameters - */ - private Entry generateInstanceIdentifier() { - //Only tree data nodes need to generate the method. - if (null == getType().getBindingNamespaceType() - || !BindingNamespaceType.isTreeData(getType().getBindingNamespaceType()) - || !getType().getImplements().contains(BindingTypes.TREE_CHILD_NODE)) { - return new SimpleEntry<>(null, null); - } - - final Deque dataPath = new ArrayDeque<>(); - GeneratedType type = getType(); - GeneratedTypeBuilder parentTypeBuilder; - - while (type != null) { - dataPath.push(type); - importedName(type); - parentTypeBuilder = (GeneratedTypeBuilder) type.getParentTypeForBuilder(); - type = parentTypeBuilder != null ? parentTypeBuilder.toInstance() : null; - } - - dataPath.pop(); - - final StringBuilder iiBuidler = new StringBuilder(); - type = dataPath.pop(); - iiBuidler.append("InstanceIdentifier.builder(").append(type.getName()).append(".class)"); - importedName(InstanceIdentifier.class); - final List keys = new ArrayList<>(); - while (dataPath.peek() != null) { - type = dataPath.pop(); - if (type.getImplements().contains(BindingTypes.AUGMENTATION)) { - iiBuidler.append(".augmentation(").append(type.getName()).append(".class)"); - } else { - Optional method = type.getMethodDefinitions().stream().filter(m -> - m.getName().equals("getIdentifier")).findFirst(); - if (method.isPresent()) { - importedName(method.get().getReturnType()); - final String keyName = method.get().getReturnType().getName(); - final String normalizedKeyName = JavaIdentifierNormalizer.normalizeSpecificIdentifier(keyName, - JavaIdentifier.METHOD); - keys.add(new StringBuilder().append("final ").append(keyName).append(" _") - .append(normalizedKeyName).toString()); - iiBuidler.append(".child(").append(type.getFullyQualifiedName()).append(".class, _") - .append(normalizedKeyName).append(")"); - } else { - iiBuidler.append(".child(").append(type.getFullyQualifiedName()).append(".class)"); - } - } - } - iiBuidler.append(".build()"); - return new SimpleEntry<>(iiBuidler.toString(), String.join(", ", keys)); - } - - - /** - * Return list of parameters. - * @param parameters list of parameters - * @return list of parameters separated with "," - */ - private String generateImports(final List parameters) { - final List strings = new ArrayList<>(parameters.size()); - for (Type parameter : parameters) { - strings.add(importedName(parameter)); - } - - return String.join(", ", strings); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionBuilderRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionBuilderRenderer.java deleted file mode 100644 index 15862632a0..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionBuilderRenderer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import java.util.HashMap; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.unionBuilderTemplate; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; - -public class UnionBuilderRenderer extends ClassRenderer { - - public UnionBuilderRenderer(final GeneratedTransferObject type) { - super(type); - } - - protected String body() { - // list of all imported names for template - final Map importedNames = new HashMap<>(); - final Map generatedParameters = new HashMap<>(); - - importedNames.put("unsupportedOperationException", importedName(UnsupportedOperationException.class)); - for (MethodSignature methodSignature : genTO.getMethodDefinitions()) { - importedNames.put(methodSignature.getName(), importedName(methodSignature.getReturnType())); - generatedParameters.put(methodSignature.getName(), generateParameters(methodSignature.getParameters())); - } - return unionBuilderTemplate.render(genTO, getType().getName(), importedNames, generatedParameters).body(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionRenderer.java deleted file mode 100644 index 890c440780..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/UnionRenderer.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Collections2; -import java.beans.ConstructorProperties; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.unionTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil; -import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition; - -public class UnionRenderer extends ClassRenderer { - public UnionRenderer(final GeneratedTransferObject type) { - super(type); - } - - @Override - protected String generateConstructors() { - // list of all imported names for template - final Map importedNames = new HashMap<>(); - - if (isBaseEncodingImportRequired()) { - this.putToImportMap("BaseEncoding","com.google.common.io"); - } - for (GeneratedProperty finalProperty : getFinalProperties()) { - importedNames.put("constructorProperties", importedName(ConstructorProperties.class)); - importedNames.put("string", importedName(String.class)); - importedNames.put(finalProperty.getName(), importedName(finalProperty.getReturnType())); - } - - for (GeneratedProperty property : getProperties()) { - if ("char[]".equals(property.getReturnType().getName())) { - importedNames.put("constructorProperties", importedName(ConstructorProperties.class)); - importedNames.put("string", importedName(String.class)); - importedNames.put(property.getName(), importedName(property.getReturnType())); - } - } - - final StringBuilder sb = new StringBuilder(); - if (!getProperties().isEmpty()) { - for (GeneratedProperty property : getProperties()) { - sb.append(generateField(property)); - } - } - - if (getProperties().isEmpty() && !getParentProperties().isEmpty()) { - importedNames.put("superType", importedName(genTO.getSuperType())); - } - - for (GeneratedProperty parentProperty : getParentProperties()) { - importedNames.put(parentProperty.getName(), importedName(parentProperty.getReturnType())); - } - - return unionTemplate.render(getType(), importedNames, getFinalProperties(), getParentProperties(), - getProperties(), sb.toString()).body(); - } - - private boolean isBaseEncodingImportRequired() { - for (GeneratedProperty property : getFinalProperties()) { - final Type returnType = property.getReturnType(); - if (returnType instanceof GeneratedTransferObject) { - final GeneratedTransferObject returnTypeGto = (GeneratedTransferObject)returnType; - if (returnTypeGto.isTypedef() && returnTypeGto.getProperties() != null - && !returnTypeGto.getProperties().isEmpty() && returnTypeGto.getProperties().size() == 1 - && "value".equals(returnTypeGto.getProperties().get(0).getName()) - && "byte[]".equals(returnTypeGto.getProperties().get(0).getReturnType().getName())) { - return true; - } - } - } - return false; - } - - private String generateField(final GeneratedProperty generatedProperty) { - final StringBuilder sb = new StringBuilder(); - final String name = TextTemplateUtil.fieldName(generatedProperty); - sb.append("this.") - .append(name) - .append(" = source.") - .append(name); - if (!"value".equals(name) && importedName(generatedProperty.getReturnType()).contains("[]")) { - sb.append(" == null ? null : source.") - .append(name) - .append(".clone()"); - } - sb.append(";\n"); - return sb.toString(); - } - - private String generateCharArrayFieldForTypedef(final String fieldName, GeneratedTransferObject typedefType) { - Preconditions.checkState(typedefType.isTypedef(),"Not a typedef type!"); - - final StringBuilder sb = new StringBuilder(); - final List retTypeCastProperties = typedefType.getProperties(); - - if (retTypeCastProperties != null - && !retTypeCastProperties.isEmpty() && retTypeCastProperties.size() == 1 - && retTypeCastProperties.get(0).getName().equals("value")) { - - final StringBuilder sb1 = new StringBuilder(fieldName); - sb1.append(".") - .append(TextTemplateUtil.getterMethodName(retTypeCastProperties.get(0))) - .append("()"); - - sb.append(generateCharArrayField(sb1.toString(), retTypeCastProperties.get(0))); - // generated bits typedef - } else if (retTypeCastProperties != null && !retTypeCastProperties.isEmpty() - && typedefType.getBaseType() instanceof BitsTypeDefinition) { - sb.append("java.util.Arrays.toString(") - .append(fieldName) - .append(".getValue()).toCharArray();"); - - //generated typedef typedef - } else if ((retTypeCastProperties == null || retTypeCastProperties.isEmpty())) { - Preconditions.checkState(typedefType.getSuperType() != null); - - sb.append(generateCharArrayFieldForTypedef(fieldName, typedefType.getSuperType())); - } - - return sb.toString(); - } - - private String generateCharArrayField(final String fieldName, final GeneratedProperty generatedProperty) { - final StringBuilder sb = new StringBuilder(); - final Type propertyReturnType = generatedProperty.getReturnType(); - - // generated type String - if ("java.lang.String".equals(propertyReturnType.getFullyQualifiedName())) { - sb.append(fieldName).append(".toCharArray();"); - // generated type InstanceIdentifier - } else if ("org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier" - .equals(propertyReturnType.getFullyQualifiedName())) { - sb.append(fieldName).append(".toString().toCharArray();"); - //generated type binary, boolean, empty - } else if (BOOLEAN.equals(propertyReturnType)) { - sb.append(fieldName).append(".toString().toCharArray();"); - //generated type byte[] - } else if ("byte[]".equals(propertyReturnType.getName())) { - sb.append("BaseEncoding.base64().encode(").append(fieldName) - .append(").toCharArray();"); - //generated type int*, uint, decimal64 or enumeration* - } else if (propertyReturnType.getFullyQualifiedName().startsWith("java.lang") - || propertyReturnType instanceof Enumeration - || propertyReturnType.getFullyQualifiedName().startsWith("java.math") - || propertyReturnType.getFullyQualifiedName().startsWith("org.opendaylight.yangtools.yang.common")) { - sb.append(fieldName).append(".toString().toCharArray();"); - - } else if (propertyReturnType instanceof GeneratedTransferObject) { - final GeneratedTransferObject propRetTypeCast = (GeneratedTransferObject) propertyReturnType; - - // generated union type - if (propRetTypeCast.isUnionType()) { - sb.append(fieldName).append(".getValue();"); - - // generated typedef type - } else if (propRetTypeCast.isTypedef()) { - sb.append(generateCharArrayFieldForTypedef(fieldName, propRetTypeCast)); - } - // generated type - } else { - sb.append(fieldName) - .append(".getValue().toString().toCharArray();"); - } - - return sb.toString(); - } - - @Override - protected String getterMethod(final GeneratedProperty field) { - if (!"value".equals(field.getName())) { - return super.getterMethod(field); - } - - final StringBuilder sb1 = new StringBuilder(); - final String name = TextTemplateUtil.fieldName(field); - final String importedName = requireNonNull(importedName(field.getReturnType())); - sb1.append("public ") - .append(importedName) - .append(' ') - .append(TextTemplateUtil.getterMethodName(field)) - .append("() {\n"); - - final List filtered = new ArrayList<>(Collections2.filter(this.getFinalProperties(), - input -> !"value".equals(input.getName()))); - - final List strings = new ArrayList<>(filtered.size()); - - for (GeneratedProperty property : filtered) { - final Type propertyReturnType = property.getReturnType(); - //string builder for current property - final StringBuilder sb = new StringBuilder(); - sb.append("if (") - .append(TextTemplateUtil.fieldName(property)) - .append(" != null) {") - .append(TextTemplateUtil.fieldName(field)) - .append(" = ") - .append(generateCharArrayField(TextTemplateUtil.fieldName(property), property)) - .append("}\n"); - strings.add(sb); - } - - sb1.append(String.join(" else ", strings)) - .append("\n"); - - sb1.append("return ") - .append(name); - if (importedName.contains("[]")) { - sb1.append(" == null ? null : ") - .append(name) - .append(".clone()"); - } - sb1.append(";\n}\n"); - - return sb1.toString(); - } - - @Override - protected String generateInnerClassBody(GeneratedTransferObject innerClass) { - final UnionRenderer unionRenderer = new UnionRenderer(innerClass); - final String body = unionRenderer.generateAsInnerClass(); - this.putAllToImportMap(unionRenderer.getImportMap()); - return body; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/YangModuleInfoTemplateRenderer.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/YangModuleInfoTemplateRenderer.java deleted file mode 100644 index 582f815652..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/YangModuleInfoTemplateRenderer.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer.normalizeFullPackageName; -import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME; -import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.TreeMap; -import java.util.function.Function; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.modelProviderTemplate; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.txt.yangModuleInfoTemplate; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.WildcardType; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.yangtools.concepts.SemVer; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; - -public class YangModuleInfoTemplateRenderer { - - private final Module module; - private final SchemaContext ctx; - private final Map importMap = new HashMap<>(); - private final String packageName; - private final String modelBindingProviderName; - private final Function> moduleFilePathResolver; - - public YangModuleInfoTemplateRenderer(final Module module, final SchemaContext ctx, - final Function> moduleFilePathResolver) { - - Preconditions.checkArgument(module != null, "Module must not be null."); - this.module = module; - this.ctx = ctx; - this.packageName = normalizeFullPackageName(getRootPackageName(module)); - this.moduleFilePathResolver = moduleFilePathResolver; - - final StringBuilder sb = new StringBuilder(); - sb.append(packageName) - .append('.') - .append(MODEL_BINDING_PROVIDER_CLASS_NAME); - this.modelBindingProviderName = sb.toString(); - } - - protected String body() { - /** - * list of all imported names for template. - */ - final Map importedNames = new HashMap<>(); - - importedNames.put("string", importedName(String.class)); - importedNames.put("stringBuilder", importedName(StringBuilder.class)); - importedNames.put("set", importedName(Set.class)); - importedNames.put("hashSet", importedName(HashSet.class)); - importedNames.put("collections", importedName(Collections.class)); - importedNames.put("immutableSet", importedName(ImmutableSet.class)); - importedNames.put("inputStream", importedName(InputStream.class)); - importedNames.put("iOException", importedName(IOException.class)); - importedNames.put("yangModuleInfo", importedName(YangModuleInfo.class)); - importedNames.put("optional", importedName(Optional.class)); - importedNames.put("semVer", importedName(SemVer.class)); - importedNames.put("schemaSourceRepresentation", importedName(SchemaSourceRepresentation.class)); - - return yangModuleInfoTemplate.render(module, ctx, importedNames, moduleFilePathResolver).body(); - } - - /** - * Builds template. - * @return generated final template - */ - public String generateTemplate() { - final StringBuilder sb = new StringBuilder(); - /* body must be filled before imports method call */ - final String templateBody = body(); - sb.append("package ") - .append(packageName) - .append(";\n\n") - .append(imports()) - .append(templateBody); - return sb.toString(); - } - - public String generateModelProvider() { - return modelProviderTemplate.render(packageName, YangModelBindingProvider.class.getName(), YangModuleInfo.class - .getName()).body(); - } - - /** - * Walks through map of imports. - * @return string of imports for template - */ - private String imports() { - final StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : importMap.entrySet()) { - if (!getRootPackageName(module).equals(entry.getValue())) { - sb.append("import ") - .append(entry.getValue()) - .append('.') - .append(entry.getKey()) - .append(";\n"); - } - } - return sb.toString(); - } - - private String importedName(final Class cls) { - final Type inType = Types.typeForClass(cls); - putTypeIntoImports(inType); - return getExplicitType(inType); - } - - private void putTypeIntoImports(final Type type) { - final String typeName = type.getName(); - final String typePackageName = type.getPackageName(); - if (typePackageName.startsWith("java.lang") || typePackageName.isEmpty()) { - return; - } - if (!importMap.containsKey(typeName)) { - importMap.put(typeName, typePackageName); - } - if (type instanceof ParameterizedType) { - final Type[] params = ((ParameterizedType) type).getActualTypeArguments(); - if (params != null) { - for (Type param : params) { - putTypeIntoImports(param); - } - } - } - } - - private String getExplicitType(final Type type) { - final String typePackageName = type.getPackageName(); - final String typeName = type.getName(); - final String importedPackageName = importMap.get(typeName); - final StringBuilder sb; - if (typePackageName.equals(importedPackageName)) { - sb = new StringBuilder(type.getName()); - if (sb.toString().equals("Void")) { - return "void"; - } - addActualTypeParameters(sb, type); - } else { - if (type.equals(Types.voidType())) { - return "void"; - } - sb = new StringBuilder(); - if (!typePackageName.isEmpty()) { - sb.append(typePackageName) - .append('.') - .append(type.getName()); - } else { - sb.append(type.getName()); - } - addActualTypeParameters(sb, type); - } - return sb.toString(); - } - - private StringBuilder addActualTypeParameters(final StringBuilder sb, final Type type) { - if (type instanceof ParameterizedType) { - final Type[] pTypes = ((ParameterizedType) type).getActualTypeArguments(); - sb.append('<'); - sb.append(getParameters(pTypes)); - sb.append('>'); - } - return sb; - } - - private String getParameters(final Type[] ptypes) { - if (ptypes == null || ptypes.length == 0) { - return "?"; - } - final StringBuilder sb = new StringBuilder(); - int count = 0; - for (Type ptype : ptypes) { - final Type type = ptypes[count]; - String separator = ","; - if (count == (ptypes.length - 1)) { - separator = ""; - } - String wildcardParam = ""; - if (type.equals(Types.voidType())) { - sb.append("java.lang.Void").append(separator); - } else { - if (type instanceof WildcardType) { - wildcardParam = "? extends "; - } - sb.append(wildcardParam).append(getExplicitType(type)).append(separator); - count = count + 1; - } - } - return sb.toString(); - } - - public static Module getSortedQName(final Set modules, final String name) { - final TreeMap, Module> sorted = new TreeMap<>(Revision::compare); - for (Module module : modules) { - if (name.equals(module.getName())) { - sorted.put(module.getRevision(), module); - } - } - return sorted.lastEntry().getValue(); - } - - public String getModelBindingProviderName() { - return modelBindingProviderName; - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/AlphabeticallyTypeMemberComparator.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/AlphabeticallyTypeMemberComparator.java deleted file mode 100644 index 756e1121c0..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/AlphabeticallyTypeMemberComparator.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.util; - -import java.util.Comparator; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeMember; - -/** - * Alphabetically type member {@link Comparator} which provides sorting by name for type members - * (variables and methods) in generated class. - * - * @param type - */ -public class AlphabeticallyTypeMemberComparator implements Comparator { - - @Override - public int compare(T member1, T member2) { - return member1.getName().compareTo(member2.getName()); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/JavaCodePrettyPrint.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/JavaCodePrettyPrint.java deleted file mode 100644 index d0fb2e844d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/JavaCodePrettyPrint.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.util; - -import java.util.ArrayList; -import java.util.List; -import javax.annotation.RegEx; -import org.apache.commons.lang3.StringUtils; - -/** - * Pretty-print utility for generated Java code. - */ -public final class JavaCodePrettyPrint { - - // JDoc - private static final String JDOC_START = "/**"; - private static final String JDOC_PART = " *"; - private static final String JDOC_END = "*/"; - - // Comments - private static final String COMMENTS = "//"; - - // Body - private static final char START_BODY = '{'; - private static final char END_BODY = '}'; - - // Whitespaces - @RegEx - private static final String NEW_LINE_REGEX = "\\r?\\n"; - @RegEx - private static final String WS_REGEX = "\\s+"; - private static final char SPACE = ' '; - private static final char NEW_LINE = '\n'; - - // Indention - private static final int INDENT = 4; - - // Specific keywords - private static final String PACKAGE = "package"; - private static final String IMPORT = "import"; - - // Line - private static final char END_LINE = ';'; - private static final char AT = '@'; - - private JavaCodePrettyPrint() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Pretty-print generated Java code. - * - * @param unformedJavaFile - * - unformed Java file from generator - * @return formed Java file - */ - public static String perform(final String unformedJavaFile) { - final StringBuilder sb = new StringBuilder(); - String[] splittedByNewLine = unformedJavaFile.split(NEW_LINE_REGEX); - // remove excessive whitespaces - splittedByNewLine = phaseOne(splittedByNewLine); - // merge or divide lines which need it && setup base new lines at the - // end of lines - splittedByNewLine = phaseTwo(splittedByNewLine); - // fix indents - splittedByNewLine = phaseThree(splittedByNewLine); - - for (final String line : splittedByNewLine) { - sb.append(line); - } - return sb.toString(); - } - - /** - * Set up indents. - * - * @param splittedByNewLine - * - cleaned and merged/divided lines - * @return fixed intents in lines - */ - private static String[] phaseThree(final String[] splittedByNewLine) { - int indentCount = 0; - final List lines = new ArrayList<>(); - for (int i = 0; i < splittedByNewLine.length; i++) { - final StringBuilder sb = new StringBuilder(); - indentCount = lineIndent(sb, indentCount, splittedByNewLine[i]); - sb.append(splittedByNewLine[i]); - if ((splittedByNewLine[i].contains(String.valueOf(END_BODY)) - || splittedByNewLine[i].contains(String.valueOf(END_LINE))) && indentCount == 1) { - sb.append(NEW_LINE); - } - lines.add(sb.toString()); - } - - return lines.toArray(new String[lines.size()]); - } - - private static int lineIndent(final StringBuilder sb, final int indentCount, final String line) { - int newIndentCount = indentCount; - if (line.contains(String.valueOf(END_BODY)) && !line.startsWith(JDOC_PART)) { - newIndentCount--; - } - for (int i = 0; i < (newIndentCount * INDENT); i++) { - sb.append(SPACE); - } - - if (line.contains(String.valueOf(START_BODY)) && !line.startsWith(JDOC_PART)) { - newIndentCount++; - } - - return newIndentCount; - } - - /** - * Join or split lines if necessary. - * - * @param splittedByNewLine - * - cleaned lines from whitespaces around them - * @return fixed lines - */ - private static String[] phaseTwo(final String[] splittedByNewLine) { - final List fixedLines = new ArrayList<>(); - - // prepare package part - if (splittedByNewLine[0].startsWith(PACKAGE)) { - fixedLines.add(new StringBuilder(splittedByNewLine[0]).append(NEW_LINE).append(NEW_LINE).toString()); - } - - // prepare imports - int importsEndAt; - if (splittedByNewLine[1].startsWith(IMPORT)) { - importsEndAt = 1; - for (int i = 1; i < splittedByNewLine.length - 1; i++) { - if (!splittedByNewLine[i + 1].startsWith(IMPORT)) { - fixedLines.add(new StringBuilder( - splittedByNewLine[i]).append(NEW_LINE).append(NEW_LINE).toString()); - importsEndAt = i; - break; - } else { - fixedLines.add(new StringBuilder(splittedByNewLine[i]).append(NEW_LINE).toString()); - } - } - } else { - importsEndAt = 0; - } - - // prepare class - StringBuilder sbLineClass = new StringBuilder(); - int classStartEnd = 0; - for (int i = importsEndAt + 1; i < splittedByNewLine.length; i++) { - i = appendJDoc(splittedByNewLine, fixedLines, i); - if (!splittedByNewLine[i].contains(String.valueOf(START_BODY))) { - sbLineClass.append(splittedByNewLine[i]).append(SPACE); - } else { - fixedLines.add(sbLineClass.append(splittedByNewLine[i]).append(NEW_LINE).append(NEW_LINE).toString()); - classStartEnd = i + 1; - break; - } - } - - for (int i = classStartEnd; i < splittedByNewLine.length; i++) { - i = appendJDoc(splittedByNewLine, fixedLines, i); - if (!splittedByNewLine[i].startsWith(COMMENTS) - && !splittedByNewLine[i].endsWith(String.valueOf(END_LINE)) - && !splittedByNewLine[i].endsWith(String.valueOf(START_BODY)) - && !splittedByNewLine[i].endsWith(String.valueOf(END_BODY)) - && !splittedByNewLine[i].startsWith(String.valueOf(AT))) { - sbLineClass = new StringBuilder(); - for (int j = i; j < splittedByNewLine.length; j++) { - if (!splittedByNewLine[j].contains(String.valueOf(START_BODY)) - && !splittedByNewLine[j].contains(String.valueOf(END_LINE))) { - final String str = splittedByNewLine[j]; - sbLineClass.append(str).append(SPACE); - } else { - fixedLines.add(sbLineClass.append(splittedByNewLine[j]).append(NEW_LINE).toString()); - i = j; - break; - } - } - continue; - } - final String splStri = splittedByNewLine[i]; - final String stringSB = String.valueOf(START_BODY); - final String stringEB = String.valueOf(END_BODY); - if (splStri.contains(stringSB) && splStri.endsWith(stringEB)) { - final StringBuilder sb = new StringBuilder(); - for (int j = 0; j < splittedByNewLine[i].length(); j++) { - if (splittedByNewLine[i].charAt(j) == END_BODY) { - sb.append(NEW_LINE); - } - sb.append(splittedByNewLine[i].charAt(j)); - if (splittedByNewLine[i].charAt(j) == START_BODY) { - sb.append(NEW_LINE); - } - } - final String[] split = sb.toString().split(NEW_LINE_REGEX); - for (final String s : split) { - fixedLines.add(new StringBuilder(s).append(NEW_LINE).toString()); - } - continue; - } - fixedLines.add(new StringBuilder(splittedByNewLine[i]).append(NEW_LINE).toString()); - } - - return fixedLines.toArray(new String[fixedLines.size()]); - } - - private static int appendJDoc(final String[] splittedByNewLine, final List fixedLines, int cur) { - if (splittedByNewLine[cur].contains(JDOC_START)) { - fixedLines.add(new StringBuilder(splittedByNewLine[cur]).append(NEW_LINE).toString()); - for (int next = cur + 1; next < splittedByNewLine.length - 1; next++) { - fixedLines.add( - new StringBuilder().append(SPACE).append(splittedByNewLine[next]).append(NEW_LINE).toString()); - if (splittedByNewLine[next].contains(JDOC_END)) { - cur = next + 1; - break; - } - } - } - return cur; - } - - /** - * Remove empty lines and whitespaces adjacent lines. - * - * @param splittedByNewLine - * - lines with whitespaces around them - * @return cleaned lines from whitespaces - */ - private static String[] phaseOne(final String[] splittedByNewLine) { - final List linesWithoutWhitespaces = new ArrayList<>(); - for (final String line : splittedByNewLine) { - if (!StringUtils.isBlank(line)) { - int lineStart = 0; - for (int i = 0; i < line.length(); i++) { - if (StringUtils.isWhitespace(String.valueOf(line.charAt(i)))) { - lineStart++; - } else { - break; - } - } - int lineEnd = line.length() - 1; - while (StringUtils.isWhitespace(String.valueOf(line.charAt(lineEnd)))) { - lineEnd--; - } - linesWithoutWhitespaces.add(line.substring(lineStart, lineEnd + 1)); - } - } - return linesWithoutWhitespaces.toArray(new String[linesWithoutWhitespaces.size()]); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtil.java b/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtil.java deleted file mode 100755 index fe357898d2..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtil.java +++ /dev/null @@ -1,593 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.java.api.generator.util; - -import static java.util.Objects.requireNonNull; - -import com.google.common.base.CharMatcher; -import com.google.common.base.Preconditions; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.Optional; -import java.util.StringTokenizer; -import java.util.function.Function; -import java.util.regex.Pattern; - -import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier; -import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeComment; -import org.opendaylight.mdsal.binding.javav2.model.api.TypeMember; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition.Multiple; -import org.opendaylight.mdsal.binding.javav2.model.api.YangSourceDefinition.Single; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType; -import org.opendaylight.yangtools.concepts.Builder; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.model.api.DocumentedNode; -import org.opendaylight.yangtools.yang.model.api.ListSchemaNode; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.api.YangStmtMapping; -import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; -import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; -import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement; -import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter; - -public final class TextTemplateUtil { - - public static final String DOT = "."; - - private static final char NEW_LINE = '\n'; - private static final String UNDERSCORE = "_"; - private static final CharMatcher NEWLINE_OR_TAB = CharMatcher.anyOf("\n\t"); - private static final CharMatcher NL_MATCHER = CharMatcher.is(NEW_LINE); - private static final CharMatcher AMP_MATCHER = CharMatcher.is('&'); - private static final CharMatcher GT_MATCHER = CharMatcher.is('>'); - private static final CharMatcher LT_MATCHER = CharMatcher.is('<'); - private static final Splitter NL_SPLITTER = Splitter.on(NL_MATCHER); - private static final Splitter BSDOT_SPLITTER = Splitter.on("."); - - private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL); - private static final Pattern MULTIPLE_SPACES_PATTERN = Pattern.compile(" +"); - - private static DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder() - .addIgnoredStatement(YangStmtMapping.CONTACT) - .addIgnoredStatement(YangStmtMapping.DESCRIPTION) - .addIgnoredStatement(YangStmtMapping.REFERENCE) - .addIgnoredStatement(YangStmtMapping.ORGANIZATION) - .build(); - - private TextTemplateUtil() { - throw new UnsupportedOperationException("Util class"); - } - - /** - * Makes start of getter name LowerCase. - * - * @param str getter name without prefix - * @return getter name starting in LowerCase - */ - public static String toFirstLower(final String str) { - return str != null && str.length() != 0 ? Character.isLowerCase(str.charAt(0)) ? str : str.length() == 1 - ? str.toLowerCase() : str.substring(0, 1).toLowerCase() + str.substring(1) : str; - } - - /** - * Wraps text as documentation, used in enum description. - * - * @param text text for wrapping - * @return wrapped text - */ - public static String wrapToDocumentation(final String text) { - if (text.isEmpty()) { - return ""; - } - final StringBuilder sb = new StringBuilder(); - sb.append("/**"); - sb.append(NEW_LINE); - for (final String t : NL_SPLITTER.split(text)) { - if (!t.isEmpty()) { - sb.append(" * "); - sb.append(t); - sb.append(NEW_LINE); - } - } - sb.append(" */"); - sb.append(NEW_LINE); - return sb.toString(); - } - - /** - * Returns formatted Javadoc, based on type. - * - * @param typeName given type name - * @return formatted Javadoc, based on type - */ - public static String formatDataForJavaDocBuilder(final String typeName) { - final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Class that builds {@link ") - .append(typeName) - .append("} instances.") - .append(NEW_LINE) - .append("@see ") - .append(typeName); - return stringBuilder.toString(); - } - - /** - * Returns formatted Javadoc with possible additional comment, based on type. - * - * @param type given type - * @param additionalComment additional comment to format - * @return formatted Javadoc with possible additional comment, based on type - */ - public static String formatDataForJavaDoc(final GeneratedType type, final String additionalComment) { - final StringBuilder javaDoc = new StringBuilder(); - javaDoc.append(formatDataForJavaDoc(type)).append(additionalComment); - return javaDoc.toString(); - } - - /** - * Returns formatted type description. - * - * @param type given type - * @return formatted type description - */ - public static String formatDataForJavaDoc(final GeneratedType type) { - final StringBuilder javaDoc = new StringBuilder(); - final TypeComment comment = type.getComment(); - if (comment != null) { - javaDoc.append(comment.getJavadoc()) - .append(NEW_LINE) - .append(NEW_LINE) - .append(NEW_LINE); - } - - appendSnippet(javaDoc, type); - - return javaDoc.toString(); - } - - private static String formatDataForJavaDoc(final TypeMember type, final String additionalComment) { - final StringBuilder javaDoc = new StringBuilder(); - if (type.getComment() != null && !type.getComment().isEmpty()) { - javaDoc.append(formatToParagraph(type.getComment(), 0)) - .append(NEW_LINE) - .append(NEW_LINE) - .append(NEW_LINE); - } - javaDoc.append(additionalComment); - return wrapToDocumentation(javaDoc.toString()); - } - - private static void appendSnippet(final StringBuilder sb, final GeneratedType type) { - Optional optDef = type.getYangSourceDefinition(); - if (optDef.isPresent()) { - YangSourceDefinition def = optDef.get(); - sb.append(NEW_LINE); - - if (def instanceof Single) { - DocumentedNode node = ((Single) def).getNode(); - sb.append("

    \n") - .append("This class represents the following YANG schema fragment defined in module ") - .append(def.getModule().argument()).append("\n") - .append("

    \n");
    -                appendYangSnippet(sb, def.getModule(), ((EffectiveStatement) node).getDeclared());
    -                sb.append("
    "); - - if (node instanceof SchemaNode) { - sb.append("The schema path to identify an instance is\n") - .append("") - .append(formatSchemaPath(def.getModule().argument(), ((SchemaNode) node).getPath() - .getPathFromRoot())) - .append("\n"); - - if (hasBuilderClass(type)) { - final String builderName = new StringBuilder() - .append(((GeneratedTypeForBuilder) type).getPackageNameForBuilder()) - .append(".").append(type.getName()).append("Builder").toString(); - - sb.append("\n

    To create instances of this class use {@link ").append(builderName) - .append("}.\n") - .append("@see ").append(builderName).append('\n'); - if (node instanceof ListSchemaNode) { - final StringBuilder linkToKeyClass = new StringBuilder(); - - final String[] namespace = Iterables.toArray( - BSDOT_SPLITTER.split(type.getFullyQualifiedName()), String.class); - final String className = namespace[namespace.length - 1]; - - linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType( - ((GeneratedTypeForBuilder) type).getBasePackageName(), (SchemaNode) node, - BindingNamespaceType.Key)).append('.').append(className).append("Key"); - - List keyDef = ((ListSchemaNode) node).getKeyDefinition(); - if (keyDef != null && !keyDef.isEmpty()) { - sb.append("@see ").append(linkToKeyClass); - } - sb.append('\n'); - } - } - } - } else if (def instanceof Multiple) { - sb.append("

    \n");
    -                for (SchemaNode node : ((Multiple) def).getNodes()) {
    -                    appendYangSnippet(sb, def.getModule(), ((EffectiveStatement) node).getDeclared());
    -                }
    -                sb.append("
    \n"); - } - } - } - - private static void appendYangSnippet(StringBuilder sb, ModuleEffectiveStatement module, - DeclaredStatement stmt) { - for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) { - sb.append(encodeAngleBrackets(encodeJavadocSymbols(str))); - } - } - - public static boolean hasBuilderClass(final GeneratedType type) { - return type instanceof GeneratedTypeForBuilder; - } - - public static String formatSchemaPath(final String moduleName, final Iterable schemaPath) { - final StringBuilder sb = new StringBuilder(); - sb.append(moduleName); - - QName currentElement = Iterables.getFirst(schemaPath, null); - for (final QName pathElement : schemaPath) { - sb.append('/'); - if (!currentElement.getNamespace().equals(pathElement.getNamespace())) { - currentElement = pathElement; - sb.append(pathElement); - } else { - sb.append(pathElement.getLocalName()); - } - } - return sb.toString(); - } - - /** - * Returns properties names in formatted string. - * - * @param properties list of given properties - * @return properties names in formatted string - */ - //FIXME: this needs further clarification in future patch - public static String valueForBits(final List properties) { - return String.join(",", Lists.transform(properties, TextTemplateUtil::fieldName)); - } - - /** - * Returns parameter name, based on given Type. - * - * @param returnType given type - * @param paramName parameter name - * @return parameter name, based on given Type - */ - public static String paramValue(final Type returnType, final String paramName) { - return returnType instanceof ConcreteType ? paramName : paramName + ".getValue()"; - } - - /** - * Template method which generates JAVA comments. InterfaceTemplate - * - * @param comment comment string with the comment for whole JAVA class - * @return string with comment in JAVA format - */ - public static String asJavadoc(final String comment) { - return comment == null ? "" : wrapToDocumentation(formatToParagraph(comment.trim(), 0)); - } - - /** - * Returns related Javadoc. - * - * @param methodSignature method signature - * @return related Javadoc - */ - public static String getJavaDocForInterface(final MethodSignature methodSignature) { - if (methodSignature.getReturnType() == Types.VOID) { - return ""; - } - final StringBuilder javaDoc = new StringBuilder(); - javaDoc.append("@return ") - .append(asCode(methodSignature.getReturnType().getFullyQualifiedName())) - .append(" ") - .append(asCode(propertyNameFromGetter(methodSignature))) - .append(", or ") - .append(asCode("null")) - .append(" if not present"); - return formatDataForJavaDoc(methodSignature, javaDoc.toString()); - } - - private static String asCode(final String text) { - return "" + text + ""; - } - - /** - * Encodes angle brackets in yang statement description. - * - * @param description description of a yang statement which is used to generate javadoc comments - * @return string with encoded angle brackets - */ - public static String encodeAngleBrackets(String description) { - if (description != null) { - description = LT_MATCHER.replaceFrom(description, "<"); - description = GT_MATCHER.replaceFrom(description, ">"); - } - return description; - } - - /** - * Returns collection of properties as formatted String. - * - * @param properties list of given properties - * @return generated properties as formatted String - */ - public static String propsAsArgs(final Iterable properties) { - return String.join(",", Iterables.transform(properties, prop -> "\"" + prop.getName() + "\"")); - } - - /** - * Returns properties as formatted String. - * - * @param properties list of given properties - * @param booleanName Java Boolean type name - * @return Properties as formatted String - */ - public static String propsAsList(final Iterable properties, final String booleanName) { - return String.join(",", Iterables.transform(properties, - prop -> "properties.get(i++).equals(defaultValue) ? " + booleanName + ".TRUE : null")); - } - - /** - * Extracts available restrictions from given type. - * - * @param currentType given type - * @return restrictions from given type - */ - public static Restrictions getRestrictions(final Type currentType) { - Restrictions restrictions = null; - if (currentType instanceof ConcreteType) { - restrictions = ((ConcreteType) currentType).getRestrictions(); - } else if (currentType instanceof GeneratedTransferObject) { - restrictions = ((GeneratedTransferObject) currentType).getRestrictions(); - } - return restrictions; - } - - /** - * sets fieldname according to property for return type. - * method(type fieldname) - * - * @param property type from getter - * @return underscored string form - */ - public static String fieldName(final GeneratedProperty property) { - final String name = requireNonNull(property.getName()); - return UNDERSCORE.concat(name); - } - - /** - * Template method which generates sequence of the names of the class attributes. - * - * @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 - */ - public static String asArguments(final List parameters) { - return String.join(", ", Lists.transform(parameters, TextTemplateUtil::fieldName)); - } - - /** - * Helper method for building getter. - * - * @param field property name - * @return getter for property - */ - public static String getterMethodName(final GeneratedProperty field) { - final Type type = requireNonNull(field.getReturnType()); - final String name = requireNonNull(field.getName()); - final String prefix = Types.BOOLEAN.equals(type) ? "is" : "get"; - return prefix.concat(toFirstUpper(name)); - } - - /** - * Returns built setter method body from input parameters. - * - * @param field generated property - * @param typeName type name - * @param returnTypeName return type name - * @return built setter method body - */ - public static String setterMethod(final GeneratedProperty field, final String typeName, final String - returnTypeName) { - final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("public ") - .append(typeName) - .append(" set") - .append(toFirstUpper(field.getName())) - .append('(') - .append(returnTypeName) - .append(" value) {\n this.") - .append(fieldName(field)) - .append(" = value;\n return this;\n}\n"); - return stringBuilder.toString(); - } - - /** - * Returns simple name of underlying class. - * - * @return Simple name of underlying class - */ - public static String getSimpleNameForBuilder() { - return Builder.class.getSimpleName(); - } - - /** - * Makes start of getter name uppercase. - * - * @param str getter name without prefix - * @return getter name starting in uppercase - */ - public static String toFirstUpper(final String str) { - return str != null && str.length() != 0 ? Character.isUpperCase(str.charAt(0)) ? str : str.length() == 1 - ? str.toUpperCase() : str.substring(0, 1).toUpperCase() + str.substring(1) : str; - } - - /** - * Cuts prefix from getter name. - * - * @param getter getter name - * @return getter name without prefix - */ - public static String propertyNameFromGetter(final MethodSignature getter) { - final String name = requireNonNull(getter.getName()); - int prefix; - if (name.startsWith("is")) { - prefix = 2; - } else if (name.startsWith("get")) { - prefix = 3; - } else { - prefix = 0; - } - return toFirstLower(name.substring(prefix)); - } - - /** - * Returns list of properties as formatted String. - * - * @param properties input list of generated properties - * @return formatted property list as String - */ - public static String getPropertyList(final List properties) { - return String.join(", ", Lists.transform(properties, prop -> "base." + getterMethodName(prop) + "()")); - } - - /** - * util method for unionTemplateBuilderTemplate. - * - * @return string with clarification for javadoc - */ - public static String getClarification() { - final StringBuilder clarification = new StringBuilder(); - clarification.append("The purpose of generated class in src/main/java for Union types is to create new " - + "instances of unions from a string representation.\n") - .append("In some cases it is very difficult to automate it since there can be unions such as (uint32 " - + "- uint16), or (string - uint32).\n") - .append("\n") - .append("The reason behind putting it under src/main/java is:\n") - .append("This class is generated in form of a stub and needs to be finished by the user. This class " - + "is generated only once to prevent\n") - .append("loss of user code.\n") - .append("\n"); - return clarification.toString(); - } - - /** - * Returns source path as String. - * - * @param module module - * @param moduleFilePathResolver function module to module file path - * @return formatted String source path - */ - public static String getSourcePath(final Module module, final Function> - moduleFilePathResolver) { - final Optional moduleFilePath = moduleFilePathResolver.apply(module); - Preconditions.checkArgument(moduleFilePath.isPresent(), "Module file path for %s is not present", module); - - return moduleFilePath.get(); - } - - /** - * Util method for unionTemplateBuilderTemplate. - * - * @param modifier enum representing Java access modifier - * @return needed access modifier - */ - public static String getAccessModifier(final AccessModifier modifier) { - switch (modifier) { - case PUBLIC: - return "public "; - case PROTECTED: - return "protected "; - case PRIVATE: - return "private "; - default: - return ""; - } - } - - /** - * Return formatted description. - * @param text Content of tag description - * @param nextLineIndent Number of spaces from left side default is 12 - * @return formatted description - */ - private static String formatToParagraph(final String text, final int nextLineIndent) { - if (Strings.isNullOrEmpty(text)) { - return ""; - } - boolean isFirstElementOnNewLineEmptyChar = false; - final StringBuilder sb = new StringBuilder(); - final StringBuilder lineBuilder = new StringBuilder(); - final String lineIndent = Strings.repeat(" ", nextLineIndent); - final String textToFormat = NEWLINE_OR_TAB.removeFrom(encodeJavadocSymbols(text)); - final String formattedText = MULTIPLE_SPACES_PATTERN.matcher(textToFormat).replaceAll(" "); - final StringTokenizer tokenizer = new StringTokenizer(formattedText, " ", true); - - while (tokenizer.hasMoreElements()) { - final String nextElement = tokenizer.nextElement().toString(); - - if (lineBuilder.length() + nextElement.length() > 80) { - // Trim trailing whitespace - for (int i = lineBuilder.length() - 1; i >= 0 && lineBuilder.charAt(i) != ' '; --i) { - lineBuilder.setLength(i); - } - // Trim leading whitespace - while (lineBuilder.charAt(0) == ' ') { - lineBuilder.deleteCharAt(0); - } - sb.append(lineBuilder).append('\n'); - lineBuilder.setLength(0); - - if (nextLineIndent > 0) { - sb.append(lineIndent); - } - - if (" ".equals(nextElement)) { - isFirstElementOnNewLineEmptyChar = true; - } - } - if (isFirstElementOnNewLineEmptyChar) { - isFirstElementOnNewLineEmptyChar = false; - } else { - lineBuilder.append(nextElement); - } - } - return sb.append(lineBuilder).append('\n').toString(); - } - - private static String encodeJavadocSymbols(final String description) { - return Strings.isNullOrEmpty(description) ? description - : AMP_MATCHER.replaceFrom(TAIL_COMMENT_PATTERN.matcher(description).replaceAll("*/"), "&"); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderConstructorHelperTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderConstructorHelperTemplate.scala.txt deleted file mode 100644 index bb62f71cc6..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderConstructorHelperTemplate.scala.txt +++ /dev/null @@ -1,33 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getterMethodName -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty - -@(allProps: List[GeneratedProperty], keyProps: List[GeneratedProperty], importedNames: Map[String, String], -keyPropsList: String) -@if(keyProps != null) { -if (base.getIdentifier() == null) { - this._identifier = new @{importedNames.get("keyTypeConstructor")}( - @{keyPropsList} - ); - @for(field <- keyProps) { - this.@{fieldName(field)} = base. - @{getterMethodName(field)}(); - } -} @{"else"} { - this._identifier = base.getIdentifier(); - @for(field <- keyProps) { - this.@{fieldName(field)} = _identifier.@{getterMethodName(field)}(); - } -} -} -@for(field <- allProps) { - this.@{fieldName(field)} = base.@{getterMethodName(field)}(); -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderTemplate.scala.txt deleted file mode 100755 index af001c9e61..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/builderTemplate.scala.txt +++ /dev/null @@ -1,547 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import java.util.List -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.formatDataForJavaDocBuilder -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getSimpleNameForBuilder -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getterMethodName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getRestrictions -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.propertyNameFromGetter -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.toFirstUpper -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.wrapToDocumentation -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.BuilderRenderer.getAllIfcs -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.BuilderRenderer.hasImplementsFromUses -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.BuilderRenderer.toListOfNames -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.AbstractRangeGenerator -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.LengthGenerator -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping -@import org.opendaylight.mdsal.binding.javav2.generator.util.Types -@import org.opendaylight.mdsal.binding.javav2.model.api.ConcreteType -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty -@import org.opendaylight.mdsal.binding.javav2.model.api.Type -@import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType -@import org.opendaylight.yangtools.concepts.Builder - -@(genType: GeneratedType, properties: Set[GeneratedProperty], importedNames: Map[String, String], -ImportedNamesWithProperties: Map[GeneratedProperty, String], augmentField: GeneratedProperty, copyConstructorHelper: String, -getterMethods: List[String], parentTypeForBuilderName: String, childTreeNode: Boolean, childTreeNodeIdent: Boolean, -keyTypeName: String, instantiable: Boolean, constants: String) -@if(genType != null) { -@{wrapToDocumentation(formatDataForJavaDocBuilder(importedNames.get("genType")))} -public class @{genType.getName}Builder implements @{getSimpleNameForBuilder} <@{importedNames.get("genType")}> { - - @generateFields(false) - - @{constants} - - @generateAugmentField(false) - - @generateConstructorsFromIfcs() - - @generateCopyConstructor(false) - - @generateMethodFieldsFrom() - - @generateGetters(false) - - @generateSetters() - - @@Override - public @{genType.getName} build() { - return new @{genType.getName}Impl(this); - } - - private static final class @{genType.getName}Impl implements @{genType.getName} { - @if(instantiable) { - @implementedInterfaceGetter() - } - - @generateFields(true) - - @generateAugmentField(true) - - @generateCopyConstructor(true) - - @generateGetters(true) - - @generateHashCode() - - @generateEquals() - - @generateToString() - - @generateImplementedMethods() - } -} -} - -@** - * Template method which generates class attributes. - * - * @param isFinal value which specify whether field is|isn't final - * @param genType is genType - * @return string with class attributes and their types - *@ -@generateFields(isFinal: Boolean) = { - @if(ImportedNamesWithProperties != null) { - @for((key, value) <- ImportedNamesWithProperties) { - private @if(isFinal) { final} - @{value} @{fieldName(key)}; - } - } -} - -@** - * Template method which generates class attributes. - * - * @param boolean value which specify whether field is|isn't final - * @return string with class attributes and their types - *@ -@generateAugmentField(isPrivate: Boolean) = { - @if(augmentField != null) { - @if(isPrivate) {private } - @{importedNames.get("map")}<@{importedNames.get("class")}, - @{importedNames.get("augmentFieldReturnType")}> @{augmentField.getName} = @{importedNames.get("collections")}.emptyMap(); - } -} - -@implementedInterfaceGetter() = { - @@Override - public @{importedNames.get("class")}<@{importedNames.get("genType")}> implementedInterface() { - return @{importedNames.get("genType")}.class; - } -} - -@** - * Generate default constructor and constructor for every implemented interface from uses statements. - *@ -@generateConstructorsFromIfcs() = { - public @{genType.getName}Builder() { - } - @if(genType.isInstanceOf[GeneratedType] && !genType.isInstanceOf[GeneratedTransferObject]) { - @for(impl <- genType.asInstanceOf[GeneratedType].getImplements) { - @generateConstructorFromIfc(impl) - } - } -} - -@generateMethodFieldsFrom() = { - @if(genType.isInstanceOf[GeneratedType] && genType.isInstanceOf[GeneratedTypeForBuilder] - && !genType.isInstanceOf[GeneratedTransferObject]) { - @if(hasImplementsFromUses(genType.asInstanceOf[GeneratedType])) { - /** - * Set fields from given grouping argument. Valid argument is instance of one of following types: - *
      - @for(impl <- getAllIfcs(genType.asInstanceOf[GeneratedType])) { - *
    • @{impl.getFullyQualifiedName}
    • - } - *
    - * - * @@param arg grouping object - * @@throws IllegalArgumentException if given argument is none of valid types - */ - - public void fieldsFrom(@{importedNames.get("treeNode")} arg) { - boolean isValidArg = false; - @for(impl <- getAllIfcs(genType.asInstanceOf[GeneratedType])) { - @if(impl.isInstanceOf[GeneratedType] && impl.isInstanceOf[GeneratedTypeForBuilder] - && !impl.asInstanceOf[GeneratedType].getMethodDefinitions.isEmpty) { - if (arg instanceof @{impl.asInstanceOf[GeneratedType].getFullyQualifiedName}) { - @if(impl.isInstanceOf[GeneratedType] && impl.isInstanceOf[GeneratedTypeForBuilder] - && !impl.isInstanceOf[GeneratedTransferObject]) { - @for(getter <- impl.asInstanceOf[GeneratedType].getMethodDefinitions) { - this._@{propertyNameFromGetter(getter)} = ((@{impl.asInstanceOf[GeneratedType].getFullyQualifiedName})arg).@{getter.getName}(); - } - } - isValidArg = true; - } - } - } - - @{importedNames.get("codeHelpers")}.validValue(isValidArg, arg, "@{toListOfNames(getAllIfcs(genType.asInstanceOf[GeneratedType]))}"); - } - } - } -} - -@** - * Generate constructor with argument of given type. - *@ -@generateConstructorFromIfc(impl: Type) = { - @if(impl.isInstanceOf[GeneratedType] && impl.isInstanceOf[GeneratedTypeForBuilder]) { - @if(!impl.asInstanceOf[GeneratedType].getMethodDefinitions.isEmpty) { - public @{genType.getName}Builder( - @{impl.getFullyQualifiedName} arg) { - @{printConstructorPropertySetter(impl)} - } - } - @for(implTypeImplement <- impl.asInstanceOf[GeneratedType].getImplements) { - @generateConstructorFromIfc(implTypeImplement) - } - } -} - -@printConstructorPropertySetter(implementedIfc: Type) = { - @if(implementedIfc.isInstanceOf[GeneratedType] && !implementedIfc.isInstanceOf[GeneratedTransferObject]) { - @for(getter <- implementedIfc.asInstanceOf[GeneratedType].getMethodDefinitions) { - this._@{propertyNameFromGetter(getter)} = arg.@{getter.getName}(); - } - @for(impl <- implementedIfc.asInstanceOf[GeneratedType].getImplements) { - @{printConstructorPropertySetter(impl)} - } - } -} - -@generateImplType() = { -@defining(genType.getName + "Impl") {typeImpl => @typeImpl} -} - -@generateBuilderType() = { -@defining(genType.getName + "Builder") {typeBuilder => @typeBuilder} -} - -@generateInnerBuilderType() = { -@defining("(" + genType.getName + "Builder base)") {typeInnerBuilder => @typeInnerBuilder} -} - -@generateInnerType() = { -@defining("(" + genType.getName + " base)") {innerType => @innerType} -} - -@generateCopyConstructor(impl: Boolean) = { - @if(impl) {private} else {public} - @if(impl) {@generateImplType()} else {@generateBuilderType()} - @if(impl) {@generateInnerBuilderType()} else {@generateInnerType()} - { - @{copyConstructorHelper} - @if(augmentField != null) { - @if(impl) { - switch (base.@{augmentField.getName}.size()) { - case 0: - this.@{augmentField.getName} = @{importedNames.get("collections")}.emptyMap(); - break; - case 1: - final @{importedNames.get("map")}.Entry<@{importedNames.get("class")}, @{importedNames.get("augmentFieldReturnType")}> e = base.@{augmentField.getName}.entrySet().iterator().next(); - this.@{augmentField.getName} = @{importedNames.get("collections")}.<@{importedNames.get("class")}, @{importedNames.get("augmentFieldReturnType")}> singletonMap(e.getKey(), e.getValue()); - break; - default : - this.@{augmentField.getName} = new @{importedNames.get("hashMap")}<>(base.@{augmentField.getName}); - } - } else { - if (base instanceof @{genType.getName}Impl) { - @{genType.getName}Impl impl = (@{genType.getName}Impl) base; - if (!impl.@{augmentField.getName}.isEmpty()) { - this.@{augmentField.getName} = new @{importedNames.get("hashMap")}<>(impl.@{augmentField.getName}); - } - } @{"else"} if (base instanceof @{importedNames.get("augmentationHolder")}) { - @@SuppressWarnings("unchecked") - @{importedNames.get("augmentationHolder")}<@{importedNames.get("genType")}> casted =(@{importedNames.get("augmentationHolder")}<@{importedNames.get("genType")}>) base; - if (!casted.augmentations().isEmpty()) { - this.@{augmentField.getName} = new @{importedNames.get("hashMap")}<>(casted.augmentations()); - } - } - } - } - } -} - -@generateSetters() = { - @for(field <- properties) { - @if(field.getReturnType.isInstanceOf[ParameterizedType] - && field.getReturnType.asInstanceOf[ParameterizedType].getRawType.equals(Types.typeForClass(classOf[List[_]]))) { - @generateSetter(field, field.getReturnType.asInstanceOf[ParameterizedType].getActualTypeArguments()(0), true) - } else { - @generateSetter(field, field.getReturnType, false) - } - } - - @if(augmentField != null) { - public @{genType.getName}Builder add@{toFirstUpper(augmentField.getName)}(@{importedNames.get("class")} augmentationType, @{importedNames.get("augmentFieldReturnType")} augmentation) { - if (augmentation == null) { - return remove@{toFirstUpper(augmentField.getName)}(augmentationType); - } - - if (!(this.@{augmentField.getName} instanceof @{importedNames.get("hashMap")})) { - this.@{augmentField.getName} = new @{importedNames.get("hashMap")}<>(); - } - - this.@{augmentField.getName}.put(augmentationType, augmentation); - return this; - } - - public @{genType.getName}Builder remove@{toFirstUpper(augmentField.getName)} - (@{importedNames.get("class")} augmentationType) { - if (this.@{augmentField.getName} instanceof @{importedNames.get("hashMap")}) { - this.@{augmentField.getName}.remove(augmentationType); - } - return this; - } - } -} - -@generateSetter(field: GeneratedProperty, actualType: Type, isList: Boolean) = { - @if(!actualType.isInstanceOf[GeneratedType] && getRestrictions(actualType) != null) { - @if(getRestrictions(actualType).getRangeConstraint.isPresent) { - @{AbstractRangeGenerator.forType(actualType).generateRangeChecker(toFirstUpper(field.getName), - getRestrictions(actualType).getRangeConstraint.get)} - } - @if(getRestrictions(actualType).getLengthConstraint.isPresent) { - @{LengthGenerator.generateLengthChecker(fieldName(field), actualType, - getRestrictions(actualType).getLengthConstraint.get)} - } - } - - @if(isList) { - public @{genType.getName}Builder set@{toFirstUpper(field.getName)}(final @{ImportedNamesWithProperties.get(field)} values) { - @if(!actualType.isInstanceOf[GeneratedType] && getRestrictions(actualType) != null) { - if (values != null) { - for (@{actualType.getFullyQualifiedName} value : values) { - @checkArgument(field, actualType) - } - } - } - this.@{fieldName(field)} = values; - return this; - } - - @generateListMethods(field, actualType) - } else { - public @{genType.getName}Builder set@{toFirstUpper(field.getName)}(final @{ImportedNamesWithProperties.get(field)} value) { - @if(!actualType.isInstanceOf[GeneratedType] && getRestrictions(actualType) != null) { - if (value != null) { - @checkArgument(field, actualType) - } - } - this.@{fieldName(field)} = value; - return this; - } - } -} - -@generateListMethods(field: GeneratedProperty, actualType: Type) = { - public @{genType.getName}Builder addTo@{toFirstUpper(field.getName)}(final @{actualType.getFullyQualifiedName} value) { - @if(!actualType.isInstanceOf[GeneratedType] && getRestrictions(actualType) != null) { - if (value != null) { - @checkArgument(field, actualType) - } - } - - if (this.@{fieldName(field)} == null) { - this.@{fieldName(field)} = new @{importedNames.get("arrayList")}<>(); - } - - this.@{fieldName(field)}.add(value); - return this; - } - - public @{genType.getName}Builder removeFrom@{toFirstUpper(field.getName)}(final @{actualType.getFullyQualifiedName} value) { - if (this.@{fieldName(field)} != null) { - this.@{fieldName(field)}.remove(value); - } - - return this; - } -} - -@checkArgument(field: GeneratedProperty, actualType: Type) = { - @if(getRestrictions(actualType).getRangeConstraint.isPresent) { - @if(actualType.isInstanceOf[ConcreteType]) { - @{AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(toFirstUpper(field.getName), "value")} - } else { - @{AbstractRangeGenerator.forType(actualType).generateRangeCheckerCall(toFirstUpper(field.getName), "value.getValue()")} - } - } - @if(getRestrictions(actualType).getLengthConstraint.isPresent) { - @if(actualType.isInstanceOf[ConcreteType]) { - @{LengthGenerator.generateLengthCheckerCall(fieldName(field), "value")} - } else { - @{LengthGenerator.generateLengthCheckerCall(fieldName(field), "value.getValue()")} - } - } - @for(currentConstant <- genType.getConstantDefinitions) { - @defining(fieldName(field)) { suffix => - @if(currentConstant.getName.startsWith(BindingMapping.PATTERN_CONSTANT_NAME) - && suffix.equals(currentConstant.getName.substring(BindingMapping.PATTERN_CONSTANT_NAME.length))) { - @{importedNames.get("codeHelpers")}.checkPattern(value, @{BindingMapping.MEMBER_PATTERN_LIST}@{suffix}, @{BindingMapping.MEMBER_REGEX_LIST}@{suffix}); - } - } - } -} - -@generateGetters(addOverride: Boolean) = { - @if(!getterMethods.isEmpty) { - @for(property <- getterMethods) { - @if(addOverride) {@@Override} - @{property} - } - } - @if(augmentField != null) { - @@SuppressWarnings("unchecked") - @if(addOverride) {@@Override} - public > E get@{toFirstUpper(augmentField.getName)} - (@{importedNames.get("class")} augmentationType) { - return (E) @{augmentField.getName}.get(@{importedNames.get("codeHelpers")}.nonNullValue(augmentationType, "augmentationType")); - } - } -} - -@generateHashCode() = { - @if(!properties.isEmpty || augmentField != null) { - private int hash = 0; - private volatile boolean hashValid = false; - - @@Override - public int hashCode() { - if (hashValid) { - return hash; - } - - final int prime = 31; - int result = 1; - @for(property <- properties) { - @if(property.getReturnType.getName.contains("[")) { - result = prime * result + @{importedNames.get("arrays")}.hashCode(@{fieldName(property)}); - } else { - result = prime * result + @{importedNames.get("objects")}.hashCode(@{fieldName(property)}); - } - } - @if(augmentField != null) { - result = prime * result + @{importedNames.get("objects")}.hashCode(@{augmentField.getName}); - } - - hash = result; - hashValid = true; - return result; - } - } -} - -@generateToString() = { - @if(properties != null) { - @@Override - public @{importedNames.get("string")} toString() { - @{importedNames.get("string")} name = "@{genType.getName} ["; - @{importedNames.get("stringBuilder")} builder = new @{importedNames.get("stringBuilder")}(name); - @for((property, index) <- properties.zipWithIndex) { - if (@{fieldName(property)} != null) { - builder.append("@{fieldName(property)}="); - @if(property.getReturnType.getName.contains("[")) { - builder.append(@{importedNames.get("arrays")}.toString(@{fieldName(property)})); - } else { - builder.append(@{fieldName(property)}); - } - @if(properties.size() > 1 && index < properties.size()-1){ - builder.append(", "); - } - } - } - @if(augmentField != null) { - @if(!properties.isEmpty()){ - final int builderLength = builder.length(); - final int builderAdditionalLength = builder.substring(name.length(), builderLength).length(); - if (builderAdditionalLength > 2 && !builder.substring(builderLength - 2, builderLength).equals(", ")) { - builder.append(", "); - } - } - builder.append("@{augmentField.getName}="); - builder.append(@{augmentField.getName}.values()); - return builder.append(']').toString(); - } else { - @if(properties.isEmpty()){ - return builder.append(']').toString(); - } else { - return builder.append(']').toString(); - } - } - } - } -} - -@generateImplementedMethods() = { - @if(childTreeNodeIdent) { - @@Override - public @{importedNames.get("identifiableItem")}<@{genType.getName()}, @{keyTypeName}> treeIdentifier() { - return new @{importedNames.get("identifiableItem")}(@{importedNames.get("genType")}.class,_identifier); - } - } else { - @if(childTreeNode) { - @@Override - public @{importedNames.get("item")}<@{genType.getName()}> treeIdentifier() { - return new @{importedNames.get("item")}(@{importedNames.get("genType")}.class); - } - } - } - - @if(augmentField != null) { - @@Override - public @{importedNames.get("classInstMap")}<@{importedNames.get("augmentation")}> - augments() { - //TODO implement - return null; - } - } -} - -@generateEquals() = { - @if(!properties.isEmpty || augmentField != null) { - @@Override - public boolean equals(@{importedNames.get("object")} obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof @{importedNames.get("treeNode")})) { - return false; - } - @if(parentTypeForBuilderName != null) { - if (!(obj instanceof @{importedNames.get("instantiable")})) { - return false; - } - if (!@{importedNames.get("genType")}.class.equals(((@{importedNames.get("instantiable")})obj) - .implementedInterface())) { - return false; - } - } - @{importedNames.get("genType")} other = (@{importedNames.get("genType")})obj; - @for(property <- properties) { - @if(property.getReturnType.getName.contains("[")) { - if (!@{importedNames.get("arrays")}.equals(@{fieldName(property)}, other.@{getterMethodName(property)}())) - } else { - if (!@{importedNames.get("objects")}.equals(@{fieldName(property)}, other.@{getterMethodName(property)}())) - } - { - return false; - } - } - @if(augmentField != null) { - if (getClass() == obj.getClass()) { - // Simple case: we are comparing against self - @{genType.getName}Impl otherImpl = (@{genType.getName}Impl) obj; - if (!@{importedNames.get("objects")}.equals(@{augmentField.getName}, otherImpl.@{augmentField.getName})) { - return false; - } - } @{"else"} { - // Hard case: compare our augments with presence there... - for (@{importedNames.get("map")}.Entry<@{importedNames.get("class")}, @{importedNames.get("augmentFieldReturnType")}> e : @{augmentField.getName}.entrySet()) { - if (!e.getValue().equals(other.getAugmentation(e.getKey()))) { - return false; - } - } - // .. and give the other one the chance to do the same - if (!obj.equals(this)) { - return false; - } - } - } - return true; - } - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplate.scala.txt deleted file mode 100644 index bc567ad636..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplate.scala.txt +++ /dev/null @@ -1,211 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.formatDataForJavaDoc -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.propsAsArgs -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.propsAsList -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.valueForBits -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.wrapToDocumentation -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty -@import org.opendaylight.yangtools.yang.model.api.`type`.BitsTypeDefinition - -@(genType: GeneratedType, genTo: GeneratedTransferObject, importedNames: Map[String, String], implementsList: String, -innerClasses: String, enumerations: String, constants: String, constructors: String, lengthRangeChecker: String, -fields: String, allProperties: List[GeneratedProperty], propertyMethod: String, isInnerClass: Boolean) -@if(genTo != null) { -@{wrapToDocumentation(formatDataForJavaDoc(genType))} -@annotationDeclaration() -@generateClassDeclaration(isInnerClass) - { - @if(genTo.getSUID != null) {private static final long serialVersionUID = @{genTo.getSUID.getValue}L;} - @{innerClasses} - @{enumerations} - @{constants} - @{fields} - @{lengthRangeChecker} - - @{constructors} - - @defaultInstance() - - @{propertyMethod} - - @if(genTo.isTypedef && genTo.getBaseType.isInstanceOf[BitsTypeDefinition]) { - public boolean[] getValue() { - return new boolean[]{ - @{valueForBits(genTo.getProperties)} - }; - } - } - - @generateHashCode() - - @generateEquals() - - @generateToString(genTo.getToStringIdentifiers) - } -} - -@annotationDeclaration() = { -@if(genTo.getAnnotations != null) { - @for(annotation <- genTo.getAnnotations) { - @@@{annotation.getName} - } -} -} - -@generateClassDeclaration(isInnerCLass: Boolean) = { -public @{if (isInnerCLass) "static final " -else if(genType.isAbstract) "abstract " -else " " -} -class @{genType.getName} -@if(genTo.getSuperType != null) { extends @{importedNames.get("superType")}} -@if(!implementsList.isEmpty) { implements @{implementsList}} -} - -@generateHashCode() = { -@if(!genTo.getHashCodeIdentifiers.isEmpty) { - @@Override - public int hashCode() { - final int prime = 31; - int result = 1; - @for(property <- genTo.getHashCodeIdentifiers) { - @if(property.getReturnType.getName.contains("[")) { - result = prime * result + @{importedNames.get("arrays")}.hashCode(@{fieldName(property)}); - } else { - result = prime * result + @{importedNames.get("objects")}.hashCode(@{fieldName(property)}); - } - } - return result; - } -} -} - -@generateEquals() = { -@if(!genTo.getEqualsIdentifiers.isEmpty) { - @@Override - public boolean equals(java.lang.Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - @{genTo.getName} other = (@{genTo.getName}) obj; - @for(property <- genTo.getEqualsIdentifiers) { - @if(property.getReturnType.getName.contains("[")) { - if (!@{importedNames.get("arrays")}.equals(@{fieldName(property)}, other.@{fieldName(property)})) - } else { - if (!@{importedNames.get("objects")}.equals(@{fieldName(property)}, other.@{fieldName(property)})) - } - { - return false; - } - } - return true; - } -} -} - -@generateToString(properties: List[GeneratedProperty]) = { -@if(properties != null) { - @@Override - public @{importedNames.get("string")} toString() { - @{importedNames.get("stringBuilder")} builder = new @{importedNames.get("stringBuilder")} (@{importedNames.get("type")}.class.getSimpleName()).append(" ["); - boolean first = true; - - @for(property <- properties) { - if (@{fieldName(property)} != null) { - if (first) { - first = false; - } else { - builder.append(", "); - } - builder.append("@{fieldName(property)}="); - @if(property.getReturnType.getName.contains("[")) { - builder.append(@{importedNames.get("arrays")}.toString(@{fieldName(property)})); - } else { - builder.append(@{fieldName(property)}); - } - } - } - return builder.append(']').toString(); - } -} -} - -@defaultInstance() = { -@if(genTo.isTypedef && !allProperties.isEmpty && !genTo.isUnionType) { - @if("org.opendaylight.yangtools.yang.common.Empty".equals(allProperties.get(0).getReturnType.getFullyQualifiedName)) { - public static @{genTo.getName} getDefaultInstance() { - return new @{genTo.getName}(Empty.getInstance()); - } - } else { - @if(!"org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier".equals(allProperties.get(0).getReturnType.getFullyQualifiedName)) { - public static @{genTo.getName} getDefaultInstance(String defaultValue) { - @if(allProperties.size > 1) { - @{importedNames.get("list")}<@{importedNames.get("string")}> properties = @{importedNames.get("lists")}.newArrayList(@{propsAsArgs(allProperties)}); - if (!properties.contains(defaultValue)) { - throw new @{importedNames.get("illegalArgumentException")}("invalid default parameter"); - } - int i = 0; - return new @{genTo.getName}(@propsAsList(allProperties, importedNames.get("boolean"))); - } else { - @if("byte[]".equals(allProperties.get(0).getReturnType.getName)) { - @{importedNames.get("baseEncoding")} baseEncoding = @{importedNames.get("baseEncoding")}.base64(); - return new @{genTo.getName}(baseEncoding.decode(defaultValue)); - } else { - @allProperties.get(0).getReturnType.getFullyQualifiedName match { - case "java.lang.String" => { - return new @{genTo.getName}(defaultValue); - } - case "java.lang.Boolean" => { - return new @{genTo.getName}(@{importedNames.get("boolean")}.valueOf(defaultValue)); - } - case "java.lang.Byte" => { - return new @{genTo.getName}(@{importedNames.get("byte")}.valueOf(defaultValue)); - } - case "java.lang.Short" => { - return new @{genTo.getName}(@{importedNames.get("short")}.valueOf(defaultValue)); - } - case "java.lang.Integer" => { - return new @{genTo.getName}(@{importedNames.get("integer")}.valueOf(defaultValue)); - } - case "java.lang.Long" => { - return new @{genTo.getName}(@{importedNames.get("long")}.valueOf(defaultValue)); - } - case "org.opendaylight.yangtools.yang.common.Uint8" => { - return new @{genTo.getName}(@{importedNames.get("uint8")}.valueOf(defaultValue)); - } - case "org.opendaylight.yangtools.yang.common.Uint16" => { - return new @{genTo.getName}(@{importedNames.get("uint16")}.valueOf(defaultValue)); - } - case "org.opendaylight.yangtools.yang.common.Uint32" => { - return new @{genTo.getName}(@{importedNames.get("uint32")}.valueOf(defaultValue)); - } - case "org.opendaylight.yangtools.yang.common.Uint64" => { - return new @{genTo.getName}(@{importedNames.get("uint64")}.valueOf(defaultValue)); - } - case _ => { - return new @{genTo.getName}(new @{allProperties.get(0).getReturnType.getName}(defaultValue)); - } - } - } - } - } - } - } -} -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateConstructors.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateConstructors.scala.txt deleted file mode 100644 index 15b0d7867d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateConstructors.scala.txt +++ /dev/null @@ -1,76 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.asArguments -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping - -@(genTo: GeneratedTransferObject, allProperties: List[GeneratedProperty], properties: List[GeneratedProperty], -parentProperties: List[GeneratedProperty], importedNames: Map[String, String], argumentsDeclaration: String, -unionConstructor: String, genRestrictions: String) -@if(!unionConstructor.isEmpty) { -@{unionConstructor} -} else { - @if(genTo.isTypedef && !allProperties.isEmpty && allProperties.size == 1 && allProperties.get(0).getName.equals("value")) { - @@@{importedNames.get("constructorProperties")}("value") - } - public @{genTo.getName}(@{argumentsDeclaration}) { - @if(!parentProperties.isEmpty) { - super(@{asArguments(parentProperties)}); - } - - @{genRestrictions} - - @if(genTo.isTypedef && !allProperties.isEmpty && allProperties.size == 1 && allProperties.get(0).getName.equals("value")) { - @{importedNames.get("preconditions")}.checkNotNull(_value, "Supplied value may not be null"); - @for(currentConstant <- genTo.getConstantDefinitions) { - @if(BindingMapping.PATTERN_CONSTANT_NAME.equals(currentConstant.getName)) { - @{importedNames.get("CodeHelpers")}.checkPattern(_value, @{BindingMapping.MEMBER_PATTERN_LIST}, @{BindingMapping.MEMBER_REGEX_LIST}); - } - } - } - @for(prop <- properties) { - @if(importedNames.get(prop.getReturnType.toString).contains("[]")) { - @if(genTo.isTypedef && !allProperties.isEmpty && allProperties.size == 1 && allProperties.get(0).getName.equals("value")) { - this.@{fieldName(prop)} = @{fieldName(prop)}.clone(); - } else { - this.@{fieldName(prop)} = @{fieldName(prop)} == null ? null : @{fieldName(prop)}.clone(); - } - } else { - this.@{fieldName(prop)} = @{fieldName(prop)}; - } - } - } -} -@if(!allProperties.isEmpty) { - /** - * Creates a copy from Source Object. - * - * @@param source Source object - */ - public @{genTo.getName}(@{genTo.getName} source) { - @if(!parentProperties.isEmpty) { - super(source); - } - @for(property <- properties) { - this.@{fieldName(property)} = source.@{fieldName(property)}; - } - } -} -@if(properties.isEmpty && !parentProperties.isEmpty) { - /** - * Creates a new instance from @{importedNames.get("superType")} - * - * @@param source Source object - */ - public @{genTo.getName}(@{importedNames.get("superType")} source) { - super(source); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateRestrictions.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateRestrictions.scala.txt deleted file mode 100644 index 631ab37041..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateRestrictions.scala.txt +++ /dev/null @@ -1,27 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getRestrictions -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.paramValue -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.AbstractRangeGenerator -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.range_generators.LengthGenerator -@import org.opendaylight.mdsal.binding.javav2.model.api.Type - -@(currentType: Type, paramName: String, returnType: Type, rangeGenerator: AbstractRangeGenerator[_]) -@if(getRestrictions(currentType) != null) { - @if(getRestrictions(currentType).getLengthConstraint.isPresent || getRestrictions(currentType).getRangeConstraint.isPresent) { - if (@{paramName} != null) { - @if(getRestrictions(currentType).getLengthConstraint.isPresent) { - @{LengthGenerator.generateLengthCheckerCall(paramName, paramValue(returnType, paramName))} - } - @if(getRestrictions(currentType).getRangeConstraint.isPresent) { - @{rangeGenerator.generateRangeCheckerCall(paramName, paramValue(returnType, paramName))} - } - } - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateUnionConstr.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateUnionConstr.scala.txt deleted file mode 100644 index 833d0cf328..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/classTemplateUnionConstr.scala.txt +++ /dev/null @@ -1,27 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.asArguments -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType - -@(genType: GeneratedType, parentProperties: List[GeneratedProperty], allProperty: GeneratedProperty, other: List[GeneratedProperty], -importedName: String, genRestrictions: String) -public @{genType.getName}(@{importedName} @{allProperty.getName}) { - @if(!parentProperties.isEmpty) { - super(@{asArguments(parentProperties)}); - } - - @{genRestrictions} - - this.@{fieldName(allProperty)} = @{allProperty.getName}; - @for(item <- other) { - this.@{fieldName(item)} = null; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/constantsTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/constantsTemplate.scala.txt deleted file mode 100644 index 14e075c39d..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/constantsTemplate.scala.txt +++ /dev/null @@ -1,53 +0,0 @@ -@* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.apache.commons.text.StringEscapeUtils.escapeJava -@import org.opendaylight.mdsal.binding.javav2.model.api.Type -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType -@import org.opendaylight.mdsal.binding.javav2.model.api.Constant -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping -@import org.opendaylight.mdsal.binding.javav2.generator.util.Types -@import org.opendaylight.yangtools.yang.common.QName; -@import org.opendaylight.yangtools.yang.common.Revision; - -@(genType: GeneratedType, importedNames: Map[String, String], importedName: Function[Type, String], qnameOnly: Boolean) -@for(c <- genType.getConstantDefinitions) { - @if(c.getName.startsWith(BindingMapping.PATTERN_CONSTANT_NAME)) { - @if(!qnameOnly) { - @defining(c.getName.substring(BindingMapping.PATTERN_CONSTANT_NAME.length)) { suffix => - @defining(c.getValue.asInstanceOf[Map[String, String]]) { cValue => - @if(cValue.size == 1) { - private static final @{importedNames.get("pattern")} @{BindingMapping.MEMBER_PATTERN_LIST}@{suffix} = - @{importedNames.get("pattern")}.compile("@{escapeJava(cValue.keySet.head)}"); - private static final @{importedNames.get("string")} @{BindingMapping.MEMBER_REGEX_LIST}@{suffix} = "@{escapeJava(cValue.values.head)}"; - } else { - private static final @{importedNames.get("pattern")}[] @{BindingMapping.MEMBER_PATTERN_LIST}@{suffix} = - @{importedNames.get("codeHelpers")}.compilePatterns(@{importedNames.get("immutableList")}.of( - @{(cValue.keySet map {escapeJava}).mkString("\"", "\", \"", "\"")})); - private static final @{importedNames.get("string")}[] @{BindingMapping.MEMBER_REGEX_LIST}@{suffix} = { - @{(cValue.keySet map {escapeJava}).mkString("\"", "\", \"", "\"")} - }; - }}}} - } else { - public static final @{importedName(c.getType())} @{c.getName} = - @if(c.getValue.isInstanceOf[QName]) { - @defining(c.getValue.asInstanceOf[QName]) { qname => - @{importedNames.get("qname")}.create("@{qname.getNamespace}", - @defining(qname.getRevision()) { rev => - @if(rev.isPresent()) { - "@{rev.get}" - } else { - "null"; - } - }, "@{qname.getLocalName}").intern(); - } - } else { - @{c.getValue}; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/enumTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/enumTemplate.scala.txt deleted file mode 100644 index 7fa0fdf6e4..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/enumTemplate.scala.txt +++ /dev/null @@ -1,64 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.EnumRenderer.writeEnumeration -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.formatDataForJavaDoc -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.wrapToDocumentation -@import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType - -@(genType: GeneratedType, importedName: String) -@if(genType != null) { -@{wrapToDocumentation(formatDataForJavaDoc(genType))} -public enum @{genType.getName} { -@{writeEnumeration(genType.asInstanceOf[Enumeration])} - - @{importedName} name; - int value; - private static final java.util.Map VALUE_MAP; - - static { - final com.google.common.collect.ImmutableMap.Builder b = com.google.common.collect.ImmutableMap.builder(); - for (@{genType.getName} enumItem : @{genType.getName}.values()) - { - b.put(enumItem.value, enumItem); - } - - VALUE_MAP = b.build(); - } - - private @{genType.getName}(int value, @{importedName} name) { - this.value = value; - this.name = name; - } - - /** - * Returns the name of the enumeration item as it is specified in the input yang. - * - * @@return the name of the enumeration item as it is specified in the input yang - */ - public @{importedName} getName() { - return name; - } - - /** - * @@return integer value - */ - public int getIntValue() { - return value; - } - - /** - * @@param valueArg - * @@return corresponding @{genType.getName} item - */ - public static @{genType.getName} forValue(int valueArg) { - return VALUE_MAP.get(valueArg); - } -} -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/interfaceTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/interfaceTemplate.scala.txt deleted file mode 100755 index f3ff1ebcb3..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/interfaceTemplate.scala.txt +++ /dev/null @@ -1,40 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.formatDataForJavaDoc -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.wrapToDocumentation -@import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType - -@(genType: GeneratedType, enums: String, annotations: String, generatedMethods: String, generatedImports: String, -generatedConstants: String, innerClasses: String, getII: String, keyParams: String) -@* - * Template method which generate the whole body of the interface. - * - * @return string with code for interface body in JAVA format - *@ -@if(genType != null) { -@{wrapToDocumentation(formatDataForJavaDoc(genType))} -@{annotations} -public interface @{genType.getName} - @if(!generatedImports.isEmpty){extends @{generatedImports}} -{ - @{innerClasses} - @{enums} - @{generatedConstants} - @{generatedMethods} - - @if(getII != null) { - public static InstanceIdentifier<@{genType.getName}> getInstanceIdentifier(@{keyParams}) { - return @{getII}; - } - } -} -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/modelProviderTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/modelProviderTemplate.scala.txt deleted file mode 100644 index 583b064de2..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/modelProviderTemplate.scala.txt +++ /dev/null @@ -1,21 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping.MODULE_INFO_CLASS_NAME - -@(packageName: String, yangModelBindingProviderName: String, yangModuleInfoName: String) -package @{packageName}; - -public final class @{MODEL_BINDING_PROVIDER_CLASS_NAME} implements @{yangModelBindingProviderName} { - - @@Override - public @{yangModuleInfoName} getModuleInfo() { - return @{MODULE_INFO_CLASS_NAME}.getInstance(); - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionBuilderTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionBuilderTemplate.scala.txt deleted file mode 100755 index 2e1bfa59a7..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionBuilderTemplate.scala.txt +++ /dev/null @@ -1,35 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import java.util.List -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.formatDataForJavaDoc -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.wrapToDocumentation -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getAccessModifier -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getClarification - -@(genType: GeneratedTransferObject, typeName: String, importedNames: Map[String, String], generatedParameters: Map[String, String]) -@if(genType != null) { -@{wrapToDocumentation(formatDataForJavaDoc(genType, getClarification))} -public class @{typeName} { - private @{typeName}() { - //Exists only to defeat instantiation. - } - - @for(method <- genType.getMethodDefinitions) { - @{getAccessModifier(method.getAccessModifier)} - @if(method.isStatic) {static} - @if(method.isFinal) { final} - @{importedNames.get(method.getName)} - @{method.getName} - (@{generatedParameters.get(method.getName)}) { - throw new @{importedNames.get("unsupportedOperationException")}("Not yet implemented"); - } - } -} -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionTemplate.scala.txt deleted file mode 100644 index 1329156484..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/unionTemplate.scala.txt +++ /dev/null @@ -1,85 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import org.opendaylight.mdsal.binding.javav2.generator.util.Types.getOuterClassName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.fieldName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.asArguments -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType -@import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty - -@(baseType: GeneratedType, importedNames: Map[String, String], finalProperties: List[GeneratedProperty], -parentProperties: List[GeneratedProperty], properties: List[GeneratedProperty], propertyList: String) -@for(property <- parentProperties) { - public @{baseType.getName}(@{importedNames.get(property.getName)} @{fieldName(property)}) { - super(@{fieldName(property)}); - } -} - -@for(property <- finalProperties) { - @*TO DO parentProperties + #[property] as argument to method below see unionTemplate 84 *@ - public @{baseType.getName}(@{importedNames.get(property.getName)} @{fieldName(property)}) { - super(); - this.@{fieldName(property)} = @{fieldName(property)}; - @for(otherProperty <- finalProperties) { - @if(property != otherProperty && !"value".equals(otherProperty.getName)) { - this.@{fieldName(otherProperty)} = null; - } - } - } -} - -@for(property <- properties) { - @if("char[]".equals(property.getReturnType.getName)) { - /** - * Constructor provided only for using in JMX. Don't use it for - * construction new object of this union type. - */ - @@@{importedNames.get("constructorProperties")}("@{property.getName}") - public @{baseType.getName}(@{importedNames.get(property.getName)} @{fieldName(property)}) { - @{importedNames.get("string")} defVal = new @{importedNames.get("string")}(@{fieldName(property)}); - @{baseType.getName} defInst = @{typeBuilder}.getDefaultInstance(defVal); - @for(otherProperty <- finalProperties) { - this.@{fieldName(otherProperty)} = defInst.@{fieldName(otherProperty)}; - } - - this.@{fieldName(property)} = @{fieldName(property)} == null ? null : @{fieldName(property)}.clone(); - } - } -} - -/** - * Creates a copy from Source Object. - * - * @@param source Source object - */ -public @{baseType.getName}(@{baseType.getName} source) { - @if(!parentProperties.isEmpty()) { - super(source); - } else { - @{propertyList} - } -} - -@if(properties.isEmpty && !parentProperties.isEmpty) { - /** - * Creates a new instance from @{importedNames.get("superType")} - * - * @@param source Source object - */ - public @{baseType.getName}(@{importedNames.get("superType")} source) { - super(source); - } -} - -@typeBuilder() = { -@if(getOuterClassName(baseType) != null) { - @{getOuterClassName(baseType)}@{baseType.getName}Builder -} else { - @{baseType.getName}Builder -} -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/yangModuleInfoTemplate.scala.txt b/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/yangModuleInfoTemplate.scala.txt deleted file mode 100644 index 7b9232a636..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/main/twirl/org/opendaylight/mdsal/binding/javav2/java/api/generator/yangModuleInfoTemplate.scala.txt +++ /dev/null @@ -1,153 +0,0 @@ -@* - * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - *@ - -@import java.util.function.Function; -@import java.util.Optional -@import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier.CLASS -@import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer.normalizeSpecificIdentifier -@import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer.normalizeFullPackageName -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.TextTemplateUtil.getSourcePath -@import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.YangModuleInfoTemplateRenderer.getSortedQName -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName -@import org.opendaylight.mdsal.binding.javav2.util.BindingMapping.MODULE_INFO_CLASS_NAME -@import org.opendaylight.yangtools.yang.model.api.Module -@import org.opendaylight.yangtools.yang.model.api.SchemaContext - -@(module: Module, ctx: SchemaContext, importedNames: Map[String, String], -moduleFilePathResolver: Function[Module, Optional[String]]) -@if(module != null && ctx != null) { -public final class @{MODULE_INFO_CLASS_NAME} implements @{importedNames.get("yangModuleInfo")} { - - private static final @{importedNames.get("yangModuleInfo")} INSTANCE = new @{MODULE_INFO_CLASS_NAME}(); - - private final @{importedNames.get("string")} name = "@{module.getName}"; - private final @{importedNames.get("string")} namespace = "@{module.getNamespace.toString}"; - private final @{importedNames.get("string")} semanticVersion = "@{module.getSemanticVersion}"; - private final @{importedNames.get("string")} revision = @if(module.getRevision.isPresent) { "@{module.getRevision.get.toString}" } else { null }; - private final @{importedNames.get("string")} resourcePath = "@{getSourcePath(module, moduleFilePathResolver)}"; - private final @{importedNames.get("set")} importedModules; - - public static @{importedNames.get("yangModuleInfo")} getInstance() { - return INSTANCE; - } - - @{classBody(module, MODULE_INFO_CLASS_NAME)} -} -} - -@generateSubInfo(module: Module) = { -@for(submodule <- module.getSubmodules) { - private static final class @{normalizeSpecificIdentifier(submodule.getName, CLASS)}Info implements @{importedNames.get("yangModuleInfo")} { - - private static final @{importedNames.get("yangModuleInfo")} INSTANCE = new @{normalizeSpecificIdentifier(submodule.getName, CLASS)}Info(); - - private final @{importedNames.get("string")} name = "@{submodule.getName}"; - private final @{importedNames.get("string")} semanticVersion = "@{submodule.getSemanticVersion}"; - private final @{importedNames.get("string")} namespace = "@{submodule.getNamespace.toString}"; - private final @{importedNames.get("string")} revision = @if(module.getRevision.isPresent) { "@{module.getRevision.get.toString}" } else { null }; - private final @{importedNames.get("string")} resourcePath = "@{getSourcePath(submodule, moduleFilePathResolver)}"; - private final @{importedNames.get("set")} importedModules; - - public static @{importedNames.get("yangModuleInfo")} getInstance() { - return INSTANCE; - } - - @{classBody(submodule, normalizeSpecificIdentifier(submodule.getName, CLASS) + "Info")} - } -} -} - -@classBody(module: Module, className: String) = { - private @{className}() { - @if(!module.getImports.isEmpty || !module.getSubmodules.isEmpty) { - @{importedNames.get("set")}<@{importedNames.get("yangModuleInfo")}> set = new @{importedNames.get("hashSet")}<>(); - } - @if(!module.getImports.isEmpty) { - @for(moduleImport <- module.getImports) { - set.add(@{normalizeFullPackageName(getRootPackageName(ctx.findModule(moduleImport - .getModuleName, moduleImport.getRevision).get))}.@{MODULE_INFO_CLASS_NAME}.getInstance()); - } - } - @if(!module.getSubmodules.isEmpty) { - @for(submodule <- module.getSubmodules) { - set.add(@{normalizeSpecificIdentifier(submodule.getName, CLASS)}Info.getInstance()); - } - } - @if(module.getImports.isEmpty && module.getSubmodules.isEmpty) { - importedModules = @{importedNames.get("collections")}.emptySet(); - } else { - importedModules = @{importedNames.get("immutableSet")}.copyOf(set); - } - - @{importedNames.get("inputStream")} stream = @{MODULE_INFO_CLASS_NAME}.class.getResourceAsStream(resourcePath); - if (stream == null) { - throw new IllegalStateException("Resource '" + resourcePath + "' is missing"); - } - try { - stream.close(); - } catch (@{importedNames.get("iOException")} e) { - // Resource leak, but there is nothing we can do - } - } - - @@Override - public @{importedNames.get("string")} getName() { - return name; - } - - @@Override - public @{importedNames.get("string")} getRevision() { - return revision; - } - - @@Override - public @{importedNames.get("string")} getNamespace() { - return namespace; - } - - @@Override - public @{importedNames.get("optional")}<@{importedNames.get("semVer")}> getSemanticVersion() { - return Optional.of(@{importedNames.get("semVer")}.valueOf(semanticVersion)); - } - - @@Override - public @{importedNames.get("schemaSourceRepresentation")} getModuleSourceRepresentation() { - //TODO implement - return null; - } - - @@Override - public @{importedNames.get("inputStream")} getModuleSourceStream() { - @{importedNames.get("inputStream")} stream = @{MODULE_INFO_CLASS_NAME}.class.getResourceAsStream(resourcePath); - if (stream == null) { - throw new IllegalStateException("Resource '" + resourcePath + "' is missing"); - } - return stream; - } - - @@Override - public @{importedNames.get("set")}<@{importedNames.get("yangModuleInfo")}> getImportedModules() { - return importedModules; - } - - @@Override - public @{importedNames.get("string")} toString() { - @{importedNames.get("stringBuilder")} sb = new @{importedNames.get("stringBuilder")}(this.getClass().getCanonicalName()); - sb.append("["); - sb.append("name = " + name); - sb.append(", namespace = " + namespace); - sb.append(", semanticVersion = " + semanticVersion); - sb.append(", revision = " + revision); - sb.append(", resourcePath = " + resourcePath); - sb.append(", imports = " + importedModules); - sb.append("]"); - return sb.toString(); - } - - @{generateSubInfo(module)} -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFileTest.java b/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFileTest.java deleted file mode 100644 index 28c09528dd..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/GeneratorJavaFileTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; -import org.sonatype.plexus.build.incremental.BuildContext; -import org.sonatype.plexus.build.incremental.DefaultBuildContext; - -public class GeneratorJavaFileTest { - - @Test - public void generatedFilesTest() throws Exception { - final SchemaContext context = YangParserTestUtils.parseYangResourceDirectory("/base/with_import/"); - final BindingGenerator bindingGenerator = new BindingGeneratorImpl(true); - final List types = bindingGenerator.generateTypes(context, context.getModules()); - final BuildContext buildContext = new DefaultBuildContext(); - final GeneratorJavaFile gjf = new GeneratorJavaFile(buildContext, types); - final File persistentSourcesDirectory = - new File(GeneratorJavaFileTest.class.getResource("/base").getPath()); - final File generatedSourcesDirectory = - new File(GeneratorJavaFileTest.class.getResource("/base").getPath()); - final List generateToFile = gjf.generateToFile(generatedSourcesDirectory, persistentSourcesDirectory); - for (final File f : generateToFile) { - Assert.assertNotNull(f); - } - final List files = new ArrayList<>(); - final RuntimeException runtimeException = new RuntimeException(); - for (final File file : generateToFile) { - BufferedReader br = null; - FileReader fr = null; - try { - fr = new FileReader(file.getAbsolutePath()); - br = new BufferedReader(fr); - final StringBuilder sb = new StringBuilder(); - String currentLine; - while ((currentLine = br.readLine()) != null) { - sb.append(currentLine).append('\n'); - } - files.add(sb.toString()); - } catch (final IOException e) { - throw new RuntimeException(e); - } finally { - try { - if (br != null) { - br.close(); - } - if (fr != null) { - fr.close(); - } - } catch (final IOException ex) { - runtimeException.addSuppressed(ex); - } - } - } - - for (final String s : files) { - Assert.assertNotNull(s); - Assert.assertTrue(!s.isEmpty()); - } - - for (final File file2 : generateToFile) { - file2.delete(); - } - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRendererTest.java b/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRendererTest.java deleted file mode 100644 index 302df4f822..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/renderers/BuilderRendererTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers; - -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; - -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -public class BuilderRendererTest { - private static final String TEST = "test"; - - @Test - public void builderTemplateGenerateToStringWithPropertyTest() throws Exception { - final GeneratedType genType = mockGenType("get" + TEST); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("java.lang.String toString() {")); - assertTrue(generateToString.contains("java.lang.String name = \"test [\";")); - assertTrue(generateToString.contains("java.lang.StringBuilder builder = new java.lang.StringBuilder(name);")); - assertTrue(generateToString.contains("if (_test != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test=\");")); - assertTrue(generateToString.contains("builder.append(_test);")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - @Test - public void builderTemplateGenerateToStringWithoutAnyPropertyTest() throws Exception { - final GeneratedType genType = mockGenType(TEST); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("java.lang.String toString() {")); - assertTrue(generateToString.contains("java.lang.String name = \"test [\";")); - assertTrue(generateToString.contains("java.lang.StringBuilder builder = new java.lang.StringBuilder(name);")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - @Test - public void builderTemplateGenerateToStringWithMorePropertiesTest() throws Exception { - final GeneratedType genType = mockGenTypeMoreMeth("get" + TEST); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("java.lang.String toString() {")); - assertTrue(generateToString.contains("java.lang.String name = \"test [\";")); - assertTrue(generateToString.contains("java.lang.StringBuilder builder = new java.lang.StringBuilder(name);")); - assertTrue(generateToString.contains("if (_test1 != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test1=\");")); - assertTrue(generateToString.contains("builder.append(_test1);")); - assertTrue(generateToString.contains("builder.append(\", \");")); - assertTrue(generateToString.contains("if (_test2 != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test2=\");")); - assertTrue(generateToString.contains("builder.append(_test2);")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - @Test - public void builderTemplateGenerateToStringWithoutPropertyWithAugmentTest() throws Exception { - final GeneratedType genType = mockGenType(TEST); - mockAugment(genType); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("java.lang.String toString() {")); - assertTrue(generateToString.contains("java.lang.String name = \"test [\";")); - assertTrue(generateToString.contains("java.lang.StringBuilder builder = new java.lang.StringBuilder(name);")); - assertTrue(generateToString.contains("builder.append(\"augmentation=\");")); - assertTrue(generateToString.contains("builder.append(augmentation.values());")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - @Test - public void builderTemplateGenerateToStringWithPropertyWithAugmentTest() throws Exception { - final GeneratedType genType = mockGenType("get" + TEST); - mockAugment(genType); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("java.lang.String toString() {")); - assertTrue(generateToString.contains("java.lang.String name = \"test [\";")); - assertTrue(generateToString.contains("java.lang.StringBuilder builder = new java.lang.StringBuilder(name);")); - assertTrue(generateToString.contains("if (_test != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test=\");")); - assertTrue(generateToString.contains("builder.append(_test);")); - assertTrue(generateToString.contains("builder.append(\", \");")); - assertTrue(generateToString.contains("builder.append(\"augmentation=\");")); - assertTrue(generateToString.contains("builder.append(augmentation.values());")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - @Test - public void builderTemplateGenerateToStringWithMorePropertiesWithAugmentTest() throws Exception { - final GeneratedType genType = mockGenTypeMoreMeth("get" + TEST); - mockAugment(genType); - final String generateToString = genToString(genType); - assertTrue(generateToString.contains("if (_test1 != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test1=\");")); - assertTrue(generateToString.contains("builder.append(_test1);")); - assertTrue(generateToString.contains("builder.append(\", \");")); - assertTrue(generateToString.contains("if (_test2 != null) {")); - assertTrue(generateToString.contains("builder.append(\"_test2=\");")); - assertTrue(generateToString.contains("builder.append(_test2);")); - assertTrue(generateToString.contains("builder.append(\", \");")); - assertTrue(generateToString.contains("builder.append(\"augmentation=\");")); - assertTrue(generateToString.contains("builder.append(augmentation.values());")); - assertTrue(generateToString.contains("return builder.append(']').toString();")); - } - - private void mockAugment(final GeneratedType genType) { - final List impls = new ArrayList<>(); - final Type impl = mock(Type.class); - doReturn("org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable").when(impl) - .getFullyQualifiedName(); - impls.add(impl); - doReturn(impls).when(genType).getImplements(); - } - - private GeneratedType mockGenTypeMoreMeth(final String methodeName) { - final GeneratedType genType = spy(GeneratedType.class); - doReturn(TEST).when(genType).getName(); - doReturn(TEST).when(genType).getPackageName(); - doReturn(new GeneratedTypeBuilderImpl(new StringBuilder(methodeName).append("test").toString(), methodeName, - new ModuleContext()) - .toInstance()).when(genType).getParentTypeForBuilder(); - - final List listMethodSign = new ArrayList<>(); - for (int i = 0; i < 2; i++) { - final MethodSignature methSign = mockMethSign(methodeName + (i + 1)); - listMethodSign.add(methSign); - } - doReturn(listMethodSign).when(genType).getMethodDefinitions(); - - final List impls = new ArrayList<>(); - doReturn(impls).when(genType).getImplements(); - return genType; - } - - private String genToString(final GeneratedType genType) { - final BuilderRenderer bt = new BuilderRenderer(genType); - return bt.body(); - } - - private GeneratedType mockGenType(final String methodeName) { - final GeneratedType genType = spy(GeneratedType.class); - doReturn(TEST).when(genType).getName(); - doReturn(TEST).when(genType).getPackageName(); - doReturn(new GeneratedTypeBuilderImpl(new StringBuilder(methodeName).append("test").toString(), methodeName, - new ModuleContext()) - .toInstance()).when(genType).getParentTypeForBuilder(); - - final List listMethodSign = new ArrayList<>(); - final MethodSignature methSign = mockMethSign(methodeName); - listMethodSign.add(methSign); - doReturn(listMethodSign).when(genType).getMethodDefinitions(); - - final List impls = new ArrayList<>(); - doReturn(impls).when(genType).getImplements(); - return genType; - } - - private MethodSignature mockMethSign(final String methodeName) { - final MethodSignature methSign = mock(MethodSignature.class); - doReturn(methodeName).when(methSign).getName(); - final Type methType = mock(Type.class); - doReturn(TEST).when(methType).getName(); - doReturn(TEST).when(methType).getPackageName(); - doReturn(methType).when(methSign).getReturnType(); - return methSign; - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtilTest.java b/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtilTest.java deleted file mode 100644 index 10f69fc63e..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/java/org/opendaylight/mdsal/binding/javav2/java/api/generator/util/TextTemplateUtilTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.java.api.generator.util; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.util.Types; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; - -public class TextTemplateUtilTest { - - @Test - public void voidReturnMethodTest() { - final MethodSignature methodSignature = mock(MethodSignature.class); - final Type returnType = Types.VOID; - when(methodSignature.getReturnType()).thenReturn(returnType); - final String javaDocForInterface = TextTemplateUtil.getJavaDocForInterface(methodSignature); - Assert.assertEquals("", javaDocForInterface); - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-import.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-import.yang deleted file mode 100644 index 5e4fa39879..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-import.yang +++ /dev/null @@ -1,14 +0,0 @@ -module test-import { - - yang-version 1; - namespace "urn:test:simple:test:import"; - prefix "test-import"; - - revision 2017-04-21; - - container _.my-import-.cont { - leaf test-leaf { - type string; - } - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-rpc.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-rpc.yang deleted file mode 100644 index 5d0011f1b7..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-rpc.yang +++ /dev/null @@ -1,21 +0,0 @@ -module test-rpc { - - yang-version 1; - namespace "urn:test:simple:test:rpc"; - prefix "test-rpc"; - - revision 2017-05-05; - - rpc hello-world { - input { - leaf name { - type string; - } - } - output { - leaf greeting { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-typedef-with-import.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-typedef-with-import.yang deleted file mode 100644 index ee2d8a9559..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/base/with_import/test-typedef-with-import.yang +++ /dev/null @@ -1,17 +0,0 @@ -module test { - - yang-version 1; - namespace "urn:test:simple:test"; - prefix "test"; - - import test-import { prefix "imported-test"; revision-date 2017-04-21; } - - revision 2017-02-06; - - typedef my-type { - type int8; - } - - container _.my-cont { - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-bits.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-bits.yang deleted file mode 100644 index 5d6af1e837..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-bits.yang +++ /dev/null @@ -1,15 +0,0 @@ -module test-bits{ - namespace "urn:test:bits"; - prefix bits; - revision 2017-01-01; - - typedef my-bits { - type bits { - bit ctrl; - bit alt { - position 5; - } - bit delete; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-decimal64.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-decimal64.yang deleted file mode 100644 index acbc5ed2a0..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-decimal64.yang +++ /dev/null @@ -1,23 +0,0 @@ -module test-decimal64{ - namespace "urn:test:decimal64"; - prefix decimal64; - revision 2017-01-01; - - typedef my-decimal64 { - type decimal64 { - fraction-digits 4; - } - } - - leaf ext-decimal64 { - type my-decimal64; - default "3.14"; - } - - leaf leaf-decimal64 { - type decimal64 { - fraction-digits 4; - } - default "3.14"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-identityref.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-identityref.yang deleted file mode 100644 index f223eae95e..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test-identityref.yang +++ /dev/null @@ -1,24 +0,0 @@ -module test-identityref{ - namespace "urn:test:identityref"; - prefix idref; - revision 2017-01-01; - - identity alg { - } - - typedef my-identityref { - type identityref { - base alg; - } - } - - leaf ext-identityref { - type my-identityref; - } - - leaf leaf-identityref { - type identityref { - base alg; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test/test-operation-service.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/test/test-operation-service.yang deleted file mode 100644 index 49a03cac79..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/test/test-operation-service.yang +++ /dev/null @@ -1,76 +0,0 @@ -module test-operation-service { - yang-version 1.1; - namespace "urn:test:operation"; - prefix "operation"; - - revision "2017-06-21" { - description - "Initial revision"; - } - - container my-cont { - action in-cont { - input { - leaf input-leaf { - type string; - } - } - - output { - leaf output-leaf { - type string; - } - } - } - - action in-cont2 { - input { - leaf input-leaf { - type string; - } - } - - output { - leaf output-leaf { - type string; - } - } - } - } - - list my-list { - key "name"; - - leaf name { - type string; - } - - action in-list { - input { - leaf input-list-leaf { - type string; - } - } - - output { - leaf output-list-leaf { - type string; - } - } - } - } - - rpc my-rpc { - input { - leaf rpc-input-leaf { - type string; - } - } - - output { - leaf rpc-output-leaf { - type string; - } - } - } -} diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/unions.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/unions.yang deleted file mode 100644 index 17b3449716..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/unions.yang +++ /dev/null @@ -1,45 +0,0 @@ -module test-recursive-unions{ - namespace "urn:test:unions"; - prefix unions; - revision 2017-01-01; - - typedef my-binary { - type binary; - } - - typedef ext-binary { - type my-binary; - } - - typedef my-bits { - type bits { - bit ctrl; - bit alt { - position 5; - } - bit delete; - } - } - - grouping apple { - container apple { - leaf apple { - type union { - type my-bits; - type ext-binary; - type instance-identifier; - type int32; - type string; - type boolean; - type union { - type int64; - type union { - type int64; - type int32; - } - } - } - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-import.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-import.yang deleted file mode 100644 index 09af041abf..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-import.yang +++ /dev/null @@ -1,23 +0,0 @@ -module yang-template-import { - yang-version 1; - namespace "org.opendaylight.yang.template.import"; - prefix "yti"; - - revision 2016-06-23 { - description "Simple yang for import"; - } - - leaf yti-leaf { - type string; - } - - extension ext; - - extension ext-arg { - argument arg; - } - - yti:ext; - - yti:ext-arg "arg"; -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-test.yang b/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-test.yang deleted file mode 100644 index a1a441653e..0000000000 --- a/binding2/mdsal-binding2-java-api-generator/src/test/resources/yang-template/yang-template-test.yang +++ /dev/null @@ -1,162 +0,0 @@ -module yang-template-test { - yang-version 1.1; - namespace "org.opendaylight.yang.template"; - prefix "ytemp"; - - import yang-template-import { prefix "yti"; revision-date 2016-06-23; } - - revision 2016-01-01 { - description "Simple yang missing deviation statement"; - } - - typedef simple-typedef { - type string; - default "simple-typedef"; - } - - deviation /yti:yti-leaf { - deviate add { - default "def"; - } - } - - container simple-container { - } - - anyxml simple-anyxml-mandatory { - mandatory true; - } - - anydata simple-anydata; - - anydata simple-anydata-mandatory { - mandatory true; - } - - container simple-container-with-action { - action act { - input { - leaf reset-at { - type string; - mandatory true; - } - } - output { - leaf reset-finished-at { - type string; - mandatory true; - } - } - } - } - - leaf simple-leaf { - type string; - } - - leaf-list simple-leaf-list { - type string; - } - - leaf-list simple-leaf-list-userordered { - ordered-by user; - type string; - } - - list simple-list { - key "simple-list-leaf-1"; - unique "simple-list-leaf-2"; - leaf simple-list-leaf-1 { - type string; - } - leaf simple-list-leaf-2 { - type string; - } - } - - list simple-list-more-arg-in-unique { - key "simple-list-leaf-1"; - unique "simple-list-leaf-1 simple-list-leaf-2"; - leaf simple-list-leaf-1 { - type string; - } - leaf simple-list-leaf-2 { - type string; - } - } - - list simple-list-userordered { - ordered-by user; - key "simple-list-userordered-leaf-1"; - unique "simple-list-userordered-leaf-2"; - leaf simple-list-userordered-leaf-1 { - type string; - } - leaf simple-list-userordered-leaf-2 { - type string; - } - } - - choice simple-choice { - case simple-case-1 { - leaf simple-case-1-leaf { - type string; - } - } - case simple-case-2 { - leaf simple-case-2-leaf { - type string; - } - } - } - - anyxml simple-anyxml; - - container simple-container-uses { - uses simple-grouping { - refine simple-grouping-leaf { - description "refined simple-grouping-leaf description"; - } - } - } - - grouping simple-grouping { - leaf simple-grouping-leaf { - description "simple-grouping-leaf description"; - type string; - } - } - - augment "/simple-container-uses" { - leaf augment-leaf { - type string; - } - } - - extension simple-extension { - description "simple-extension"; - argument simple-extension-argument; - } - - feature simple-feature { - description "simple-feature definex if device has some feature... hdd"; - } - - identity simple-identity { - description "simple-identity"; - } - - notification simple-notification { - leaf notification-leaf { - type string; - } - } - - rpc simple-rpc { - input { - leaf rpc-input-leaf { - type string; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-maven-api-gen-plugin/pom.xml b/binding2/mdsal-binding2-maven-api-gen-plugin/pom.xml deleted file mode 100644 index 441abbc8e7..0000000000 --- a/binding2/mdsal-binding2-maven-api-gen-plugin/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - org.opendaylight.odlparent - odlparent - 4.0.9 - - - - 4.0.0 - org.opendaylight.mdsal - mdsal-binding2-maven-api-gen-plugin - 0.16.0-SNAPSHOT - jar - - - - - org.opendaylight.mdsal - mdsal-artifacts - 4.0.0-SNAPSHOT - pom - import - - - org.opendaylight.yangtools - yangtools-artifacts - 2.1.8 - pom - import - - - - - - - org.opendaylight.yangtools - yang-maven-plugin-spi - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - - - org.opendaylight.mdsal - mdsal-binding2-java-api-generator - - - - org.opendaylight.yangtools - yang-data-api - - - - org.apache.maven - maven-core - 3.3.3 - provided - - - org.sonatype.plexus - plexus-build-api - provided - - - diff --git a/binding2/mdsal-binding2-maven-api-gen-plugin/src/main/java/org/opendaylight/mdsal/binding/javav2/maven/api/gen/plugin/CodeGeneratorImpl.java b/binding2/mdsal-binding2-maven-api-gen-plugin/src/main/java/org/opendaylight/mdsal/binding/javav2/maven/api/gen/plugin/CodeGeneratorImpl.java deleted file mode 100644 index 937fa9dd00..0000000000 --- a/binding2/mdsal-binding2-maven-api-gen-plugin/src/main/java/org/opendaylight/mdsal/binding/javav2/maven/api/gen/plugin/CodeGeneratorImpl.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.maven.api.gen.plugin; - -import static java.util.Objects.requireNonNull; -import static org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer.normalizeFullPackageName; -import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName; - -import com.google.common.annotations.Beta; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; -import java.io.BufferedWriter; -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import org.apache.maven.project.MavenProject; -import org.opendaylight.mdsal.binding.javav2.generator.api.BindingGenerator; -import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.GeneratorJavaFile; -import org.opendaylight.mdsal.binding.javav2.java.api.generator.renderers.YangModuleInfoTemplateRenderer; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator; -import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware; -import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonatype.plexus.build.incremental.BuildContext; - -@Beta -public final class CodeGeneratorImpl implements BasicCodeGenerator, BuildContextAware, MavenProjectAware { - - private static final Logger LOG = LoggerFactory.getLogger(CodeGeneratorImpl.class); - private static final String FS = File.separator; - private BuildContext buildContext; - private File projectBaseDir; - private Map additionalConfig; - private MavenProject mavenProject; - private File resourceBaseDir; - - /** - * This method is called from mojo (maven goal) - * @param context - * parsed from YANG files - * @param outputBaseDir - * expected output directory for generated sources configured by - * user - * @param currentModules - * YANG modules parsed from yangFilesRootDir - * @param moduleResourcePathResolver - * Function converting a local module to the packaged resource path - * @return - * @throws IOException - */ - @Override - public Collection generateSources(SchemaContext context, File outputBaseDir, Set currentModules, Function> moduleResourcePathResolver) throws IOException { - final BindingGenerator bindingGenerator = new BindingGeneratorImpl(true); - final List types = bindingGenerator.generateTypes(context, currentModules); - final GeneratorJavaFile generator = new GeneratorJavaFile(buildContext, types); - - File persistentSourcesDir = null; - if (additionalConfig != null) { - String persistentSourcesPath = additionalConfig.get("persistentSourcesDir"); - if (persistentSourcesPath != null) { - persistentSourcesDir = new File(persistentSourcesPath); - } - } - if (persistentSourcesDir == null) { - persistentSourcesDir = new File(projectBaseDir, "src" + FS + "main" + FS + "java"); - } - - List result = generator.generateToFile(outputBaseDir, persistentSourcesDir); - - result.addAll(generateModuleInfos(outputBaseDir, currentModules, context, moduleResourcePathResolver)); - return result; - } - - @Override - public void setAdditionalConfig(Map additionalConfiguration) { - this.additionalConfig = additionalConfiguration; - } - - @Override - public void setResourceBaseDir(File resourceBaseDir) { - this.resourceBaseDir = resourceBaseDir; - } - - @Override - public void setBuildContext(BuildContext buildContext) { - this.buildContext = requireNonNull(buildContext); - } - - @Override - public void setMavenProject(MavenProject project) { - this.mavenProject = project; - this.projectBaseDir = project.getBasedir(); - } - - private Collection generateModuleInfos(final File outputBaseDir, final Set yangModules, - final SchemaContext context, final Function> moduleResourcePathResolver) { - Builder result = ImmutableSet.builder(); - Builder bindingProviders = ImmutableSet.builder(); - for (Module module : yangModules) { - Builder currentProvidersBuilder = ImmutableSet.builder(); - Set moduleInfoProviders = generateYangModuleInfo(outputBaseDir, module, context, - moduleResourcePathResolver, currentProvidersBuilder); - ImmutableSet currentProviders = currentProvidersBuilder.build(); - LOG.info("Adding ModuleInfo providers {}", currentProviders); - bindingProviders.addAll(currentProviders); - result.addAll(moduleInfoProviders); - } - - result.add(writeMetaInfServices(resourceBaseDir, YangModelBindingProvider.class, bindingProviders.build())); - return result.build(); - } - - private File writeMetaInfServices(final File outputBaseDir, final Class serviceClass, - final ImmutableSet services) { - File metainfServicesFolder = new File(outputBaseDir, "META-INF" + File.separator + "services"); - metainfServicesFolder.mkdirs(); - File serviceFile = new File(metainfServicesFolder, serviceClass.getName()); - - String src = Joiner.on('\n').join(services); - - return writeFile(serviceFile, src); - } - - private Set generateYangModuleInfo(final File outputBaseDir, final Module module, final SchemaContext ctx, - final Function> moduleResourcePathResolver, final Builder providerSourceSet) { - - Builder generatedFiles = ImmutableSet.builder(); - final YangModuleInfoTemplateRenderer template = new YangModuleInfoTemplateRenderer(module, ctx, - moduleResourcePathResolver); - String moduleInfoSource = template.generateTemplate(); - if (moduleInfoSource.isEmpty()) { - throw new IllegalStateException("Generated code should not be empty!"); - } - String providerSource = template.generateModelProvider(); - - final File packageDir = GeneratorJavaFile.packageToDirectory(outputBaseDir, - normalizeFullPackageName(getRootPackageName(module))); - - generatedFiles.add(writeJavaSource(packageDir, BindingMapping.MODULE_INFO_CLASS_NAME, moduleInfoSource)); - generatedFiles - .add(writeJavaSource(packageDir, BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME, providerSource)); - providerSourceSet.add(template.getModelBindingProviderName()); - - return generatedFiles.build(); - - } - - private File writeFile(final File file, final String source) { - try (final OutputStream stream = buildContext.newFileOutputStream(file)) { - try (final Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) { - try (final BufferedWriter bw = new BufferedWriter(fw)) { - bw.write(source); - } - } catch (Exception e) { - LOG.error("Could not write file: {}",file,e); - } - } catch (Exception e) { - LOG.error("Could not create file: {}",file,e); - } - return file; - } - - private File writeJavaSource(final File packageDir, final String className, final String source) { - if (!packageDir.exists()) { - packageDir.mkdirs(); - } - final File file = new File(packageDir, className + ".java"); - writeFile(file, source); - return file; - } -} diff --git a/binding2/mdsal-binding2-runtime/pom.xml b/binding2/mdsal-binding2-runtime/pom.xml deleted file mode 100644 index f084d8bff0..0000000000 --- a/binding2/mdsal-binding2-runtime/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-runtime - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.mdsal - mdsal-binding2-generator-impl - - - org.opendaylight.yangtools - yang-test-util - - - org.opendaylight.mdsal - mdsal-binding2-test-model - - - diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContext.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContext.java deleted file mode 100755 index 8d43e29c30..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContext.java +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.context; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -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.BiMap; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Multimap; -import java.lang.reflect.Method; -import java.util.AbstractMap.SimpleEntry; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nullable; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext; -import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl; -import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType; -import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature; -import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType; -import org.opendaylight.mdsal.binding.javav2.model.api.Type; -import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder; -import org.opendaylight.mdsal.binding.javav2.runtime.context.util.BindingSchemaContextUtils; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.Action; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.concepts.Immutable; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; -import org.opendaylight.yangtools.yang.model.api.ActionDefinition; -import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode; -import org.opendaylight.yangtools.yang.model.api.AugmentationTarget; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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.DocumentedNode.WithStatus; -import org.opendaylight.yangtools.yang.model.api.Module; -import org.opendaylight.yangtools.yang.model.api.OperationDefinition; -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.api.TypeDefinition; -import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; -import org.opendaylight.yangtools.yang.model.api.meta.StatementSource; -import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition; -import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema; -import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Runtime Context for Java YANG Binding classes - * - *

    - * Runtime Context provides additional insight in Java YANG Binding, binding - * classes and underlying YANG schema, it contains runtime information, which - * could not be derived from generated classes alone using - * {@link BindingReflections}. - *

    - * Some of this information are for example list of all available children for - * cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are - * augmentable and new choices may be introduced by additional models. - *

    - * Same goes for all possible augmentations. - * - */ -@Beta -public class BindingRuntimeContext implements Immutable { - - private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class); - private static final char DOT = '.'; - private final ClassLoadingStrategy strategy; - private final SchemaContext schemaContext; - private final Multimap augmentationToSchemas = HashMultimap.create(); - private final BiMap targetToAugmentation = HashBiMap.create(); - - private final BiMap typeToDefiningSchema = HashBiMap.create(); - private final Multimap choiceToCases = HashMultimap.create(); - private final Map identities = new HashMap<>(); - - private final LoadingCache> identityClasses = CacheBuilder.newBuilder().weakValues().build( - new CacheLoader>() { - @Override - public Class load(final QName key) { - final Type identityType = BindingRuntimeContext.this.identities.get(key); - Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key); - try { - return BindingRuntimeContext.this.strategy.loadClass(identityType); - } catch (final ClassNotFoundException e) { - throw new IllegalArgumentException("Required class " + identityType + "was not found.", e); - } - } - }); - - private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) { - this.strategy = strategy; - this.schemaContext = schema; - - final BindingGeneratorImpl generator = new BindingGeneratorImpl(false); - final Map modules = generator.getModuleContexts(this.schemaContext); - - for (final ModuleContext ctx : modules.values()) { - this.augmentationToSchemas.putAll(ctx.getTypeToAugmentations()); - this.targetToAugmentation.putAll(ctx.getTargetToAugmentation()); - this.typeToDefiningSchema.putAll(ctx.getTypeToSchema()); - - ctx.getTypedefs(); - this.choiceToCases.putAll(ctx.getChoiceToCases()); - this.identities.putAll(ctx.getIdentities()); - } - } - - /** - * Creates Binding Runtime Context from supplied class loading strategy and - * schema context. - * - * @param strategy - * - class loading strategy to retrieve generated Binding classes - * @param ctx - * - schema context which describes YANG model and to which - * Binding classes should be mapped - * @return Instance of BindingRuntimeContext for supplied schema context. - */ - public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) { - return new BindingRuntimeContext(strategy, ctx); - } - - /** - * Returns a class loading strategy associated with this binding runtime context - * which is used to load classes. - * - * @return Class loading strategy. - */ - public ClassLoadingStrategy getStrategy() { - return this.strategy; - } - - /** - * Returns an stable immutable view of schema context associated with this Binding runtime context. - * - * @return stable view of schema context - */ - public SchemaContext getSchemaContext() { - return this.schemaContext; - } - - /** - * Returns schema of augmentation - *

    - * Returned schema is schema definition from which augmentation class was - * generated. This schema is isolated from other augmentations. This means - * it contains augmentation definition as was present in original YANG - * module. - *

    - * Children of returned schema does not contain any additional - * augmentations, which may be present in runtime for them, thus returned - * schema is unsuitable for use for validation of data. - *

    - * For retrieving {@link AugmentationSchemaNode}, which will contains full model - * for child nodes, you should use method - * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)} which - * will return augmentation schema derived from supplied augmentation target - * schema. - * - * @param augClass - * - ugmentation class - * @return Schema of augmentation or null if augmentaiton is not known in - * this context - * @throws IllegalArgumentException - * - if supplied class is not an augmentation - */ - public @Nullable Entry> - getAugmentationDefinition(final Class augClass) { - Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), - "Class %s does not represent augmentation", augClass); - - final Type refType = referencedType(augClass); - for (Entry> entry : this.augmentationToSchemas.asMap().entrySet()) { - if (refType.equals(entry.getKey())) { - return entry; - } - } - - throw new IllegalArgumentException("Supplied class is not an augmentation."); - } - - /** - * Returns defining {@link DataSchemaNode} for supplied class. - * - *

    - * Returned schema is schema definition from which class was generated. This - * schema may be isolated from augmentations, if supplied class represent - * node, which was child of grouping or augmentation. - *

    - * For getting augmentation schema from augmentation class use - * {@link #getAugmentationDefinition(Class)} instead. - * - * @param cls - * - class which represents list, container, choice or case. - * @return Schema node, from which class was generated. - */ - public DataSchemaNode getSchemaDefinition(final Class cls) { - Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls); - return (DataSchemaNode) this.typeToDefiningSchema.get(referencedType(cls)); - } - - public RpcDefinition getRpcDefinition(final Class> cls) { - return (RpcDefinition) typeToDefiningSchema.get(referencedType(cls)); - } - - public ActionDefinition getActionDefinition(final Class> cls) { - return (ActionDefinition) typeToDefiningSchema.get(referencedType(cls)); - } - - /** - * Returns defining {@link AugmentationSchemaNode} of target for supplied class. - * - * @param target - * - {@link DataNodeContainer} - * @param aug - * - supplied class - * @return entry of {@link AugmentationSchemaNode} according to its identifier - * {@link AugmentationIdentifier} - */ - public Entry getResolvedAugmentationSchema( - final DataNodeContainer target, final Class> aug) { - final Collection origSchemas = getAugmentationDefinition(aug).getValue(); - Preconditions.checkArgument(origSchemas != null, "Augmentation %s is not known in current schema context",aug); - /* - * FIXME: Validate augmentation schema lookup - * - * Currently this algorithm, does not verify if instantiated child nodes - * are real one derived from augmentation schema. The problem with full - * validation is, if user used copy builders, he may use augmentation - * which was generated for different place. - * - * If this augmentations have same definition, we emit same identifier - * with data and it is up to underlying user to validate data. - * - */ - final Set childNames = new HashSet<>(); - final Set realChilds = new HashSet<>(); - for (final AugmentationSchemaNode origSchema : origSchemas) { - for (final DataSchemaNode child : origSchema.getChildNodes()) { - final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName()); - final String childLocalName = child.getQName().getLocalName(); - if (dataChildQNname == null) { - for (final DataSchemaNode dataSchemaNode : target.getChildNodes()) { - if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) { - realChilds.add(dataSchemaNode); - childNames.add(dataSchemaNode.getQName()); - } - } - } else { - realChilds.add(dataChildQNname); - childNames.add(child.getQName()); - } - } - } - - final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames); - final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchemas.stream().findFirst().get(), - realChilds); - return new SimpleEntry<>(identifier, proxy); - } - - /** - * Returns resolved case schema for supplied class - * - * @param schema - * - resolved parent choice schema - * @param childClass - * - class representing case. - * @return Optionally a resolved case schema,.empty if the choice is not - * legal in the given context. - * @throws IllegalArgumentException - * - if supplied class does not represent case - */ - public Optional getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class childClass) throws IllegalArgumentException { - final DataSchemaNode origSchema = getSchemaDefinition(childClass); - Preconditions.checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema); - - /* - * FIXME: Make sure that if there are multiple augmentations of same - * named case, with same structure we treat it as equals this is due - * property of Binding specification and copy builders that user may be - * unaware that he is using incorrect case which was generated for - * choice inside grouping. - */ - final Optional found = BindingSchemaContextUtils.findInstantiatedCase(schema, - (CaseSchemaNode) origSchema); - return found; - } - - private static Type referencedType(final Class type) { - return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName(), true, null); - } - - static Type referencedType(final String type) { - final int packageClassSeparator = type.lastIndexOf(DOT); - return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), - type.substring(packageClassSeparator + 1), true, null); - } - - /** - * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}) - * from which supplied class was generated. Returned schema may be augmented with - * additional information, which was not available at compile type - * (e.g. third party augmentations). - * - * @param type Binding Class for which schema should be retrieved. - * @return Instance of generated type (definition of Java API), along with - * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition} - * which was used to generate supplied class. - */ - public Entry getTypeWithSchema(final Class type) { - return getTypeWithSchema(referencedType(type)); - } - - public Entry getTypeWithSchema(final String type) { - return getTypeWithSchema(referencedType(type)); - } - - private Entry getTypeWithSchema(final Type referencedType) { - final Object schema = this.typeToDefiningSchema.get(referencedType); - requireNonNull(schema, () -> "Failed to find schema for type " + referencedType); - - final Type definedType = this.typeToDefiningSchema.inverse().get(schema); - requireNonNull(definedType, () -> "Failed to find defined type for " + referencedType + " schema " + schema); - - if (definedType instanceof GeneratedTypeBuilder) { - return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema); - } - Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType); - return new SimpleEntry<>((GeneratedType) definedType,schema); - } - - public ImmutableMap> getChoiceCaseChildren(final DataNodeContainer schema) { - final Map> childToCase = new HashMap<>(); - for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) { - final ChoiceSchemaNode originalChoice = getOriginalSchema(choice); - final Type choiceType = referencedType(this.typeToDefiningSchema.inverse().get(originalChoice)); - final Collection cases = this.choiceToCases.get(choiceType); - - for (Type caze : cases) { - final Entry caseIdentifier = new SimpleEntry<>(choiceType,caze); - final HashSet caseChildren = new HashSet<>(); - if (caze instanceof GeneratedTypeBuilder) { - caze = ((GeneratedTypeBuilder) caze).toInstance(); - } - collectAllContainerTypes((GeneratedType) caze, caseChildren); - for (final Type caseChild : caseChildren) { - childToCase.put(caseChild, caseIdentifier); - } - } - } - return ImmutableMap.copyOf(childToCase); - } - - /** - * Map enum constants: yang - java - * - * @param enumClass enum generated class - * @return mapped enum constants from yang with their corresponding values in generated binding classes - */ - public BiMap getEnumMapping(final Class enumClass) { - final Entry typeWithSchema = getTypeWithSchema(enumClass); - return getEnumMapping(typeWithSchema); - } - - /** - * See {@link #getEnumMapping(Class)}} - */ - public BiMap getEnumMapping(final String enumClass) { - final Entry typeWithSchema = getTypeWithSchema(enumClass); - return getEnumMapping(typeWithSchema); - } - - private static BiMap getEnumMapping(final Entry typeWithSchema) { - final TypeDefinition typeDef = (TypeDefinition) typeWithSchema.getValue(); - - Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition); - final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef; - - final HashBiMap mappedEnums = HashBiMap.create(); - - for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) { - mappedEnums.put(enumPair.getName(), - JavaIdentifierNormalizer.normalizeSpecificIdentifier(enumPair.getName(), JavaIdentifier.CLASS)); - } - - // TODO cache these maps for future use - - return mappedEnums; - } - - public Set> getCases(final Class choice) { - final Collection cazes = this.choiceToCases.get(referencedType(choice)); - final Set> ret = new HashSet<>(cazes.size()); - for(final Type caze : cazes) { - try { - final Class c = this.strategy.loadClass(caze); - ret.add(c); - } catch (final ClassNotFoundException e) { - LOG.warn("Failed to load class for case {}, ignoring it", caze, e); - } - } - return ret; - } - - public Class getClassForSchema(final SchemaNode childSchema) { - final SchemaNode origSchema = getOriginalSchema(childSchema); - final Type clazzType = this.typeToDefiningSchema.inverse().get(origSchema); - try { - return this.strategy.loadClass(clazzType); - } catch (final ClassNotFoundException e) { - throw new IllegalStateException(e); - } - } - - private static boolean isLocalAugment(final AugmentationTarget container, final AugmentationSchemaNode augment) { - Preconditions.checkState(container instanceof SchemaNode); - final QName root = ((SchemaNode) container).getPath().getPathFromRoot().iterator().next(); - // findFirst makes no sense but just pick up one child to judge whether the target node is - // in the same module. - final Optional child = augment.getChildNodes().stream().findFirst(); - if (child.isPresent()) { - return root.getModule().equals(child.get().getQName().getModule()); - } - return false; - } - - public ImmutableMap getAvailableAugmentationTypes(final DataNodeContainer container) { - final Map identifierToType = new HashMap<>(); - if (container instanceof AugmentationTarget) { - for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) { - if (!isLocalAugment((AugmentationTarget) container, augment)) { - // Augmentation must have child nodes if is to be used with Binding classes - AugmentationSchemaNode augOrig = augment; - while (augOrig.getOriginalDefinition().isPresent()) { - augOrig = augOrig.getOriginalDefinition().get(); - } - - if (!augment.getChildNodes().isEmpty()) { - final Type augType = this.targetToAugmentation.get(augOrig.getTargetPath()); - if (augType != null) { - identifierToType.put(getAugmentationIdentifier(augment), augType); - } - } - } - } - } - - return ImmutableMap.copyOf(identifierToType); - } - - private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) { - final Set childNames = new HashSet<>(); - for (final DataSchemaNode child : augment.getChildNodes()) { - childNames.add(child.getQName()); - } - return new AugmentationIdentifier(childNames); - } - - private static Type referencedType(final Type type) { - if (type instanceof ReferencedTypeImpl) { - return type; - } - return new ReferencedTypeImpl(type.getPackageName(), type.getName(), true, null); - } - - private static Set collectAllContainerTypes(final GeneratedType type, final Set collection) { - for (final MethodSignature definition : type.getMethodDefinitions()) { - Type childType = definition.getReturnType(); - if (childType instanceof ParameterizedType) { - childType = ((ParameterizedType) childType).getActualTypeArguments()[0]; - } - if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) { - collection.add(referencedType(childType)); - } - } - for (final Type parent : type.getImplements()) { - if (parent instanceof GeneratedType) { - collectAllContainerTypes((GeneratedType) parent, collection); - } - } - return collection; - } - - private static T getOriginalSchema(final T choice) { - @SuppressWarnings("unchecked") - final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice); - if (original != null) { - return original; - } - return choice; - } - - public Class getIdentityClass(final QName input) { - return this.identityClasses.getUnchecked(input); - } - - public Method findOperationMethod(final Class key, final OperationDefinition operationDef) - throws NoSuchMethodException { - final String methodName = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(operationDef.getQName().getLocalName(), - JavaIdentifier.METHOD); - if (operationDef.getInput() != null && isExplicitStatement(operationDef.getInput())) { - final Class inputClz = this.getClassForSchema(operationDef.getInput()); - return key.getMethod(methodName, inputClz); - } - return key.getMethod(methodName); - } - - @SuppressWarnings("rawtypes") - private static boolean isExplicitStatement(final ContainerSchemaNode node) { - return node instanceof EffectiveStatement - && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION; - } -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContext.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContext.java deleted file mode 100644 index c6efd3e0e1..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContext.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.context; - -import com.google.common.annotations.Beta; -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.io.ByteSource; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import java.io.IOException; -import java.io.InputStream; -import java.lang.ref.WeakReference; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.generator.api.ModuleInfoRegistry; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.yangtools.concepts.AbstractObjectRegistration; -import org.opendaylight.yangtools.concepts.ObjectRegistration; -import org.opendaylight.yangtools.util.ClassLoaderUtils; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider; -import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; -import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; -import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource; -import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider; -import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Module info context. - */ -@Beta -public class ModuleInfoBackedContext extends GeneratedClassLoadingStrategy - implements ModuleInfoRegistry, SchemaContextProvider, SchemaSourceProvider { - - private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBackedContext.class); - - private final YangTextSchemaContextResolver ctxResolver = YangTextSchemaContextResolver.create("binding-context"); - private final ConcurrentMap> packageNameToClassLoader = - new ConcurrentHashMap<>(); - private final ConcurrentMap sourceIdentifierToModuleInfo = - new ConcurrentHashMap<>(); - private final ClassLoadingStrategy backingLoadingStrategy; - - - private ModuleInfoBackedContext(final ClassLoadingStrategy loadingStrategy) { - this.backingLoadingStrategy = loadingStrategy; - } - - /** - * Create new module info context. - * - * @return new module info context - */ - public static ModuleInfoBackedContext create() { - return new ModuleInfoBackedContext(getTCCLClassLoadingStrategy()); - } - - /** - * Create new module info context based on specific loading strategy. - * - * @param loadingStrategy - * - specific loading strategy - * @return new module info cotext based on specific loading strategy - */ - public static ModuleInfoBackedContext create(final ClassLoadingStrategy loadingStrategy) { - return new ModuleInfoBackedContext(loadingStrategy); - } - - @Override - public Class loadClass(final String fullyQualifiedName) throws ClassNotFoundException { - final String modulePackageName = BindingReflections.getModelRootPackageName(fullyQualifiedName); - final WeakReference classLoaderRef = packageNameToClassLoader.get(modulePackageName); - if (classLoaderRef != null) { - final ClassLoader classLoader = classLoaderRef.get(); - if (classLoader != null) { - return ClassLoaderUtils.loadClass(classLoader, fullyQualifiedName); - } - } - - if (backingLoadingStrategy == null) { - throw new ClassNotFoundException(fullyQualifiedName); - } - - final Class cls = backingLoadingStrategy.loadClass(fullyQualifiedName); - if (BindingReflections.isBindingClass(cls)) { - resolveModuleInfo(cls); - } - - return cls; - } - - // TODO finish schema parsing and expose as SchemaService - // Unite with current SchemaService - // Implement remove ModuleInfo to update SchemaContext - - /** - * Resolving of schema context. - * - * @return optional of schema context - */ - public Optional tryToCreateSchemaContext() { - return ctxResolver.getSchemaContext(); - } - - private boolean resolveModuleInfo(final Class cls) { - try { - return resolveModuleInfo(BindingReflections.getModuleInfo(cls)); - } catch (final Exception e) { - throw new IllegalStateException(String.format("Failed to resolve module information for class %s", cls), e); - } - } - - private boolean resolveModuleInfo(final YangModuleInfo moduleInfo) { - - final SourceIdentifier identifier = sourceIdentifierFrom(moduleInfo); - final YangModuleInfo previous = sourceIdentifierToModuleInfo.putIfAbsent(identifier, moduleInfo); - final ClassLoader moduleClassLoader = moduleInfo.getClass().getClassLoader(); - try { - if (previous == null) { - final String modulePackageName = moduleInfo.getClass().getPackage().getName(); - packageNameToClassLoader.putIfAbsent(modulePackageName, - new WeakReference<>(moduleClassLoader)); - ctxResolver.registerSource(toYangTextSource(identifier, moduleInfo)); - for (final YangModuleInfo importedInfo : moduleInfo.getImportedModules()) { - resolveModuleInfo(importedInfo); - } - } else { - return false; - } - } catch (final Exception e) { - LOG.error("Not including {} in YANG sources because of error.", moduleInfo, e); - } - return true; - } - - private static YangTextSchemaSource toYangTextSource(final SourceIdentifier identifier, final YangModuleInfo moduleInfo) { - return new YangTextSchemaSource(identifier) { - - @Override - public InputStream openStream() throws IOException { - return moduleInfo.getModuleSourceStream(); - } - - @Override - protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) { - return toStringHelper; - } - }; - } - - private static SourceIdentifier sourceIdentifierFrom(final YangModuleInfo moduleInfo) { - return RevisionSourceIdentifier.create(moduleInfo.getName(), Revision.ofNullable(moduleInfo.getRevision())); - } - - /** - * Add new module info into context. - * - * @param moduleInfos - * - new module info - */ - public void addModuleInfos(final Iterable moduleInfos) { - for (final YangModuleInfo yangModuleInfo : moduleInfos) { - registerModuleInfo(yangModuleInfo); - } - } - - @Override - public ObjectRegistration registerModuleInfo(final YangModuleInfo yangModuleInfo) { - final YangModuleInfoRegistration registration = new YangModuleInfoRegistration(yangModuleInfo, this); - resolveModuleInfo(yangModuleInfo); - return registration; - } - - @Override - public ListenableFuture getSource( - final SourceIdentifier sourceIdentifier) { - final YangModuleInfo yangModuleInfo = sourceIdentifierToModuleInfo.get(sourceIdentifier); - - if (yangModuleInfo == null) { - LOG.debug("Unknown schema source requested: {}, available sources: {}", sourceIdentifier, - sourceIdentifierToModuleInfo.keySet()); - return Futures.immediateFailedFuture(new SchemaSourceException("Unknown schema source: " - + sourceIdentifier)); - } - - return Futures.immediateFuture(YangTextSchemaSource.delegateForByteSource(sourceIdentifier, new ByteSource() { - @Override - public InputStream openStream() throws IOException { - return yangModuleInfo.getModuleSourceStream(); - } - })); - } - - private static class YangModuleInfoRegistration extends AbstractObjectRegistration { - - private final ModuleInfoBackedContext context; - - public YangModuleInfoRegistration(final YangModuleInfo instance, final ModuleInfoBackedContext context) { - super(instance); - this.context = context; - } - - @Override - protected void removeRegistration() { - context.remove(this); - } - - } - - private void remove(final YangModuleInfoRegistration registration) { - // FIXME implement - } - - @Override - public SchemaContext getSchemaContext() { - final Optional contextOptional = tryToCreateSchemaContext(); - if (contextOptional.isPresent()) { - return contextOptional.get(); - } - throw new IllegalStateException("Unable to recreate SchemaContext, error while parsing"); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtils.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtils.java deleted file mode 100644 index 64b09ab335..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtils.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.runtime.context.util; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.util.Iterator; -import java.util.Optional; -import java.util.Set; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier; -import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.mdsal.binding.javav2.util.BindingMapping; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode; -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; -import org.opendaylight.yangtools.yang.model.api.OperationDefinition; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.model.api.SchemaNode; -import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils; - -@Beta -public final class BindingSchemaContextUtils { - - private BindingSchemaContextUtils() { - throw new UnsupportedOperationException("Utility class should not be instantiated"); - } - - /** - * Find data node container by binding path in schema context. - * - * FIXME: This method does not search in case augmentations. - * - * @param ctx - * - schema context - * @param path - * - binding path - * @return node container by binding path if exists,.empty otherwise - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static Optional findDataNodeContainer(final SchemaContext ctx, - final InstanceIdentifier path) { - final Iterator pathArguments = path.getPathArguments().iterator(); - TreeArgument currentArg = pathArguments.next(); - Preconditions.checkArgument(currentArg != null); - QName currentQName = BindingReflections.findQName(currentArg.getType()); - - Optional currentContainer; - if (BindingReflections.isNotification(currentArg.getType())) { - currentContainer = findNotification(ctx, currentQName); - } else if (BindingReflections.isOperationType(currentArg.getType())) { - currentContainer = findFirstDataNodeContainerInRpcOrAction(ctx, currentArg.getType()); - if(currentQName == null && currentContainer.isPresent()) { - currentQName = ((DataSchemaNode) currentContainer.get()).getQName(); - } - } else { - currentContainer = findDataNodeContainer(ctx, currentQName); - } - - while (currentContainer.isPresent() && pathArguments.hasNext()) { - currentArg = pathArguments.next(); - if (Augmentation.class.isAssignableFrom(currentArg.getType())) { - currentQName = BindingReflections.findQName(currentArg.getType()); - if(pathArguments.hasNext()) { - currentArg = pathArguments.next(); - } else { - return currentContainer; - } - } - if (TreeChildNode.class.isAssignableFrom(currentArg.getType()) - && BindingReflections.isAugmentationChild(currentArg.getType())) { - currentQName = BindingReflections.findQName(currentArg.getType()); - } else { - currentQName = QName.create(currentQName, BindingReflections.findQName(currentArg.getType()).getLocalName()); - } - final Optional potential = findDataNodeContainer(currentContainer.get(), currentQName); - if (potential.isPresent()) { - currentContainer = potential; - } else { - return Optional.empty(); - } - } - return currentContainer; - } - - private static Optional findNotification(final SchemaContext ctx, final QName notificationQName) { - for (final NotificationDefinition notification : ctx.getNotifications()) { - if (notification.getQName().equals(notificationQName)) { - return Optional.of(notification); - } - } - return Optional.empty(); - } - - private static Optional findDataNodeContainer(final DataNodeContainer ctx, - final QName targetQName) { - - for (final DataSchemaNode child : ctx.getChildNodes()) { - if (child instanceof ChoiceSchemaNode) { - final DataNodeContainer potential = findInCases((ChoiceSchemaNode) child, targetQName); - if (potential != null) { - return Optional.of(potential); - } - } else if (child instanceof DataNodeContainer && child.getQName().equals(targetQName)) { - return Optional.of((DataNodeContainer) child); - } else if (child instanceof DataNodeContainer // - && child.isAddedByUses() // - && child.getQName().getLocalName().equals(targetQName.getLocalName())) { - return Optional.of((DataNodeContainer) child); - } - - } - return Optional.empty(); - } - - private static DataNodeContainer findInCases(final ChoiceSchemaNode choiceNode, final QName targetQName) { - for (final CaseSchemaNode caze : choiceNode.getCases().values()) { - final Optional potential = findDataNodeContainer(caze, targetQName); - if (potential.isPresent()) { - return potential.get(); - } - } - return null; - } - - private static Optional findFirstDataNodeContainerInRpcOrAction(final SchemaContext ctx, - final Class targetType) { - final YangModuleInfo moduleInfo; - try { - moduleInfo = BindingReflections.getModuleInfo(targetType); - } catch (final Exception e) { - throw new IllegalArgumentException( - String.format("Failed to load module information for class %s", targetType), e); - } - Optional optional = null; - optional = findFirst(ctx.getOperations(), moduleInfo, targetType); - if (optional.isPresent()) { - return optional; - } else { - return findFirst(ctx.getActions(), moduleInfo, targetType); - } - } - - private static Optional findFirst(final Set operations, - final YangModuleInfo moduleInfo, final Class targetType) { - for (final OperationDefinition operation : operations) { - final String operationNamespace = operation.getQName().getNamespace().toString(); - final String operationRevision = operation.getQName().getRevision().map(Revision::toString).orElse(null); - if (moduleInfo.getNamespace().equals(operationNamespace) - && moduleInfo.getRevision().equals(operationRevision)) { - final Optional potential = findInputOutput(operation, targetType.getSimpleName()); - if(potential.isPresent()) { - return potential; - } - } - } - return Optional.empty(); - } - - private static Optional findInputOutput(final OperationDefinition operation, - final String targetType) { - final String operationName = - JavaIdentifierNormalizer.normalizeSpecificIdentifier(operation.getQName().getLocalName(), - JavaIdentifier.CLASS); - final String actionInputName = - new StringBuilder(operationName).append(BindingMapping.RPC_INPUT_SUFFIX).toString(); - final String actionOutputName = - new StringBuilder(operationName).append(BindingMapping.RPC_OUTPUT_SUFFIX).toString(); - if (targetType.equals(actionInputName)) { - return Optional.of(operation.getInput()); - } else if (targetType.equals(actionOutputName)) { - return Optional.of(operation.getOutput()); - } - return Optional.empty(); - } - - /** - * Find choice schema node in parent by binding class. - * - * @param parent - * - choice parent - * @param choiceClass - * - choice binding class - * @return choice schema node if exists,.empty() otherwise - */ - public static Optional findInstantiatedChoice(final DataNodeContainer parent, final Class choiceClass) { - return findInstantiatedChoice(parent, BindingReflections.findQName(choiceClass)); - } - - /** - * Find choice schema node in parent node by qname of choice. - * - * @param ctxNode - * - parent node - * @param choiceName - * - qname of choice - * @return choice schema node if exists,.empty() otherwise - */ - public static Optional findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) { - final DataSchemaNode potential = ctxNode.getDataChildByName(choiceName); - if (potential instanceof ChoiceSchemaNode) { - return Optional.of((ChoiceSchemaNode) potential); - } - - return Optional.empty(); - } - - /** - * Find choice case node in choice schema node. - * - * @param instantiatedChoice - * - choice - * @param originalDefinition - * - choice case - * @return choice case node if exists,.empty() otherwise - */ - public static Optional findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final CaseSchemaNode originalDefinition) { - final QName qname = originalDefinition.getQName(); - final CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(qname); - if (originalDefinition.equals(potential)) { - return Optional.of(potential); - } - if (potential != null) { - final SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential); - if (originalDefinition.equals(potentialRoot)) { - return Optional.of(potential); - } - } - // We try to find case by name, then lookup its root definition - // and compare it with original definition - // This solves case, if choice was inside grouping - // which was used in different module and thus namespaces are - // different, but local names are still same. - // - // Still we need to check equality of definition, because local name is not - // sufficient to uniquely determine equality of cases - for (CaseSchemaNode found : instantiatedChoice.findCaseNodes(qname.getLocalName())) { - if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(found))) { - return Optional.of(found); - } - } - return Optional.empty(); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassCustomizer.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassCustomizer.java deleted file mode 100644 index 456003e6d2..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassCustomizer.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import com.google.common.annotations.Beta; -import javassist.CtClass; - -/** - * Interface allowing customization of classes after loading. - */ -@Beta -public interface ClassCustomizer { - - /** - * Customize a class. - * - * @param cls - * - class to be customized - * @throws Exception - * - when a problem ensues - */ - void customizeClass(CtClass cls) throws Exception; -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassGenerator.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassGenerator.java deleted file mode 100644 index 1149d41002..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/ClassGenerator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import com.google.common.annotations.Beta; -import javassist.CannotCompileException; -import javassist.CtClass; - -/** - * Interface allowing generate new classes. - */ -@Beta -public interface ClassGenerator { - - /** - * Process class. - * - * @param baseClass - * - class to be generated - * @throws CannotCompileException - */ - void process(CtClass baseClass) throws CannotCompileException; -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtils.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtils.java deleted file mode 100644 index 41bfd6a05f..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtils.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import java.util.Collection; -import java.util.Map; -import java.util.WeakHashMap; -import javassist.CannotCompileException; -import javassist.ClassClassPath; -import javassist.ClassPath; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtField; -import javassist.CtMethod; -import javassist.LoaderClassPath; -import javassist.Modifier; -import javassist.NotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Users of this utility class are expected to synchronize on this instance it - * they need to ensure atomic operations on it. - */ -@Beta -public final class JavassistUtils { - - private static final Logger LOG = LoggerFactory.getLogger(JavassistUtils.class); - - private static final Map INSTANCES = new WeakHashMap<>(); - private final Map loaderClassPaths = new WeakHashMap<>(); - private final ClassPool classPool; - - private JavassistUtils(final ClassPool pool) { - classPool = requireNonNull(pool); - } - - /** - * Get a utility instance for a particular class pool. A new instance is - * created if this is a new pool. If an instance already exists, is is - * returned. - * - * @param pool - * - backing class pool - * @return shared utility instance for specified pool - */ - public static synchronized JavassistUtils forClassPool(final ClassPool pool) { - JavassistUtils ret = INSTANCES.get(requireNonNull(pool)); - if (ret == null) { - ret = new JavassistUtils(pool); - INSTANCES.put(pool, ret); - } - return ret; - } - - /** - * Generate and add method to class. - * - * @param baseClass - * - class for adding method - * @param methodReturnType - * - return type of method - * @param methodName - * - name of method - * @param methodParameter - * - parameter of method - * @param methodGenerator - * - method generator - * @throws CannotCompileException - */ - public void method(final CtClass baseClass, final Class methodReturnType, final String methodName, - final Class methodParameter, final MethodGenerator methodGenerator) throws CannotCompileException { - final CtClass[] pa = new CtClass[] { asCtClass(methodParameter) }; - final CtMethod method = new CtMethod(asCtClass(methodReturnType), methodName, pa, baseClass); - - methodGenerator.process(method); - baseClass.addMethod(method); - } - - /** - * Generate and add method to class. - * - * @param baseClass - * - class for adding method - * @param methodReturnType - * - return type of method - * @param methodName - * - name of method - * @param methodParameters - * - parameters of method - * @param methodGenerator - * - method generator - * @throws CannotCompileException - */ - public void method(final CtClass baseClass, final Class methodReturnType, final String methodName, - final Collection> methodParameters, final MethodGenerator methodGenerator) - throws CannotCompileException { - final CtClass[] pa = new CtClass[methodParameters.size()]; - - int i = 0; - for (final Class parameter : methodParameters) { - pa[i] = asCtClass(parameter); - ++i; - } - - final CtMethod method = new CtMethod(asCtClass(methodReturnType), methodName, pa, baseClass); - methodGenerator.process(method); - baseClass.addMethod(method); - } - - /** - * Generate and add static method to class. - * - * @param baseClass - * - class for adding method - * @param methodReturnType - * - return type of method - * @param methodName - * - name of method - * @param methodParameter - * - parameter of method - * @param methodGenerator - * - method generator - * @throws CannotCompileException - */ - public void staticMethod(final CtClass baseClass, final Class methodReturnType, final String methodName, - final Class methodParameter, final MethodGenerator methodGenerator) throws CannotCompileException { - final CtClass[] pa = new CtClass[] { asCtClass(methodParameter) }; - final CtMethod method = new CtMethod(asCtClass(methodReturnType), methodName, pa, baseClass); - methodGenerator.process(method); - baseClass.addMethod(method); - } - - /** - * Implement methods to class from other class. - * - * @param target - * - class for implementing methods - * @param source - * - source class of methods to be implemented in target - * @param methodGenerator - * - method generator - * @throws CannotCompileException - */ - public void implementMethodsFrom(final CtClass target, final CtClass source, final MethodGenerator methodGenerator) - throws CannotCompileException { - for (final CtMethod method : source.getMethods()) { - if (method.getDeclaringClass() == source) { - final CtMethod redeclaredMethod = new CtMethod(method, target, null); - methodGenerator.process(redeclaredMethod); - target.addMethod(redeclaredMethod); - } - } - } - - /** - * Generate and add class to global class pool. - * - * @param className - * - name of class - * @param classGenerator - * - class generator - * @return generated class - * @throws CannotCompileException - */ - public CtClass createClass(final String className, final ClassGenerator classGenerator) throws CannotCompileException { - final CtClass target = classPool.makeClass(className); - classGenerator.process(target); - return target; - } - - /** - * Generate and add class to global class pool with implemented interface. - * - * @param className - * - name of class - * @param superInterface - * - interface to be implemented to the class - * @param classGenerator - * - class generator - * @return generated class with interface - * @throws CannotCompileException - */ - public CtClass createClass(final String className, final CtClass superInterface, final ClassGenerator classGenerator) - throws CannotCompileException { - final CtClass target = classPool.makeClass(className); - implementsType(target, superInterface); - classGenerator.process(target); - return target; - } - - /** - * Instantiate a new class based on a prototype. The class is set to - * automatically prune. - * - * @param prototype - * - prototype class fully qualified name - * @param target - * - target class fully qualified name - * @param customizer - * - customization callback to be invoked on the new class - * @return An instance of the new class - * @throws NotFoundException - * - when the prototype class is not found - */ - public synchronized CtClass instantiatePrototype(final String prototype, final String target, - final ClassCustomizer customizer) throws NotFoundException { - final CtClass result = classPool.getAndRename(prototype, target); - - try { - customizer.customizeClass(result); - } catch (final Exception e) { - LOG.warn("Failed to customize {} from prototype {}", target, prototype, e); - result.detach(); - throw new IllegalStateException(String.format("Failed to instantiate prototype %s as %s", prototype, target), - e); - } - - result.stopPruning(false); - return result; - } - - /** - * Implements type to class. - * - * @param baseClass - * - class for implements interface - * @param superInterface - * - interface to be implemented - */ - public void implementsType(final CtClass baseClass, final CtClass superInterface) { - Preconditions.checkArgument(superInterface.isInterface(), "Supertype must be interface"); - baseClass.addInterface(superInterface); - } - - /** - * Get class from class pool. - * - * @param class1 - * - class for getting from class pool - * @return class - */ - public CtClass asCtClass(final Class class1) { - return get(this.classPool, class1); - } - - /** - * Create and add field to class. - * - * @param baseClass - * - class for adding field - * @param fieldName - * - name of field - * @param fieldType - * - type of field - * @return class of field - * @throws CannotCompileException - */ - public CtField field(final CtClass baseClass, final String fieldName, final Class fieldType) - throws CannotCompileException { - final CtField field = new CtField(asCtClass(fieldType), fieldName, baseClass); - field.setModifiers(Modifier.PUBLIC); - baseClass.addField(field); - return field; - } - - /** - * Create and add static field to class. - * - * @param baseClass - * - class for adding field - * @param fieldName - * - name of field - * @param fieldType - * - type of field - * @return class of field - * @throws CannotCompileException - */ - public CtField staticField(final CtClass baseClass, final String fieldName, final Class fieldType) - throws CannotCompileException { - return staticField(baseClass, fieldName, fieldType, null); - } - - /** - * Create and add static field to class. - * - * @param baseClass - * - class for adding field - * @param fieldName - * - name of field - * @param fieldType - * - type of field - * @param sourceGenerator - * - source generator - * @return class of field - * @throws CannotCompileException - */ - public CtField staticField(final CtClass baseClass, final String fieldName, final Class fieldType, - final SourceCodeGenerator sourceGenerator) throws CannotCompileException { - final CtField field = new CtField(asCtClass(fieldType), fieldName, baseClass); - field.setModifiers(Modifier.PUBLIC + Modifier.STATIC); - baseClass.addField(field); - - if (sourceGenerator != null) { - sourceGenerator.appendField(field, null); - } - - return field; - } - - /** - * Get class from pool. - * - * @param pool - * - class pool - * @param clazz - * - search class in class pool - * @return class if exists - */ - public CtClass get(final ClassPool pool, final Class clazz) { - try { - return pool.get(clazz.getName()); - } catch (final NotFoundException nfe1) { - appendClassLoaderIfMissing(clazz.getClassLoader()); - try { - return pool.get(clazz.getName()); - } catch (final NotFoundException nfe2) { - LOG.warn("Appending ClassClassPath for {}", clazz, nfe2); - pool.appendClassPath(new ClassClassPath(clazz)); - try { - return pool.get(clazz.getName()); - } catch (final NotFoundException e) { - LOG.warn("Failed to load class {} from pool {}", clazz, pool, e); - throw new IllegalStateException("Failed to load class", e); - } - } - } - } - - /** - * Append class to class pool if doesn't exist. - * - * @param loader - * - class loader of search class - */ - public synchronized void appendClassLoaderIfMissing(final ClassLoader loader) { - if (!loaderClassPaths.containsKey(loader)) { - final ClassPath ctLoader = new LoaderClassPath(loader); - classPool.appendClassPath(ctLoader); - loaderClassPaths.put(loader, ctLoader); - } - } - - /** - * Ensure if is class in class loader. - * - * @param child - * - search class - */ - public void ensureClassLoader(final Class child) { - appendClassLoaderIfMissing(child.getClassLoader()); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/MethodGenerator.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/MethodGenerator.java deleted file mode 100644 index 2258f1f615..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/MethodGenerator.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import com.google.common.annotations.Beta; -import javassist.CannotCompileException; -import javassist.CtMethod; - -/** - * Interface allowing generator new methods. - */ -@Beta -public interface MethodGenerator { - - /** - * Process method. - * - * @param method - * - method to be generated - * @throws CannotCompileException - */ - void process(CtMethod method) throws CannotCompileException; -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/SourceCodeGenerator.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/SourceCodeGenerator.java deleted file mode 100644 index 9c41f4cf43..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/SourceCodeGenerator.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import com.google.common.annotations.Beta; -import javassist.CtClass; -import javassist.CtField; -import javassist.CtMethod; - -/** - * Interface for a class that that generates readable source code for a runtime generated class. - * The appendField/appendMethod methods append source code to a temporary output. When outputGeneratedSource - * is called, the entire class source code is generated and outputted. - */ -@Beta -public interface SourceCodeGenerator { - - /** - * Appends the given class field and value to the temporary output. - */ - void appendField(CtField field, String value); - - /** - * Appends the given method and source code body to the temporary output. - */ - void appendMethod(CtMethod method, String code); - - /** - * Generates the full source code for the given class and outputs it. - */ - void outputGeneratedSource(CtClass ctClass); -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetter.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetter.java deleted file mode 100644 index 008d741d61..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetter.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.runtime.reflection; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -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.Field; -import java.util.Collections; -import java.util.Map; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -abstract class AugmentationFieldGetter { - - private static final Logger LOG = LoggerFactory.getLogger(AugmentationFieldGetter.class); - - private static final String AUGMENTATION_FIELD = "augmentation"; - - private static final AugmentationFieldGetter DUMMY = new AugmentationFieldGetter() { - @Override - protected Map>, Augmentation> getAugmentations(final Object input) { - return Collections.emptyMap(); - } - }; - - private static final AugmentationFieldGetter AUGMENTATION_HOLDER_GETTER = new AugmentationFieldGetter() { - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected Map>, Augmentation> getAugmentations(final Object input) { - return (Map) ((AugmentationHolder) input).augmentations(); - } - }; - - private static final LoadingCache, AugmentationFieldGetter> AUGMENTATION_GETTERS = - CacheBuilder.newBuilder().weakKeys().build(new AugmentationGetterLoader()); - - /** - * Retrieves augmentations from supplied object. - * - * @param input - * - input Data object, from which augmentations should be - * extracted - * @return Map of Augmentation class to augmentation - */ - protected abstract Map>, Augmentation> getAugmentations(final Object input); - - public static AugmentationFieldGetter getGetter(final Class clz) { - if (AugmentationHolder.class.isAssignableFrom(clz)) { - return AUGMENTATION_HOLDER_GETTER; - } - return AUGMENTATION_GETTERS.getUnchecked(clz); - } - - private static final class AugmentationGetterLoader extends CacheLoader, AugmentationFieldGetter> { - private static final MethodType GETTER_TYPE = MethodType.methodType(Map.class, Object.class); - private static final Lookup LOOKUP = MethodHandles.lookup(); - - @Override - public AugmentationFieldGetter load(final Class key) throws IllegalAccessException { - final Field field; - try { - field = key.getDeclaredField(AUGMENTATION_FIELD); - field.setAccessible(true); - } catch (NoSuchFieldException | SecurityException e) { - LOG.warn("Failed to acquire augmentation field {}, ignoring augmentations in class {}", - AUGMENTATION_FIELD, key, e); - return DUMMY; - } - if (!Map.class.isAssignableFrom(field.getType())) { - LOG.warn("Class {} field {} is not a Map, ignoring augmentations", key, - AUGMENTATION_FIELD); - return DUMMY; - } - - return new ReflectionAugmentationFieldGetter(LOOKUP.unreflectGetter(field).asType(GETTER_TYPE)); - } - } - - private static final class ReflectionAugmentationFieldGetter extends AugmentationFieldGetter { - private final MethodHandle fieldGetter; - - ReflectionAugmentationFieldGetter(final MethodHandle mh) { - this.fieldGetter = requireNonNull(mh); - } - - @Override - protected Map>, Augmentation> getAugmentations(final Object input) { - try { - return (Map>, Augmentation>) this.fieldGetter.invokeExact(input); - } catch (final Throwable e) { - throw new IllegalStateException("Failed to access augmentation field on " + input, e); - } - } - } -} diff --git a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflections.java b/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflections.java deleted file mode 100644 index 5e203f9d70..0000000000 --- a/binding2/mdsal-binding2-runtime/src/main/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflections.java +++ /dev/null @@ -1,667 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.reflection; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; - -import com.google.common.annotations.Beta; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.ServiceLoader; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity; -import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; -import org.opendaylight.mdsal.binding.javav2.spec.base.Operation; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModelBindingProvider; -import org.opendaylight.mdsal.binding.javav2.spec.runtime.YangModuleInfo; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.util.ClassLoaderUtils; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.common.QNameModule; -import org.opendaylight.yangtools.yang.common.Revision; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Beta -public final class BindingReflections { - - private static final Logger LOG = LoggerFactory.getLogger(BindingReflections.class); - - private static final long EXPIRATION_TIME = 60; - private static final String QNAME_STATIC_FIELD_NAME = "QNAME"; - private static final String OPERATION_ACTION_OUTPUT_SUFFIX = "Output"; - private static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl"; - private static final String PACKAGE_PREFIX = "org.opendaylight.mdsal.gen.javav2"; - private static final String ROOT_PACKAGE_PATTERN_STRING = - "(org.opendaylight.mdsal.gen.javav2.[a-z0-9_\\.]*\\.rev[0-9][0-9][0-1][0-9][0-3][0-9])"; - - private static final Pattern ROOT_PACKAGE_PATTERN = Pattern.compile(ROOT_PACKAGE_PATTERN_STRING); - - private static final LoadingCache, Optional> CLASS_TO_QNAME = CacheBuilder.newBuilder().weakKeys() - .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS).build(new ClassToQNameLoader()); - - private BindingReflections() { - throw new UnsupportedOperationException("Utility class."); - } - - /** - * Find augmentation target class from concrete Augmentation class - * - * This method uses first generic argument of implemented - * {@link Augmentation} interface. - * - * @param augmentation - * {@link Augmentation} subclass for which we want to determine - * augmentation target. - * @return Augmentation target - class which augmentation provides - * additional extensions. - */ - public static Class> findAugmentationTarget( - final Class> augmentation) { - return ClassLoaderUtils.findFirstGenericArgument(augmentation, Augmentation.class); - } - - /** - * Find data hierarchy parent from concrete Tree Node class - * - * This method uses first generic argument of implemented - * {@link TreeChildNode} interface. - * - * @param childClass - * - child class for which we want to find the parent class - * @return Parent class, e.g. class of which the childClass is ChildOf - */ - static Class findHierarchicalParent(final Class> childClass) { - return ClassLoaderUtils.findFirstGenericArgument(childClass, TreeChildNode.class); - } - - /** - * Returns a QName associated to supplied type - * - * @param dataType - * - type of data - * @return QName associated to supplied dataType. If dataType is - * Augmentation method does not return canonical QName, but QName - * with correct namespace revision, but virtual local name, since - * augmentations do not have name. - * - * May return null if QName is not present. - */ - public static QName findQName(final Class dataType) { - return CLASS_TO_QNAME.getUnchecked(dataType).orElse(null); - } - - /** - * Checks if method is RPC or Action invocation - * - * @param possibleMethod - * - method to check - * @return true if method is RPC or Action invocation, false otherwise. - */ - public static boolean isOperationMethod(final Method possibleMethod) { - return possibleMethod != null && Operation.class.isAssignableFrom(possibleMethod.getDeclaringClass()) - && Future.class.isAssignableFrom(possibleMethod.getReturnType()) - // length <= 2: it seemed to be impossible to get correct OperationMethodInvoker because of - // resolveOperationInputClass() check.While OperationMethodInvoker counts with one argument - // for - // non input type and two arguments for input type, resolveOperationInputClass() counting - // with zero for non input and one for input type - && possibleMethod.getParameterTypes().length <= 2; - } - - /** - * Extracts Output class for RPC method - * - * @param targetMethod - * method to scan - * @return Optional.empty() if result type could not be get, or return type - * is Void. - */ - @SuppressWarnings("rawtypes") - public static Optional> resolveOperationOutputClass(final Method targetMethod) { - checkState(isOperationMethod(targetMethod), "Supplied method is not a RPC or Action invocation method"); - final Type futureType = targetMethod.getGenericReturnType(); - final Type operationResultType = ClassLoaderUtils.getFirstGenericParameter(futureType); - final Type operationResultArgument = ClassLoaderUtils.getFirstGenericParameter(operationResultType); - if (operationResultArgument instanceof Class && !Void.class.equals(operationResultArgument)) { - return Optional.of((Class) operationResultArgument); - } - return Optional.empty(); - } - - /** - * Extracts input class for RPC or Action - * - * @param targetMethod - * - method to scan - * @return Optional.empty() if RPC or Action has no input, RPC input type - * otherwise. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Optional>> resolveOperationInputClass(final Method targetMethod) { - for (final Class clazz : targetMethod.getParameterTypes()) { - if (Instantiable.class.isAssignableFrom(clazz)) { - return Optional.of(clazz); - } - } - return Optional.empty(); - } - - /** - * Find qname of base identity context. - * - * @param context - * - base identity type context - * @return QName of base identity context - */ - public static QName getQName(final Class context) { - return findQName(context); - } - - /** - * Checks if class is child of augmentation. - * - * @param clazz - * - class to check - * @return true if is augmentation, false otherwise - */ - public static boolean isAugmentationChild(final Class clazz) { - // FIXME: Current resolver could be still confused when child node was - // added by grouping - checkArgument(clazz != null); - - @SuppressWarnings({ "rawtypes", "unchecked" }) - final Class parent = findHierarchicalParent((Class) clazz); - if (parent == null) { - LOG.debug("Did not find a parent for class {}", clazz); - return false; - } - - final String clazzModelPackage = getModelRootPackageName(clazz.getPackage()); - final String parentModelPackage = getModelRootPackageName(parent.getPackage()); - - return !clazzModelPackage.equals(parentModelPackage); - } - - /** - * Returns root package name for supplied package. - * - * @param pkg - * Package for which find model root package. - * @return Package of model root. - */ - public static String getModelRootPackageName(final Package pkg) { - return getModelRootPackageName(pkg.getName()); - } - - /** - * Returns root package name for supplied package name. - * - * @param name - * - package for which find model root package - * @return Package of model root - */ - public static String getModelRootPackageName(final String name) { - checkArgument(name != null, "Package name should not be null."); - checkArgument(name.startsWith(PACKAGE_PREFIX), "Package name not starting with %s, is: %s", PACKAGE_PREFIX, - name); - final Matcher match = ROOT_PACKAGE_PATTERN.matcher(name); - checkArgument(match.find(), "Package name '%s' does not match required pattern '%s'", name, - ROOT_PACKAGE_PATTERN_STRING); - return match.group(0); - } - - /** - * Get QName module of specific Binding object class. - * - * @param clz - * - class of binding object - * @return QName module of binding object - */ - public static final QNameModule getQNameModule(final Class clz) { - if (Instantiable.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) { - return findQName(clz).getModule(); - } - try { - final YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz); - return getQNameModule(modInfo); - } catch (final Exception e) { - throw new IllegalStateException("Unable to get QName of defining model.", e); - } - } - - /** - * Returns module QName. - * - * @param modInfo - * - module info - * @return {@link QNameModule} from module info - */ - public static final QNameModule getQNameModule(final YangModuleInfo modInfo) { - return QNameModule.create(URI.create(modInfo.getNamespace()), Revision.ofNullable(modInfo.getRevision())); - } - - /** - * Returns instance of {@link YangModuleInfo} of declaring model for - * specific class. - * - * @param cls - * - class for getting info - * @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 { - checkArgument(cls != null); - final String packageName = getModelRootPackageName(cls.getPackage()); - final String potentialClassName = getModuleInfoClassName(packageName); - return ClassLoaderUtils.callWithClassLoader(cls.getClassLoader(), () -> { - final Class moduleInfoClass = Thread.currentThread().getContextClassLoader().loadClass(potentialClassName); - return (YangModuleInfo) moduleInfoClass.getMethod("getInstance").invoke(null); - }); - } - - /** - * Returns name of module info class. - * - * @param packageName - * - package name - * @return name of module info class - */ - public static String getModuleInfoClassName(final String packageName) { - return packageName + "." + MODULE_INFO_CLASS_NAME; - } - - /** - * Check if supplied class is derived from YANG model. - * - * @param cls - * - class to check - * @return true if class is derived from YANG model. - */ - public static boolean isBindingClass(final Class cls) { - if (Instantiable.class.isAssignableFrom(cls) || Augmentation.class.isAssignableFrom(cls) - || TreeNode.class.isAssignableFrom(cls)) { - return true; - } - return cls.getName().startsWith(PACKAGE_PREFIX); - } - - /** - * Checks if supplied method is callback for notifications. - * - * @param method - * - method for check - * @return true if method is notification callback - */ - public static boolean isNotificationCallback(final Method method) { - checkArgument(method != null); - if (method.getName().startsWith("on") && method.getParameterTypes().length == 1) { - final Class potentialNotification = method.getParameterTypes()[0]; - if (isNotification(potentialNotification) - && method.getName().equals("on" + potentialNotification.getSimpleName())) { - return true; - } - } - return false; - } - - /** - * Check if supplied class is Notification. - * - * @param potentialNotification - * - class to check - * @return true if class is notification, false otherwise - */ - public static boolean isNotification(final Class potentialNotification) { - checkArgument(potentialNotification != null, "potentialNotification must not be null."); - return Notification.class.isAssignableFrom(potentialNotification); - } - - /** - * Loads {@link YangModuleInfo} info available on current classloader. - * - * This method is shorthand for {@link #loadModuleInfos(ClassLoader)} with - * {@link Thread#getContextClassLoader()} for current thread. - * - * @return Set of {@link YangModuleInfo} available for current classloader. - */ - public static ImmutableSet loadModuleInfos() { - return loadModuleInfos(Thread.currentThread().getContextClassLoader()); - } - - /** - * Loads {@link YangModuleInfo} info 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 - * recursively 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 loadModuleInfos(final ClassLoader loader) { - final Builder moduleInfoSet = ImmutableSet.builder(); - final ServiceLoader serviceLoader = ServiceLoader.load(YangModelBindingProvider.class, - loader); - for (final YangModelBindingProvider bindingProvider : serviceLoader) { - final YangModuleInfo moduleInfo = bindingProvider.getModuleInfo(); - checkState(moduleInfo != null, "Module Info for %s is not available.", bindingProvider.getClass()); - collectYangModuleInfo(bindingProvider.getModuleInfo(), moduleInfoSet); - } - return moduleInfoSet.build(); - } - - private static void collectYangModuleInfo(final YangModuleInfo moduleInfo, - final Builder moduleInfoSet) { - moduleInfoSet.add(moduleInfo); - for (final YangModuleInfo dependency : moduleInfo.getImportedModules()) { - collectYangModuleInfo(dependency, moduleInfoSet); - } - } - - /** - * Checks if supplied class represents RPC or Action input/output. - * - * @param targetType - * - class to be checked - * @return true if class represents RPC or Action input/output class - */ - public static boolean isOperationType(final Class targetType) { - return Instantiable.class.isAssignableFrom(targetType) && !TreeChildNode.class.isAssignableFrom(targetType) - && !Notification.class.isAssignableFrom(targetType) - && (targetType.getName().endsWith("Input") || targetType.getName().endsWith("Output")); - } - - /** - * 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 - */ - @SuppressWarnings("unchecked") - public static Iterable> getChildrenClasses(final Class> type) { - checkArgument(type != null, "Target type must not be null"); - checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable"); - final List> ret = new LinkedList<>(); - for (final Method method : type.getMethods()) { - final Optional>> entity = getYangModeledReturnType(method); - if (entity.isPresent()) { - ret.add((Class) entity.get()); - } - } - 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, Method> getChildrenClassToMethod(final Class type) { - checkArgument(type != null, "Target type must not be null"); - checkArgument(Instantiable.class.isAssignableFrom(type), "Supplied type must be derived from Instantiable"); - final Map, Method> ret = new HashMap<>(); - for (final Method method : type.getMethods()) { - final Optional>> entity = getYangModeledReturnType(method); - if (entity.isPresent()) { - ret.put(entity.get(), method); - } - } - return ret; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static Optional>> getYangModeledReturnType(final Method method) { - if ("getClass".equals(method.getName()) || !method.getName().startsWith("get") - || method.getParameterTypes().length > 0) { - return Optional.empty(); - } - - final Class returnType = method.getReturnType(); - if (Instantiable.class.isAssignableFrom(returnType)) { - return Optional.of(returnType); - } else if (List.class.isAssignableFrom(returnType)) { - try { - return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(), - (Callable>>>) () -> { - final Type listResult = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType()); - if (listResult instanceof Class - && Instantiable.class.isAssignableFrom((Class) listResult)) { - return Optional.of((Class) listResult); - } - return Optional.empty(); - }); - } catch (final 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. - */ - LOG.debug("Unable to find YANG modeled return type for {}", method, e); - } - } - return Optional.empty(); - } - - private static class ClassToQNameLoader extends CacheLoader, Optional> { - - @Override - public Optional load(@Nonnull final Class key) throws Exception { - return resolveQNameNoCache(key); - } - - /** - * Tries to resolve QName for supplied class. - * - * Looks up for static field with name from constant {@link #QNAME_STATIC_FIELD_NAME} and returns - * value if present. - * - * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types. - * - * @param key - * - class for resolving QName - * @return resolved QName - */ - private static Optional resolveQNameNoCache(final Class key) { - try { - final Field field = key.getField(QNAME_STATIC_FIELD_NAME); - final Object obj = field.get(null); - if (obj instanceof QName) { - return Optional.of((QName) obj); - } - - } catch (final NoSuchFieldException e) { - return Optional.of(computeQName(key)); - } 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. - */ - LOG.debug("Unexpected exception during extracting QName for {}", key, e); - } - return Optional.empty(); - } - - /** - * Computes QName for supplied class - * - * Namespace and revision are same as {@link YangModuleInfo} associated - * with supplied class. - *

    - * If class is - *

      - *
    • rpc/action input: local name is "input". - *
    • rpc/action output: local name is "output". - *
    • augmentation: local name is "module name". - *
    - * - * 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. - * - * @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)) { - YangModuleInfo moduleInfo; - try { - moduleInfo = getModuleInfo(key); - } catch (final Exception e) { - throw new IllegalStateException("Unable to get QName for " + key - + ". YangModuleInfo was not found.", e); - } - final QName module = getModuleQName(moduleInfo).intern(); - if (Augmentation.class.isAssignableFrom(key)) { - return module; - } else if (isOperationType(key)) { - final String className = key.getSimpleName(); - if (className.endsWith(OPERATION_ACTION_OUTPUT_SUFFIX)) { - return QName.create(module, "output").intern(); - } else { - return QName.create(module, "input").intern(); - } - } - /* - * Fallback for Binding types which do not have QNAME field - */ - return module; - } else { - 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. - * - * @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()); - } - - /** - * 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. - */ - public static Map>, Augmentation> getAugmentations(final Augmentable input) { - return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input); - } - - /** - * Determines if two augmentation classes or case classes represents same - * data. - *

    - * Two augmentations or cases could be substituted only if and if: - *

      - *
    • Both implements same interfaces
    • - *
    • Both have same children
    • - *
    • If augmentations: Both have same augmentation target class. Target - * class was generated for data node in grouping.
    • - *
    • If cases: Both are from same choice. Choice class was generated for - * data node in grouping.
    • - *
    - *

    - * Explanation: 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 substitution - * @param target - * - class which should be used at particular subtree - * @return true if and only if classes represents same data. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static boolean isSubstitutionFor(final Class potential, final Class target) { - Set subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces())); - Set targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces())); - if (!subImplemented.equals(targetImplemented)) { - return false; - } - if (Augmentation.class.isAssignableFrom(potential) - && !BindingReflections.findAugmentationTarget(potential).equals( - BindingReflections.findAugmentationTarget(target))) { - return false; - } - for (final Method potentialMethod : potential.getMethods()) { - try { - final Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes()); - if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) { - return false; - } - } catch (final NoSuchMethodException e) { - // Counterpart method is missing, so classes could not be - // substituted. - return false; - } catch (final SecurityException e) { - throw new IllegalStateException("Could not compare methods", e); - } - } - return true; - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContextTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContextTest.java deleted file mode 100644 index 65478e1085..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/BindingRuntimeContextTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.runtime.context; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class BindingRuntimeContextTest { - - private SchemaContext schemaContext; - private BindingRuntimeContext brc; - private DataNodeContainer myCont; - - @Before - public void setup() { - schemaContext = YangParserTestUtils.parseYangResource("/yang/test-runtime.yang"); - myCont = (DataNodeContainer) schemaContext.getChildNodes().iterator().next(); - brc = BindingRuntimeContext.create(GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy(), schemaContext); - } - - @Test - public void basicTest() { - assertNotNull(brc.getSchemaContext()); - assertNotNull(brc.getStrategy()); - assertNotNull(brc.getChoiceCaseChildren(myCont)); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContextTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContextTest.java deleted file mode 100644 index f2b20059fc..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/ModuleInfoBackedContextTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.runtime.context; - -import static org.junit.Assert.assertNotNull; - -import java.io.FileNotFoundException; -import java.net.URISyntaxException; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy; -import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException; - -public class ModuleInfoBackedContextTest { - - private ModuleInfoBackedContext moduleInfoBackedContext; - - @Before - public void setup() throws ReactorException, FileNotFoundException, URISyntaxException { - moduleInfoBackedContext = ModuleInfoBackedContext.create(); - } - - @Test - public void createTestWithStrategy() { - assertNotNull(ModuleInfoBackedContext.create( - GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy())); - } - - @Test(expected = ClassNotFoundException.class) - public void loadClassTest() throws ClassNotFoundException { - moduleInfoBackedContext.loadClass("org.opendaylight.mdsal.gen.javav2.test.rev990939.Dummy"); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtilsTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtilsTest.java deleted file mode 100644 index a2940d9595..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/context/util/BindingSchemaContextUtilsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.runtime.context.util; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.gen.javav2.org.test.runtime.rev170710.data.MyCont; -import org.opendaylight.mdsal.gen.javav2.org.test.runtime.rev170710.data.my_cont.MyChoice; -import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode; -import org.opendaylight.yangtools.yang.model.api.DataNodeContainer; -import org.opendaylight.yangtools.yang.model.api.SchemaContext; -import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; - -public class BindingSchemaContextUtilsTest { - - private SchemaContext schemaContext; - private DataNodeContainer myCont; - private ChoiceSchemaNode myChoice; - - private static final InstanceIdentifier MY_CONT_NODE_PATH - = InstanceIdentifier.create(MyCont.class); - - - @Before - public void setup() { - schemaContext = YangParserTestUtils.parseYangResource("/yang/test-runtime.yang"); - myCont = (DataNodeContainer) schemaContext.getChildNodes().iterator().next(); - myChoice = (ChoiceSchemaNode) myCont.getChildNodes().iterator().next(); - } - - @Test - public void utilTest() { - assertNotNull(BindingSchemaContextUtils.findDataNodeContainer(schemaContext, MY_CONT_NODE_PATH)); - assertNotNull(BindingSchemaContextUtils.findInstantiatedChoice(myCont, MyChoice.class)); - assertNotNull(BindingSchemaContextUtils.findInstantiatedCase(myChoice, myChoice.findCaseNodes("one") - .iterator().next())); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtilsTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtilsTest.java deleted file mode 100644 index e8b43f1d1e..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/javassist/JavassistUtilsTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.javassist; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; - -import com.google.common.collect.ImmutableList; -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtField; -import javassist.bytecode.AccessFlag; -import org.junit.Test; - -public class JavassistUtilsTest { - - @Test - public void forClassPool() throws Exception { - final JavassistUtils javassistUtils = JavassistUtils.forClassPool(ClassPool.getDefault()); - final ClassGenerator classGenerator = mock(ClassGenerator.class); - doNothing().when(classGenerator).process(any()); - final CtClass ctInterface = javassistUtils.createClass("TestInterface", classGenerator); - ctInterface.setModifiers(AccessFlag.INTERFACE); - final CtClass ctClass = javassistUtils.createClass("TestClass", ctInterface, classGenerator); - javassistUtils.ensureClassLoader(ctClass.getClass()); - assertNotNull(ctClass); - assertNotNull(javassistUtils.get(ClassPool.getDefault(), ctClass.getClass())); - - CtField ctField = javassistUtils.field(ctClass, "testField", Object.class); - assertEquals(ctField, ctClass.getField("testField")); - ctField = javassistUtils.staticField(ctClass, "testStaticField", Object.class); - assertEquals(ctField, ctClass.getField("testStaticField")); - - final MethodGenerator methodGenerator = mock(MethodGenerator.class); - doNothing().when(methodGenerator).process(any()); - javassistUtils.method(ctClass, Void.class, "testMethod", Object.class, methodGenerator); - javassistUtils.method(ctInterface, Void.class, "testInterfaceMethod", Object.class, methodGenerator); - javassistUtils.method(ctClass, Void.class, "testMethod2", ImmutableList.of(Object.class), methodGenerator); - javassistUtils.staticMethod(ctClass, Void.class, "testStaticMethod", Object.class, methodGenerator); - javassistUtils.implementMethodsFrom(ctClass, ctInterface, methodGenerator); - assertNotNull(ctClass.getDeclaredMethod("testMethod")); - assertNotNull(ctClass.getDeclaredMethod("testMethod2")); - assertNotNull(ctClass.getDeclaredMethod("testStaticMethod")); - assertNotNull(ctClass.getDeclaredMethod("testInterfaceMethod")); - - final ClassCustomizer classCustomizer = mock(ClassCustomizer.class); - doNothing().when(classCustomizer).customizeClass(any()); - assertNotNull(javassistUtils.instantiatePrototype("javassist.CtNewClass", "leWut", classCustomizer)); - } - - @Test - public void privateConstructTest() throws Exception { - assertFalse(JavassistUtils.class.getDeclaredConstructor(ClassPool.class).isAccessible()); - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetterTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetterTest.java deleted file mode 100644 index 1047b9338e..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/AugmentationFieldGetterTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.reflection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.opendaylight.mdsal.binding.javav2.runtime.reflection.AugmentationFieldGetter.getGetter; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder; - -public class AugmentationFieldGetterTest { - - @SuppressWarnings("rawtypes") - @Test - public void getGetterTest() throws Exception { - assertNotNull(getGetter(AugmentationHolder.class)); - assertTrue(getGetter(AugmentationHolder.class).getAugmentations(mock(AugmentationHolder.class)).isEmpty()); - assertTrue(getGetter(Object.class).getAugmentations(null).isEmpty()); - assertTrue(getGetter(TestAugmentationWrongTypeClass.class).getAugmentations(null).isEmpty()); - - final AugmentationFieldGetter augmentationFieldGetter = getGetter(TestAugmentationClass.class); - final Augmentation augmentation = mock(Augmentation.class); - final TestAugmentationClass testAugmentationClass = new TestAugmentationClass(); - - testAugmentationClass.addAugmentation(augmentation, augmentation); - assertNotNull(augmentationFieldGetter.getAugmentations(testAugmentationClass)); - assertEquals(1, augmentationFieldGetter.getAugmentations(testAugmentationClass).size()); - } - - @Test(expected = IllegalStateException.class) - public void getWrongGetterTest() throws Exception { - final AugmentationFieldGetter augmentationFieldGetter = getGetter(TestAugmentationClass.class); - augmentationFieldGetter.getAugmentations(""); - fail("Expected IllegalStateException"); - } - - @Test - public void getNoGetterTest() throws Exception { - assertTrue(getGetter(Object.class).getAugmentations(null).isEmpty()); - } - - private final class TestAugmentationClass { - @SuppressWarnings("rawtypes") - private final Map augmentation = new HashMap(); - - @SuppressWarnings({ "rawtypes", "unchecked" }) - void addAugmentation(final Augmentation key, final Augmentation value) { - this.augmentation.put(key, value); - } - } - - private final class TestAugmentationWrongTypeClass { - @SuppressWarnings("unused") - private String augmentation; - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflectionsTest.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflectionsTest.java deleted file mode 100644 index 66c8cc5e4b..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/BindingReflectionsTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.reflection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -import java.lang.reflect.Constructor; -import java.util.List; -import java.util.concurrent.Future; -import org.junit.Test; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.test.mock.FooChild; -import org.opendaylight.mdsal.binding.javav2.runtime.reflection.test.mock.GroupingFoo; -import org.opendaylight.mdsal.binding.javav2.spec.base.BaseIdentity; -import org.opendaylight.mdsal.binding.javav2.spec.base.Input; -import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc; -import org.opendaylight.mdsal.binding.javav2.spec.base.RpcCallback; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.yang.common.QName; - -public class BindingReflectionsTest { - - @Test - public void testBindingWithDummyObject() throws Exception { - assertEquals("Package name should be equal to string", "org.opendaylight.mdsal.gen.javav2.test.rev990939", - BindingReflections.getModelRootPackageName("org.opendaylight.mdsal.gen.javav2.test.rev990939")); - assertEquals("ModuleInfoClassName should be equal to string", "test.$YangModuleInfoImpl", - BindingReflections.getModuleInfoClassName("test")); - assertFalse("Should not be RpcType", BindingReflections.isOperationType(TreeNode.class)); - assertFalse("Should not be AugmentationChild", BindingReflections.isAugmentationChild(TreeNode.class)); - assertTrue("Should be BindingClass", BindingReflections.isBindingClass(TreeNode.class)); - assertFalse("Should not be Notification", BindingReflections.isNotification(TreeNode.class)); - - assertNull(mock(TreeChildNode.class).treeParent()); - - assertEquals(GroupingFoo.class, BindingReflections.findHierarchicalParent(FooChild.class)); - - assertTrue(BindingReflections.isOperationMethod(TestImplementation.class.getDeclaredMethod("rpcMethodTest"))); - assertEquals(TestImplementation.class, BindingReflections.findAugmentationTarget(TestImplementation.class)); - - assertEquals(Object.class, BindingReflections - .resolveOperationOutputClass(TestImplementation.class.getDeclaredMethod("rpcMethodTest")).get()); - assertFalse(BindingReflections - .resolveOperationOutputClass(TestImplementation.class.getDeclaredMethod("rpcMethodTest2")).isPresent()); - - assertTrue(BindingReflections.getQName(TestImplementation.class).toString().equals("()test")); - assertNotNull(BindingReflections.getQNameModule(TestImplementation.class)); - } - - @SuppressWarnings("rawtypes") - @Test(expected = UnsupportedOperationException.class) - public void testPrivateConstructor() throws Throwable { - assertFalse(BindingReflections.class.getDeclaredConstructor().isAccessible()); - final Constructor constructor = BindingReflections.class.getDeclaredConstructor(); - constructor.setAccessible(true); - try { - constructor.newInstance(); - } catch (final Exception e) { - throw e.getCause(); - } - } - - @SuppressWarnings({ "rawtypes", "unused" }) - private static final class TestImplementation - implements Augmentation, Rpc, BaseIdentity { - - public static final QName QNAME = QName.create("", "test"); - - Future> rpcMethodTest() { - return null; - } - - Future rpcMethodTest2() { - return null; - } - - @Override - public void invoke(final Input input, final RpcCallback callback) { - } - } -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/FooChild.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/FooChild.java deleted file mode 100644 index ae7f2dbaed..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/FooChild.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.reflection.test.mock; - -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; - -public interface FooChild extends TreeChildNode> { - -} diff --git a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/GroupingFoo.java b/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/GroupingFoo.java deleted file mode 100644 index 91edfc21c3..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/java/org/opendaylight/mdsal/binding/javav2/runtime/reflection/test/mock/GroupingFoo.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.runtime.reflection.test.mock; - -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -public interface GroupingFoo extends TreeNode { - -} diff --git a/binding2/mdsal-binding2-runtime/src/test/resources/yang/test-runtime.yang b/binding2/mdsal-binding2-runtime/src/test/resources/yang/test-runtime.yang deleted file mode 100644 index 36526bd156..0000000000 --- a/binding2/mdsal-binding2-runtime/src/test/resources/yang/test-runtime.yang +++ /dev/null @@ -1,22 +0,0 @@ -module test-runtime { - namespace "org.test.runtime"; - prefix "tst"; - revision "2017-07-10" { - } - - container my-cont { - choice my-choice { - case one { - leaf one { - type string; - } - } - case two { - leaf two { - type string; - } - } - - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/pom.xml b/binding2/mdsal-binding2-spec/pom.xml deleted file mode 100644 index f2736f7b34..0000000000 --- a/binding2/mdsal-binding2-spec/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-spec - ${project.artifactId} - Java Binding for YANG - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.yangtools - concepts - - - org.opendaylight.yangtools - util - - - org.opendaylight.yangtools - yang-common - - - org.opendaylight.yangtools - yang-model-api - - - com.google.guava - guava - - - diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Action.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Action.java deleted file mode 100644 index 624641c98b..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Action.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -/** - * - * The "action" statement is used to define an operation connected to a - * specific container or list data node. The "action" statement defines - * an action node in the schema tree. Under the action node, a schema node - * with the name "input" and a schema node with the name "output" are also - * defined. The nodes "input" and "output" are defined in the module’s namespace. - * - * The difference between an action and an rpc is that an action is tied - * to a node in the datastore, whereas an rpc is not. - * - * Action replaces concept of routed RPC and comes up with implicit InstanceIdentifier - * context, whereas routed RPC defines explicit leaf for this purpose. - * - */ -@FunctionalInterface -public interface Action

    , I extends Input & Instantiable, - O extends Output & Instantiable> extends Operation { - - /** - * @param input Action input schema node - * @param ii implicit InstanceIdentifier connected to action, according to https://tools.ietf.org/html/rfc7950 - * @param callback on success/failure callback - */ - void invoke(I input, D ii, RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/BaseIdentity.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/BaseIdentity.java deleted file mode 100644 index 2785dc9af1..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/BaseIdentity.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -/** - * Base Identity interface - * - */ -public interface BaseIdentity { -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/IdentifiableItem.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/IdentifiableItem.java deleted file mode 100644 index 9928032175..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/IdentifiableItem.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; - -/** - * An IdentifiableItem represents a object that is usually present in a collection and can be - * identified uniquely by a key. In YANG terms this would probably represent an item in a list. - * - * @param An object that is identifiable by an identifier - * @param The identifier of the object - */ -@Beta -public final class IdentifiableItem extends TreeArgument { - private final Class type; - private final T key; - - public IdentifiableItem(final Class type, final T key) { - this.type = requireNonNull(type); - this.key = requireNonNull(key, "Key may not be null."); - } - - @Override - public Class getType() { - return type; - } - - public T getKey() { - return this.key; - } - - @Override - public boolean equals(final Object obj) { - return super.equals(obj) && key.equals(((IdentifiableItem) obj).getKey()); - } - - @Override - public int hashCode() { - return super.hashCode() * 31 + key.hashCode(); - } - - @Override - public String toString() { - return type.getName() + "[key=" + key + "]"; - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Input.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Input.java deleted file mode 100644 index c6ef2cc6be..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Input.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -@Beta -public interface Input> { - - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifier.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifier.java deleted file mode 100644 index b0fe028e51..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifier.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableCollection; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.concepts.Immutable; -import org.opendaylight.yangtools.concepts.Path; -import org.opendaylight.yangtools.util.HashCodeBuilder; - -/** - * - * This instance identifier uniquely identifies a specific TreeNode in the data tree modeled by - * YANG. - * - * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG - * as follows, - * - *

    - * module opendaylight-inventory {
    - *      ....
    - *
    - *      container nodes {
    - *        list node {
    - *            key "id";
    - *            ext:context-instance "node-context";
    - *
    - *            uses node;
    - *        }
    - *    }
    - *
    - * }
    - * 
    - * - * You could create an instance identifier as follows to get to a node with id "openflow:1" - * - * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new - * NodeId("openflow:1")).build(); - * - * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the - * openflow:1 node - * - */ -@Beta -public class InstanceIdentifier implements Path>, Immutable, - Serializable { - private static final Field PATHARGUMENTS_FIELD; - private static final long serialVersionUID = 2L; - /* - * Protected to differentiate internal and external access. Internal - * access is required never to modify the contents. References passed - * to outside entities have to be wrapped in an unmodifiable view. - */ - protected transient final Iterable pathArguments; - private final Class targetType; - private final boolean wildcarded; - private final int hash; - - static { - final Field f; - try { - f = InstanceIdentifier.class.getDeclaredField("pathArguments"); - } catch (NoSuchFieldException | SecurityException e) { - throw new ExceptionInInitializerError(e); - } - f.setAccessible(true); - PATHARGUMENTS_FIELD = f; - } - - InstanceIdentifier(final Class type, final Iterable pathArguments, final boolean wildcarded, final int hash) { - this.pathArguments = requireNonNull(pathArguments); - this.targetType = requireNonNull(type); - this.wildcarded = wildcarded; - this.hash = hash; - } - - /** - * Return the type of data which this InstanceIdentifier identifies. - * - * @return Target type - */ - public final Class getTargetType() { - return targetType; - } - - /** - * Return the path argument chain which makes up this instance identifier. - * - * @return Path argument chain. Immutable and does not contain nulls. - */ - public final Iterable getPathArguments() { - return Iterables.unmodifiableIterable(pathArguments); - } - - /** - * Check whether an instance identifier contains any wildcards. A wildcard - * is an path argument which has a null key. - * - * @return true if any of the path arguments has a null key. - */ - public final boolean isWildcarded() { - return wildcarded; - } - - @Override - public final int hashCode() { - return hash; - } - - @Override - public final boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - - final InstanceIdentifier other = (InstanceIdentifier) obj; - if (pathArguments == other.pathArguments) { - return true; - } - - /* - * We could now just go and compare the pathArguments, but that - * can be potentially expensive. Let's try to avoid that by - * checking various things that we have cached from pathArguments - * and trying to prove the identifiers are *not* equal. - */ - if (hash != other.hash) { - return false; - } - if (wildcarded != other.wildcarded) { - return false; - } - if (targetType != other.targetType) { - return false; - } - if (fastNonEqual(other)) { - return false; - } - - // Everything checks out so far, so we have to do a full equals - return Iterables.elementsEqual(pathArguments, other.pathArguments); - } - - /** - * Perform class-specific fast checks for non-equality. This allows - * subclasses to avoid iterating over the pathArguments by performing - * quick checks on their specific fields. - * - * @param other The other identifier, guaranteed to be the same class - * @return true if the other identifier cannot be equal to this one. - */ - protected boolean fastNonEqual(final InstanceIdentifier other) { - return false; - } - - @Override - public final String toString() { - return addToStringAttributes(MoreObjects.toStringHelper(this)).toString(); - } - - /** - * Add class-specific toString attributes. - * - * @param toStringHelper ToStringHelper instance - * @return ToStringHelper instance which was passed in - */ - protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) { - return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(pathArguments)); - } - - /** - * Return an instance identifier trimmed at the first occurrence of a - * specific component type. - * - * For example let's say an instance identifier was built like so, - *
    -     *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
    -     * 
    - * - * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so, - * - *
    -     *      identifier.firstIdentifierOf(Nodes.class)
    -     * 
    - * - * @param type component type - * @return trimmed instance identifier, or null if the component type - * is not present. - */ - public final InstanceIdentifier firstIdentifierOf(final Class type) { - int i = 1; - for (final TreeArgument a : pathArguments) { - if (type.equals(a.getType())) { - @SuppressWarnings("unchecked") - final InstanceIdentifier ret = (InstanceIdentifier) internalCreate(Iterables.limit(pathArguments, i)); - return ret; - } - - ++i; - } - - return null; - } - - /** - * Return the key associated with the first component of specified type in - * an identifier. - * - * @param listItem component type - * @param listKey component key type - * @return key associated with the component, or null if the component type - * is not present. - * - * @deprecated Use {@link #firstKeyOf(Class)} instead. - */ - @Deprecated - public final K firstKeyOf(final Class listItem, - final Class listKey) { - return firstKeyOf(listItem); - } - - /** - * Return the key associated with the first component of specified type in - * an identifier. - * - * @param listItem component type - * @return key associated with the component, or null if the component type - * is not present. - */ - - public final K firstKeyOf(final Class listItem) { - for (final TreeArgument i : pathArguments) { - if (listItem.equals(i.getType())) { - @SuppressWarnings("unchecked") - final K ret = ((IdentifiableItem)i).getKey(); - return ret; - } - } - - return null; - } - - /** - * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all - * PathArguments to match exactly, e.g. - * - * - * The contains method checks if the other identifier is fully contained within the current identifier. It does this - * by looking at only the types of the path arguments and not by comparing the path arguments themselves. - * - * To illustrate here is an example which explains the working of this API. - * - * Let's say you have two instance identifiers as follows, - * - * this = /nodes/node/openflow:1 - * other = /nodes/node/openflow:2 - * - * then this.contains(other) will return false. - * - * @param other - * @return - */ - @Override - public final boolean contains(final InstanceIdentifier other) { - requireNonNull(other, "other should not be null"); - - final Iterator lit = pathArguments.iterator(); - final Iterator oit = other.pathArguments.iterator(); - - while (lit.hasNext()) { - if (!oit.hasNext()) { - return false; - } - - if (!lit.next().equals(oit.next())) { - return false; - } - } - - return true; - } - - /** - * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar - * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their - * non-wildcarded PathArgument counterpart. - * - * @param other Identifier which should be checked for inclusion. - * @return true if this identifier contains the other object - */ - public final boolean containsWildcarded(final InstanceIdentifier other) { - requireNonNull(other, "other should not be null"); - - final Iterator lit = pathArguments.iterator(); - final Iterator oit = other.pathArguments.iterator(); - - while (lit.hasNext()) { - if (!oit.hasNext()) { - return false; - } - - final TreeArgument la = lit.next(); - final TreeArgument oa = oit.next(); - - if (!la.getType().equals(oa.getType())) { - return false; - } - if (la instanceof IdentifiableItem && oa instanceof IdentifiableItem && !la.equals(oa)) { - return false; - } - } - - return true; - } - - /** - * Create a builder rooted at this key. - * - * @return A builder instance - */ - public InstanceIdentifierBuilder builder() { - return new InstanceIdentifierBuilderImpl(new Item(targetType), pathArguments, hash, isWildcarded()); - } - - private InstanceIdentifier childIdentifier(final TreeArgument arg) { - return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded()); - } - - @SuppressWarnings("unchecked") - public final > InstanceIdentifier child(final Class container) { - final TreeArgument arg = new Item<>(container); - return (InstanceIdentifier) childIdentifier(arg); - } - - @SuppressWarnings("unchecked") - public final , K> KeyedInstanceIdentifier child( - final Class listItem, final K listKey) { - final TreeArgument arg = new IdentifiableItem<>(listItem, listKey); - return (KeyedInstanceIdentifier) childIdentifier(arg); - } - - @SuppressWarnings("unchecked") - public final > InstanceIdentifier augmentation( - final Class container) { - final TreeArgument arg = new Item<>(container); - return (InstanceIdentifier) childIdentifier(arg); - } - - @Deprecated - private List legacyCache; - - /** - * @deprecated Use {@link #getPathArguments()} instead. - */ - @Deprecated - public final List getPath() { - if (legacyCache == null) { - legacyCache = ImmutableList.copyOf(pathArguments); - } - - return legacyCache; - } - - /** - * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier - * - * @param base - * @param - * @return - * - * @deprecated Use {@link #builder()} instead. - */ - @Deprecated - public static InstanceIdentifierBuilder builder(final InstanceIdentifier base) { - return base.builder(); - } - - /** - * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container - * - * @param container - * @param - * @return - */ - public static > InstanceIdentifierBuilder builder( - final Class container) { - return new InstanceIdentifierBuilderImpl().addNode(container); - } - - /** - * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem - * - * @param listItem - * @param listKey - * @param - * @param - * @return - */ - - public static , K> InstanceIdentifierBuilder builder( - final Class listItem, final K listKey) { - return new InstanceIdentifierBuilderImpl().addNode(listItem, listKey); - } - - /** - * Create an instance identifier for a very specific object type. This method - * implements {@link #create(Iterable)} semantics, except it is used by internal - * callers, which have assured that the argument is an immutable Iterable. - * - * - * @param pathArguments The path to a specific node in the data tree - * @return InstanceIdentifier instance - * @throws IllegalArgumentException if pathArguments is empty or - * contains a null element. - */ - private static InstanceIdentifier internalCreate(final Iterable pathArguments) { - final Iterator it = requireNonNull(pathArguments, "pathArguments may not be null").iterator(); - final HashCodeBuilder hashBuilder = new HashCodeBuilder<>(); - boolean wildcard = false; - TreeArgument a = null; - - while (it.hasNext()) { - a = it.next(); - Preconditions.checkArgument(a != null, "pathArguments may not contain null elements"); - - // TODO: sanity check ChildTreeNode<>; - hashBuilder.addArgument(a); - - if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem)) { - wildcard = true; - } - } - Preconditions.checkArgument(a != null, "pathArguments may not be empty"); - - return trustedCreate(a, pathArguments, hashBuilder.build(), wildcard); - } - - /** - * Create an instance identifier for a very specific object type. - * - * Example - *
    -     *  List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
    -     *  new InstanceIdentifier(path);
    -     * 
    - * - * @param pathArguments The path to a specific node in the data tree - * @return InstanceIdentifier instance - * @throws IllegalArgumentException if pathArguments is empty or - * contains a null element. - */ - public static InstanceIdentifier create(final Iterable pathArguments) { - if (pathArguments instanceof ImmutableCollection) { - @SuppressWarnings("unchecked") - final Iterable immutableArguments = (Iterable) pathArguments; - return internalCreate(immutableArguments); - } else { - return internalCreate(ImmutableList.copyOf(pathArguments)); - } - } - - /** - * Create an instance identifier for a very specific object type. - * - * For example - *
    -     *      new InstanceIdentifier(Nodes.class)
    -     * 
    - * would create an InstanceIdentifier for an object of type Nodes - * - * @param type The type of the object which this instance identifier represents - * @return InstanceIdentifier instance - */ - @SuppressWarnings("unchecked") - public static InstanceIdentifier create(final Class type) { - return (InstanceIdentifier) create(Collections. singletonList(new Item<>(type))); - } - - /** - * Return the key associated with the last component of the specified identifier. - * - * @param id instance identifier - * @return key associated with the last component - * @throws IllegalArgumentException if the supplied identifier type cannot have a key. - * @throws NullPointerException if id is null. - */ - - public static K keyOf( - final InstanceIdentifier id) { - requireNonNull(id); - Preconditions.checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id); - - @SuppressWarnings("unchecked") - final K ret = ((KeyedInstanceIdentifier)id).getKey(); - return ret; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - static InstanceIdentifier trustedCreate(final TreeArgument arg, final Iterable pathArguments, final int hash, boolean wildcarded) { - if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) { - Object key = null; - if (arg instanceof IdentifiableItem) { - key = ((IdentifiableItem) arg).getKey(); - } else { - wildcarded = true; - } - - return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key); - } else { - return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash); - } - } - - private void writeObject(final java.io.ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeInt(Iterables.size(pathArguments)); - for (Object o : pathArguments) { - out.writeObject(o); - } - } - - private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - - final int size = in.readInt(); - final List args = new ArrayList<>(size); - for (int i = 0; i < size; ++i) { - args.add((TreeArgument) in.readObject()); - } - - try { - PATHARGUMENTS_FIELD.set(this, ImmutableList.copyOf(args)); - } catch (IllegalArgumentException | IllegalAccessException e) { - throw new IOException(e); - } - } -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilder.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilder.java deleted file mode 100644 index d7fa902013..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilder.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.concepts.Builder; - -@Beta -public interface InstanceIdentifierBuilder extends Builder> { - /** - * Append the specified container as a child of the current InstanceIdentifier referenced by the - * builder. - * - * This method should be used when you want to build an instance identifier by appending - * top-level elements - * - * Example, - * - *
    -     * InstanceIdentifier.builder().child(Nodes.class).build();
    -     *
    -     * 
    - * - * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has - * been deprecated and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead - * - * @param container - * @param - * @return - */ - // FIXME: Why TreeNode needs to be explicitly mentioned, whern ChildTreeNode is derived from - // TreeNode? - >> InstanceIdentifierBuilder child(Class container); - - /** - * Append the specified listItem as a child of the current InstanceIdentifier referenced by the - * builder. - * - * This method should be used when you want to build an instance identifier by appending a - * specific list element to the identifier - * - * @param listItem - * @param listKey - * @param - * @param - * @return - */ - , K> InstanceIdentifierBuilder child(Class listItem, K listKey); - - /** - * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier - * referenced by the builder - * - * @param container - * @param - * @return - */ - > InstanceIdentifierBuilder augmentation(Class container); - - /** - * Build the instance identifier. - * - * @return - */ - @Override - InstanceIdentifier build(); - - /* - * @deprecated use #build() - */ - @Deprecated - InstanceIdentifier toInstance(); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilderImpl.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilderImpl.java deleted file mode 100644 index 2a5b270125..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/InstanceIdentifierBuilderImpl.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import java.util.Objects; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.util.HashCodeBuilder; - -@Beta -final class InstanceIdentifierBuilderImpl - implements InstanceIdentifierBuilder { - private final ImmutableList.Builder pathBuilder = ImmutableList.builder(); - private final HashCodeBuilder hashBuilder; - private final Iterable basePath; - private boolean wildcard = false; - private TreeArgument arg = null; - - InstanceIdentifierBuilderImpl() { - this.hashBuilder = new HashCodeBuilder<>(); - this.basePath = null; - } - - InstanceIdentifierBuilderImpl(final TreeArgument item, final Iterable pathArguments, final int hash, final boolean wildcard) { - this.hashBuilder = new HashCodeBuilder<>(hash); - this.basePath = pathArguments; - this.wildcard = wildcard; - this.arg = item; - } - - @Override - public int hashCode() { - return hashBuilder.build(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof InstanceIdentifierBuilderImpl) { - InstanceIdentifierBuilderImpl otherBuilder = (InstanceIdentifierBuilderImpl) obj; - return wildcard == otherBuilder.wildcard && - Objects.equals(basePath, otherBuilder.basePath) && - Objects.equals(arg, otherBuilder.arg) && - Objects.equals(hashBuilder.build(), otherBuilder.hashBuilder.build()); - } - return false; - } - - @SuppressWarnings("unchecked") - InstanceIdentifierBuilderImpl addNode(final Class container) { - arg = new Item(container); - hashBuilder.addArgument(arg); - pathBuilder.add(arg); - - if (Identifiable.class.isAssignableFrom(container)) { - wildcard = true; - } - - return (InstanceIdentifierBuilderImpl) this; - } - - @SuppressWarnings("unchecked") - InstanceIdentifierBuilderImpl addNode( - final Class listItem, final K listKey) { - arg = new IdentifiableItem(listItem, listKey); - hashBuilder.addArgument(arg); - pathBuilder.add(arg); - return (InstanceIdentifierBuilderImpl) this; - } - - @Override - public >> InstanceIdentifierBuilderImpl child( - final Class container) { - return addNode(container); - } - - @Override - public , K> InstanceIdentifierBuilderImpl child( - final Class listItem, final K listKey) { - return addNode(listItem, listKey); - } - - /** - * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by - * the builder - * - * @param container - * @param - * @return - */ - @Override - public > InstanceIdentifierBuilderImpl augmentation( - final Class container) { - return addNode(container); - } - - @Override - public InstanceIdentifier build() { - Preconditions.checkState(arg != null, "No path arguments present"); - - final Iterable pathArguments; - if (basePath == null) { - pathArguments = pathBuilder.build(); - } else { - pathArguments = Iterables.concat(basePath, pathBuilder.build()); - } - - @SuppressWarnings("unchecked") - final InstanceIdentifier ret = (InstanceIdentifier) InstanceIdentifier.trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard); - return ret; - } - - /* - * @deprecated Use #build() instead. - */ - @Override - @Deprecated - public InstanceIdentifier toInstance() { - return build(); - } -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Instantiable.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Instantiable.java deleted file mode 100644 index 93ae7a5e4c..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Instantiable.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -/** - * Represents instantiable data object such as input / output, data tree items. - * - * @param Final interface which is instantiable and extends this interface - */ - -@Beta -public interface Instantiable> { - - // REPLACES: DataObject#getImplementedInterface() - Class implementedInterface(); - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Item.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Item.java deleted file mode 100644 index 1e0a12f527..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Item.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; - -/** - * An Item represents an object that probably is only one of it's kind. For example a Nodes object - * is only one of a kind. In YANG terms this would probably represent a container. - * - * @param - */ - -@Beta -public final class Item extends TreeArgument { - private final Class type; - - public Item(final Class type) { - this.type = requireNonNull(type); - } - - @Override - public Class getType() { - return type; - } - - @Override - public String toString() { - return type.getName(); - } - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/KeyedInstanceIdentifier.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/KeyedInstanceIdentifier.java deleted file mode 100644 index 3d0c535146..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/KeyedInstanceIdentifier.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -/** - * An {@link InstanceIdentifier}, which has a list key attached at its last path - * element. - * - * @param Target data type - * @param Target key type - */ - -@Beta -public class KeyedInstanceIdentifier extends InstanceIdentifier { - private static final long serialVersionUID = 1L; - private final K key; - - KeyedInstanceIdentifier(final Class type, final Iterable pathArguments, final boolean wildcarded, final int hash, final K key) { - super(type, pathArguments, wildcarded, hash); - this.key = key; - } - - /** - * Return the key attached to this identifier. This method is equivalent to - * calling {@link InstanceIdentifier#keyOf(InstanceIdentifier)}. - * - * @return Key associated with this instance identifier. - */ - public final K getKey() { - return key; - } - - @Override - public final InstanceIdentifierBuilder builder() { - return new InstanceIdentifierBuilderImpl(new IdentifiableItem(getTargetType(), key), pathArguments, - hashCode(), isWildcarded()); - } - - @Override - protected boolean fastNonEqual(final InstanceIdentifier other) { - final KeyedInstanceIdentifier kii = (KeyedInstanceIdentifier) other; - - /* - * We could do an equals() here, but that may actually be expensive. - * equals() in superclass falls back to a full compare, which will - * end up running that equals anyway, so do not bother here. - */ - return (key == null) != (kii.key == null); - } -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/ListAction.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/ListAction.java deleted file mode 100644 index 71bdefd281..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/ListAction.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import org.opendaylight.yangtools.concepts.Identifier; - -/** - * - * ListAction provides support for YANG actions defined under List statement. - * - * The "action" statement is used to define an operation connected to a - * specific container or list data node. The "action" statement defines - * an action node in the schema tree. Under the action node, a schema node - * with the name "input" and a schema node with the name "output" are also - * defined. The nodes "input" and "output" are defined in the module’s namespace. - * - * The difference between an action and an rpc is that an action is tied - * to a node in the datastore, whereas an rpc is not. - * - * Action replaces concept of routed RPC and comes up with implicit InstanceIdentifier - * context, whereas routed RPC defines explicit leaf for this purpose. - * - */ -@FunctionalInterface -public interface ListAction

    & Instantiable, - O extends Output & Instantiable> extends Action, I, O> { - - /** - * @param input Action input schema node - * @param kii implicit KeyedInstanceIdentifier connected to action, according to https://tools.ietf.org/html/rfc7950 - * @param callback on success/failure callback - */ - void invoke(I input, KeyedInstanceIdentifier kii, RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Notification.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Notification.java deleted file mode 100644 index 4e147e7453..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Notification.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -/** - * Marker interface for YANG-defined notifications - * - * - */ -@Beta -public interface Notification> { - -} - diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Operation.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Operation.java deleted file mode 100644 index 4b2d5f5ae2..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Operation.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -/** - * Marker interface for tagging operations - RPC, Action and ListAction. - */ -@Beta -public interface Operation { - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Output.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Output.java deleted file mode 100644 index 3a996cc6e8..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Output.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -@Beta -public interface Output> { - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Rpc.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Rpc.java deleted file mode 100644 index c5003900a9..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/Rpc.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -/** - * - * The "rpc" statement is used to define an RPC operation. The "rpc" statement - * defines an RPC node in the schema tree. Under the RPC node, a schema node - * with the name "input" and a schema node with the name "output" are also defined. - * The nodes "input" and "output" are defined in the module’s namespace. - * - */ -@FunctionalInterface -public interface Rpc & Instantiable, O extends Output & Instantiable> extends Operation { - - /** - * @param input Rpc input schema node - * @param callback on success/failure callback - */ - void invoke(I input, RpcCallback callback); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/RpcCallback.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/RpcCallback.java deleted file mode 100644 index 79c7eda255..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/RpcCallback.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -@Beta -public interface RpcCallback { - - void onSuccess(O output); - - void onFailure(Throwable e); - - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeArgument.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeArgument.java deleted file mode 100644 index 46a178a1b2..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeArgument.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; - -@Beta -public abstract class TreeArgument { - - static TreeArgument root() { - throw new UnsupportedOperationException(); - } - - static > Item singular(Class implementedInterface) { - throw new UnsupportedOperationException(); - } - - TreeArgument() { - // Intentionally package-visible & noop - } - - public abstract Class getType(); - - @Override - public int hashCode() { - return getType().hashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TreeArgument other = (TreeArgument) obj; - return getType().equals(other.getType()); - } - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeNode.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeNode.java deleted file mode 100644 index 33210fafa4..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeNode.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode; - -/** - * - * Replaces org.opendaylight.yangtools.yang.binding.DataObject from Binding Spec v1 - * @see TreeRoot - * @see TreeChildNode - * - */ -@Beta -public interface TreeNode { - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeRoot.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeRoot.java deleted file mode 100644 index 673d58500f..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/base/TreeRoot.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.base; - -import com.google.common.annotations.Beta; - -@Beta -public interface TreeRoot extends TreeNode { - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingCodec.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingCodec.java deleted file mode 100644 index 65d8205c3e..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingCodec.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.concepts.Codec; - -/** - * Base interface for Binding2 encoding/decoding mechanism implementation - */ -@Beta -public interface BindingCodec extends BindingSerializer, BindingDeserializer, Codec { - - /** - * Produces an object based on input. - * - * @param input Input object - * @return Product derived from input - */ - @Override - P serialize(I input); - - /** - * Produces an object based on input. - * - * @param input Input object - * @return Product derived from input - */ - @Override - I deserialize(P input); - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingDeserializer.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingDeserializer.java deleted file mode 100644 index 9995c7b4d2..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingDeserializer.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; - -/** - * The concept of a deserializer in Binding part, which produces an object from some input. - * - * @param

    Product type - * @param Input type - */ -@Beta -public interface BindingDeserializer { - - /** - * Produces an object based on input. - * - * @param input Input object - * @return Product derived from input - */ - P deserialize(I input); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingNamespaceType.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingNamespaceType.java deleted file mode 100755 index 6ed5cbd8bb..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingNamespaceType.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; - -/** - * Binding Namespace is structure of Java packages designed to prevent conflicts in YANG Java - * Binding, since Java does have only one namespace. - */ -@Beta -public enum BindingNamespaceType { - - /** - * - * Namespace containing all derived types, defined from grouping and data namespaces - * - */ - Typedef("type"), Identity("ident"), Key("key"), Data("data"), Notification("data"), Operation("data"), - Grouping("grp"), Builder("dto"); - - private final String packagePrefix; - - BindingNamespaceType(String packagePrefix) { - this.packagePrefix = requireNonNull(packagePrefix); - } - - public String getPackagePrefix() { - return packagePrefix; - } - - public static Boolean isData(final BindingNamespaceType type) { - return isTreeData(type) || isNotificationData(type) || isOperationData(type); - } - - public static Boolean isTreeData(final BindingNamespaceType type) { - return Data.equals(type); - } - - public static Boolean isNotificationData(final BindingNamespaceType type) { - return Notification.equals(type); - } - - public static Boolean isOperationData(final BindingNamespaceType type) { - return Operation.equals(type); - } - - public static Boolean isGrouping(final BindingNamespaceType type) { - return Grouping.equals(type); - } -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingSerializer.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingSerializer.java deleted file mode 100644 index b1e9c60d8c..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; - -/** - * The concept of a serializer in Binding part, which produces an object from some input. - * - * @param

    Product type - * @param Input type - */ -@Beta -public interface BindingSerializer { - - /** - * Produces an object based on input. - * - * @param input Input object - * @return Product derived from input - */ - P serialize(I input); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingStreamEventWriter.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingStreamEventWriter.java deleted file mode 100644 index 0e67872e69..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/BindingStreamEventWriter.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem; -import org.opendaylight.mdsal.binding.javav2.spec.base.Item; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation; -import org.opendaylight.yangtools.concepts.Identifiable; - -/** - * Event Stream Writer for Binding version 2 Representation - * - * - *

    Emitting Event Stream

    - * - *
      - *
    • container - Container node representation, start event is - * emitted using {@link #startContainerNode(Class, int)} and node end event is - * emitted using {@link #endNode()}. Container node is implementing - * {@link TreeNode} interface. - * - *
    • list - YANG list statement has two representations in event - * stream - un-keyed list and map. Un-keyed list is YANG list which didn't - * specify key. - * - *
        - *
      • Map - Map start event is emitted using - * {@link #startMapNode(Class, int)} and is ended using {@link #endNode()}. Each map - * entry start is emitted using {@link #startMapEntryNode(IdentifiableItem, int)} with Map of keys - * and finished using {@link #endNode()}.
      • - * - *
      • UnkeyedList - Un-keyed list represents list without keys, - * un-keyed list start is emitted using {@link #startUnkeyedList(Class, int)}, list - * end is emitted using {@link #endNode()}. Each list item is emitted using - * {@link #startUnkeyedListItem(int)} and ended using {@link #endNode()}.
      • - *
    • - * - *
    • leaf - Leaf node event is emitted using - * {@link #leafNode(String, Object)}. {@link #endNode()} MUST NOT be emitted for - * leaf node.
    • - * - *
    • leaf-list - Leaf list start is emitted using - * {@link #startLeafSet(String, int)}. Leaf list end is emitted using - * {@link #endNode()}. Leaf list entries are emitted using - * {@link #leafSetEntryNode(Object)}. - * - *
    • anyxml - Anyxml node event is emitted using - * {@link #anyxmlNode(String, Object)}. {@link #endNode()} MUST NOT be emitted - * for anyxml node.
    • - * - *
    • anydata - Anydata node event is emitted using - * {@link #startAnydataNode(String, Object)}. {@link #endNode()} MUST NOT be emitted - * for anydata node.
    • - * - *
    • choice Choice node event is emitted by - * {@link #startChoiceNode(Item, int)} event and must be immediately followed by - * {@link #startCase(Class, int)} event. Choice node is finished by emitting an - * {@link #endNode()} event.
    • - * - *
    • - * case - Case node may be emitted only inside choice node by - * invoking {@link #startCase(Class, int)}. Case node is finished be emitting an - * {@link #endNode()} event.
    • - * - *
    • - * augment - Represents augmentation, augmentation node is started - * by invoking {@link #startAugmentationNode(Class)} and - * finished by invoking {@link #endNode()}.
    • - * - *
    - * - *

    Implementation notes

    This interface is not intended to be - * implemented by users of generated Binding2 DTOs but to be used by utilities, - * which needs to emit NormalizedNode model from Binding2 DTOs. - *

    - * This interface is intended as API definition of facade for real Event / - * Stream Writer, without explicitly requiring stream writer and related - * interfaces to be imported by all generated Binding2 DTOs. - *

    - * Existence of this interface in runtime Java Binding2 package is required to - * support runtime generation of users of this interface in OSGI and OSGI-like - * environment, since this package is only package which is imported by all - * generated Binding2 DTOs and wired in OSGI. - * - * - */ -@Beta -public interface BindingStreamEventWriter extends Closeable, Flushable { - - /** - * Methods in this interface allow users to hint the underlying - * implementation about the sizing of container-like constructors - * (leafLists, containers, etc.). These hints may be taken into account by a - * particular implementation to improve performance, but clients are not - * required to provide hints. This constant should be used by clients who - * either do not have the sizing information, or do not wish to divulge it - * (for whatever reasons). Implementations are free to ignore these hints - * completely, but if they do use them, they are expected to be resilient in - * face of missing and mismatched hints, which is to say the user can - * specify startLeafSet(..., 1) and then call leafNode() 15 times. - *

    - * The acceptable hint values are non-negative integers and this constant, - * all other values will result, based on implementation preference, in the - * hint being completely ignored or IllegalArgumentException being thrown. - */ - int UNKNOWN_SIZE = -1; - - /** - * - * Emits a leaf node event with supplied value. - * - * @param localName - * name of node as defined in schema, namespace and revision are - * derived from parent node. - * @param value - * Value of leaf node. - * @throws IllegalArgumentException - * If emitted leaf node has invalid value in current context or - * was emitted multiple times. - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void leafNode(String localName, Object value) throws IOException; - - /** - * - * Emits a start of leaf set (leaf-list). - *

    - * Emits start of leaf set, during writing leaf set event, only - * {@link #leafSetEntryNode(Object)} calls are valid. Leaf set event is - * finished by calling {@link #endNode()}. - * - * @param localName - * name of node as defined in schema, namespace and revision are - * derived from parent node. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * If emitted leaf node is invalid in current context or was - * emitted multiple times. - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startLeafSet(String localName, int childSizeHint) throws IOException; - - /** - * - * Emits a start of leaf set (leaf-list). - *

    - * Emits start of leaf set, during writing leaf set event, only - * {@link #leafSetEntryNode(Object)} calls are valid. Leaf set event is - * finished by calling {@link #endNode()}. - * - * @param localName - * name of node as defined in schema, namespace and revision are - * derived from parent node. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * If emitted leaf node is invalid in current context or was - * emitted multiple times. - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startOrderedLeafSet(String localName, int childSizeHint) throws IOException; - - /** - * Emits a leaf set entry node - * - * @param value - * Value of leaf set entry node. - * @throws IllegalArgumentException - * If emitted leaf node has invalid value. - * @throws IllegalStateException - * If node was emitted outside leaf set node. - * @throws IOException if an underlying IO error occurs - */ - void leafSetEntryNode(Object value) throws IOException; - - /** - * - * Emits start of new container. - * - *

    - * End of container event is emitted by invoking {@link #endNode()}. - * - *

    - * Valid sub-events are: - *

      - *
    • {@link #leafNode(String, Object)}
    • - *
    • {@link #startContainerNode(Class, int)}
    • - *
    • {@link #startChoiceNode(Item, int)}
    • - *
    • {@link #startLeafSet(String, int)}
    • - *
    • {@link #startMapNode(Class, int)}
    • - *
    • {@link #startUnkeyedList(Class, int)}
    • - *
    • {@link #startAugmentationNode(Class)}
    • - *
    - * - * @param container - * name of node as defined in schema, namespace and revision are - * derived from parent node. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * If emitted node is invalid in current context or was emitted - * multiple times. - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startContainerNode(Class container, int childSizeHint) throws IOException; - - /** - * - * Emits start of unkeyed list node event. - * - *

    - * End of unkeyed list event is emitted by invoking {@link #endNode()}. - * Valid sub-event is only {@link #startUnkeyedListItem(int)}. All other - * methods will throw {@link IllegalArgumentException}. - * - * @param localName - * name of node as defined in schema, namespace and revision are - * derived from parent node. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * If emitted node is invalid in current context or was emitted - * multiple times. - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startUnkeyedList(Class localName, int childSizeHint) throws IOException; - - /** - * Emits start of new unkeyed list item. - * - *

    - * Un-keyed list item event is finished by invoking {@link #endNode()}. - *

    - * Valid sub-events are: - * - *

      - *
    • {@link #leafNode(String, Object)}
    • - *
    • {@link #startContainerNode(Class, int)}
    • - *
    • {@link #startChoiceNode(Item, int)}
    • - *
    • {@link #startLeafSet(String, int)}
    • - *
    • {@link #startMapNode(Class, int)}
    • - *
    • {@link #startUnkeyedList(Class, int)}
    • - *
    • {@link #startAugmentationNode(Class)}
    • - *
    - * - * - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalStateException - * If node was emitted outside unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startUnkeyedListItem(int childSizeHint) throws IOException; - - /** - * - * Emits start of unordered map node event. - * - *

    - * End of map node event is emitted by invoking {@link #endNode()}. Valid - * subevents is only {@link #startMapEntryNode(IdentifiableItem, int)}. All other methods will - * throw {@link IllegalArgumentException}. - * - * @param mapEntryType - * Class of list. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - > void startMapNode(Class mapEntryType, int childSizeHint) - throws IOException; - - /** - * - * Emits start of ordered map node event. - * - *

    - * End of map node event is emitted by invoking {@link #endNode()}. Valid - * sub-event is only {@link #startMapEntryNode(IdentifiableItem, int)}. All other methods will - * throw {@link IllegalArgumentException}. - * - * @param mapEntryType - * Class of list item, which has defined key. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - > void startOrderedMapNode(Class mapEntryType, int childSizeHint) - throws IOException; - - /** - * - * Emits start of map entry. - * - *

    - * End of map entry event is emitted by invoking {@link #endNode()}. - * - *

    - * Valid sub-events are: - *

      - *
    • {@link #leafNode(String, Object)}
    • - *
    • {@link #startContainerNode(Class, int)}
    • - *
    • {@link #startChoiceNode(Item, int)}
    • - *
    • {@link #startLeafSet(String, int)}
    • - *
    • {@link #startMapNode(Class, int)}
    • - *
    • {@link #startUnkeyedList(Class, int)}
    • - *
    • {@link #startAugmentationNode(Class)}
    • - *
    - * - * @param keyValues - * Key of map entry node - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * If key contains incorrect value. - * @throws IllegalStateException - * If node was emitted outside map entry node. - * @throws IOException if an underlying IO error occurs - */ - void startMapEntryNode(IdentifiableItem keyValues, int childSizeHint) - throws IOException; - - /** - * Emits start of choice node. - * - *

    - * Valid sub-event is {@link #startCase(Class, int)}, which selects case - * which should be written. - * - * @param choice - * Choice class. - * @param childSizeHint - * Non-negative count of expected direct child nodes or - * {@link #UNKNOWN_SIZE} if count is unknown. This is only hint - * and should not fail writing of child events, if there are more - * events than count. - * @throws IllegalArgumentException - * @throws IllegalStateException - * If node was emitted inside map, choice, - * unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startChoiceNode(Item choice, int childSizeHint) throws IOException; - - /** - * - * Starts a case node. - * - *

    - * Valid sub-events are: - *

      - *
    • {@link #leafNode(String, Object)}
    • - *
    • {@link #startContainerNode(Class, int)}
    • - *
    • {@link #startChoiceNode(Item, int)}
    • - *
    • {@link #startLeafSet(String, int)}
    • - *
    • {@link #startMapNode(Class, int)}
    • - *
    • {@link #startUnkeyedList(Class, int)}
    • - *
    • {@link #startAugmentationNode(Class)}
    • - *
    - * - * @param caze Case class - * @throws IllegalArgumentException - * @throws IOException if an underlying IO error occurs - */ - void startCase(Class caze, int childSizeHint) throws IOException; - - /** - * Emits start of augmentation node. - * - *

    - * End of augmentation event is emitted by invoking {@link #endNode()}. - * - *

    - * Valid sub-events are: - * - *

      - *
    • {@link #leafNode(String, Object)}
    • - *
    • {@link #startContainerNode(Class, int)}
    • - *
    • {@link #startChoiceNode(Item, int)}
    • - *
    • {@link #startLeafSet(String, int)}
    • - *
    • {@link #startMapNode(Class, int)}
    • - *
    • {@link #startUnkeyedList(Class, int)}
    • - *
    - * - *

    - * Note this is only method, which does not require childSizeHint, since - * maximum value is always size of possibleChildren. - * - * @param augmentationType augmentation class - * @throws IllegalArgumentException - * If augmentation is invalid in current context. - * @throws IOException if an underlying IO error occurs - */ - void startAugmentationNode(Class> augmentationType) throws IOException; - - /** - * Emits anyxml node event. - * - * @param name - * @param value - * @throws IllegalArgumentException - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void anyxmlNode(String name, Object value) throws IOException; - - /** - * Emits anydata node event. - * - * @param name - * @param value - * @throws IllegalStateException - * If node was emitted inside map, - * choice unkeyed list node. - * @throws IOException if an underlying IO error occurs - */ - void startAnydataNode(String name, Object value) throws IOException; - - /** - * Emits end event for node. - * - * @throws IllegalStateException If there is no open node. - * @throws IOException if an underlying IO error occurs - */ - void endNode() throws IOException; - - @Override - void flush() throws IOException; - - @Override - void close() throws IOException; -} - diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/CodeHelpers.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/CodeHelpers.java deleted file mode 100644 index 197cc42ea8..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/CodeHelpers.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2018 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Verify.verify; -import static java.util.Objects.requireNonNull; - -import com.google.common.base.MoreObjects.ToStringHelper; -import com.google.common.base.VerifyException; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; -import org.eclipse.jdt.annotation.NonNull; -import org.eclipse.jdt.annotation.Nullable; - -/** - * Helper methods for generated binding code. This class concentrates useful primitives generated code may call - * to perform specific shared functions. This allows for generated classes to be leaner. Methods in this class follows - * general API stability requirements of the Binding Specification. - * - * @author Robert Varga - */ -public final class CodeHelpers { - private static final String NEGATED_PATTERN_PREFIX = "^(?!"; - private static final String NEGATED_PATTERN_SUFFIX = ").*$"; - - private CodeHelpers() { - // Hidden - } - - /** - * Require that an a value-related expression is true. - * - * @param expression Expression to evaluate - * @param value Value being validated - * @param options Valid value options checked - * @throws IllegalArgumentException if expression is false - */ - public static void validValue(final boolean expression, final Object value, final String options) { - checkArgument(expression, "expected one of: %s \n%but was: %s", options, value); - } - - /** - * Require an argument being received. This is similar to {@link java.util.Objects#requireNonNull(Object)}, but - * throws an IllegalArgumentException. - * - *

    - * Implementation note: we expect argName to be a string literal or a constant, so that it's non-nullness can be - * quickly discovered for a call site (where we are going to be inlined). - * - * @param value Value itself - * @param name Symbolic name - * @return non-null value - * @throws IllegalArgumentException if value is null - * @throws NullPointerException if name is null - */ - // FIXME: another advantage is that it is JDT-annotated, but we could live without that. At some point we should - // schedule a big ISE-to-NPE conversion and just use Objects.requireNonNull() instead. - public static @NonNull T nonNullValue(@Nullable final T value, final @NonNull String name) { - requireNonNull(name); - checkArgument(value != null, "%s must not be null", name); - return value; - } - - /** - * Append a named value to a ToStringHelper. If the value is null, this method does nothing. - * - * @param helper Helper to append to - * @param name Name of the value - * @param value Value to append - * @throws NullPointerException if the name or helper is null - */ - public static void appendValue(final @NonNull ToStringHelper helper, final @NonNull String name, - final @Nullable Object value) { - if (value != null) { - helper.add(name, value); - } - } - - /** - * Append a named value to a ToStringHelper. If the value is null, this method does nothing. - * - * @param helper Helper to append to - * @param name Name of the value - * @param value Value to append - * @throws NullPointerException if the name or helper is null - */ - public static void appendValue(final ToStringHelper helper, final String name, final byte[] value) { - if (value != null) { - helper.add(name, Arrays.toString(value)); - } - } - - /** - * Compile a list of pattern regular expressions and return them as an array. The list must hold at least two - * expressions. - * - * @param patterns Patterns to compile - * @return Compiled patterns in an array - * @throws NullPointerException if the list or any of its elements is null - * @throws VerifyException if the list has fewer than two elements - */ - public static @NonNull Pattern[] compilePatterns(final @NonNull List patterns) { - final int size = patterns.size(); - verify(size > 1, "Patterns has to have at least 2 elements"); - final @NonNull Pattern[] result = new Pattern[size]; - for (int i = 0; i < size; ++i) { - result[i] = Pattern.compile(patterns.get(i)); - } - return result; - } - - /** - * Check whether a specified string value matches a specified pattern. This method handles the distinction between - * modeled XSD expression and enforcement {@link Pattern} which may reflect negation. - * - * @param value Value to be checked. - * @param pattern Enforcement pattern - * @param regex Source regular expression, as defined in YANG model - * @throws IllegalArgumentException if the value does not match the pattern - * @throws NullPointerException if any of the arguments are null - */ - public static void checkPattern(final String value, final Pattern pattern, final String regex) { - if (!pattern.matcher(value).matches()) { - final String match = isNegatedPattern(pattern.toString()) ? "matches forbidden" - : "does not match required"; - throw new IllegalArgumentException("Supplied value \"" + value + "\" " + match + " pattern \"" - + regex + "\""); - } - } - - private static boolean isNegatedPattern(final String pattern) { - return pattern.startsWith(NEGATED_PATTERN_PREFIX) && pattern.endsWith(NEGATED_PATTERN_SUFFIX); - } - - /** - * Check whether a specified string value matches specified patterns. This method handles the distinction between - * modeled XSD expression and enforcement {@link Pattern} which may reflect negation. - * - * @param value Value to be checked. - * @param patterns Enforcement patterns - * @param regexes Source regular expression, as defined in YANG model. Size and order must match patterns. - * @throws IllegalArgumentException if the value does not match the pattern - * @throws NullPointerException if any of the arguments are null - * @throws VerifyException if the size of patterns and regexes does not match - */ - public static void checkPattern(final String value, final Pattern[] patterns, final String[] regexes) { - verify(patterns.length == regexes.length, "Patterns and regular expression lengths have to match"); - for (int i = 0; i < patterns.length; ++i) { - checkPattern(value, patterns[i], regexes[i]); - } - } - - /** - * Throw an IllegalArgument exception describing a length violation. - * - * @param expected String describing expected lengths - * @param actual Actual observed object - * @throws IllegalArgumentException always - */ - public static void throwInvalidLength(final String expected, final Object actual) { - throw new IllegalArgumentException("Invalid length: " + actual + ", expected: " + expected + "."); - } - - /** - * Throw an IllegalArgument exception describing a length violation. - * - * @param expected String describing expected lengths - * @param actual Actual observed byte array - * @throws IllegalArgumentException always - */ - public static void throwInvalidLength(final String expected, final byte[] actual) { - throwInvalidLength(expected, Arrays.toString(actual)); - } - - /** - * Throw an IllegalArgument exception describing a range violation. - * - * @param expected String describing expected ranges - * @param actual Actual observed object - * @throws IllegalArgumentException always - */ - public static void throwInvalidRange(final String expected, final Object actual) { - throw new IllegalArgumentException("Invalid range: " + actual + ", expected: " + expected + "."); - } - - /** - * Throw an IllegalArgument exception describing a range violation. - * - * @param expected Objects describing expected ranges - * @param actual Actual observed byte array - * @throws IllegalArgumentException always - */ - public static void throwInvalidRange(final Object[] expected, final Object actual) { - throwInvalidRange(Arrays.toString(expected), actual); - } -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/NotificationListener.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/NotificationListener.java deleted file mode 100644 index e08c9408b7..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/NotificationListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; -import java.util.EventListener; -import org.opendaylight.mdsal.binding.javav2.spec.base.Notification; - -/** - * Marker interface for generated notification listener interfaces. This interface - * exists solely as support for generated code. Users should never implement this - * interface directly, but rather implement one of the sub-interfaces generated - * from a YANG model. - * - *

    - * The subclasses of this interface have callbacks for events, which are derived - * from {@link Notification} class in form void - * on{NotificationType}(NotificationType notification). - * - *

    - * E.g. if we have notification SessionUp the callback will have signature: - * void onSessionUp(SessionUp notification) - */ -@Beta -public interface NotificationListener extends EventListener { -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializer.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializer.java deleted file mode 100644 index 3e95a75010..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializer.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * A serializer which writes TreeNode to supplied stream event writer. - */ -@Beta -public interface TreeNodeSerializer { - - /** - * Writes stream events representing object to supplied stream. - * - * @param obj - * Source of stream events - * @param stream - * Stream to which events should be written. - */ - void serialize(TreeNode obj, BindingStreamEventWriter stream) throws IOException; -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerImplementation.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerImplementation.java deleted file mode 100644 index a13d7b4ca1..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerImplementation.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import java.io.IOException; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Contract for implementations of {@link TreeNodeSerializer}. - * The contract is kept between implementation of {@link TreeNodeSerializerRegistry}, - * which maintains the lookup context required for recursive serialization. - */ -public interface TreeNodeSerializerImplementation { - - /** - * Writes stream events for supplied tree node to provided stream. - * - * TreeNodeSerializerRegistry may be used to lookup serializers for other generated classes in order to - * support writing their events. - */ - void serialize(TreeNodeSerializerRegistry reg, TreeNode obj, BindingStreamEventWriter stream) throws IOException; -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerRegistry.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerRegistry.java deleted file mode 100644 index 5f8f26da69..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/TreeNodeSerializerRegistry.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; - -/** - * Contract for registry of {@link TreeNodeSerializer}. - * The contract is kept between implementation of {@link TreeNodeSerializerImplementation}, - * Registry provides lookup for serializers to support recursive - * serialization of nested {@link TreeNode}s. - */ -public interface TreeNodeSerializerRegistry { - - /** - * Returns implementation of requested serializer. - * @param binding input binding class - * @return returns serializer, based on input binding class - */ - TreeNodeSerializer getSerializer(Class binding); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModelBindingProvider.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModelBindingProvider.java deleted file mode 100644 index 9086b368d3..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModelBindingProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import java.util.ServiceLoader; - -/** - * - * Provider of YangModuleInfo for specified package / model. - * - * Implementation of this interface should be discoverable - * via {@link ServiceLoader} - * - */ -public interface YangModelBindingProvider { - - /** - * YangModuleInfo associated to package - * - * @return YangModuleInfo - */ - YangModuleInfo getModuleInfo(); - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModuleInfo.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModuleInfo.java deleted file mode 100644 index 8342ef7ed9..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/runtime/YangModuleInfo.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.runtime; - -import com.google.common.annotations.Beta; -import java.io.InputStream; -import java.util.Optional; -import java.util.Set; -import org.opendaylight.yangtools.concepts.SemVer; -import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation; - -/** - * Provides basic information about YANG module - */ -@Beta -public interface YangModuleInfo { - - /** - * Returns yang module name - * - * @return YANG module name - */ - String getName(); - - /** - * Returns revision of yang module. - * - * @return YANG module revision - */ - String getRevision(); - - /** - * Returns semantic version of yang module - * - * @return YANG module semantic version - */ - Optional getSemanticVersion(); - - /** - * Returns XML namespace associated to the YANG module - * - * @return XML namespace associated to the YANG module. - */ - String getNamespace(); - - /** - * Returns set of imported modules - * @return set of YangModuleInfo instances - */ - Set getImportedModules(); - - /** - * Transforms YangModuleInfo instance to its source representation - * @return YangModuleInfo source representation - */ - SchemaSourceRepresentation getModuleSourceRepresentation(); - - /** - * Get stream of module source - * - * @return input stream of module source - */ - InputStream getModuleSourceStream(); - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentable.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentable.java deleted file mode 100644 index 6de2eb52bb..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentable.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.structural; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ClassToInstanceMap; - -/** - * Augmentable (extensible) object which could carry additional data defined by third-party - * extension, without introducing conflict between various extension. - * - * This interface uses extended version of ExtensibleInterface pattern which also adds marker - * interface for augmentations (extensions) - {@link Augmentable} - * - * @author Tony Tkacik - * @param Base class which should implements this interface and is target for augmentation. - */ -@Beta -public interface Augmentable { - - /** - * Returns instance of augmentation based on class - * - * @param augment Type of augmentation to be returned. - * @return instance of augmentation. - */ - default > E getAugmentation(Class augment) { - return augments().getInstance(augment); - } - - /** - * - * Returns map of all instantiated augmentations. - * - * @return Class to Instance Map - */ - // REPLACES: BindingReflections#getAugmentations() - ClassToInstanceMap> augments(); -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentation.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentation.java deleted file mode 100644 index 5e61e07b00..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/Augmentation.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.structural; - -import com.google.common.annotations.Beta; -import org.opendaylight.yangtools.util.ClassLoaderUtils; - -@Beta -public interface Augmentation { - - // REPLACES: BindingReflections#findAugmentationTarget - default Class augmentTarget() { - return ClassLoaderUtils.findFirstGenericArgument(getClass(), Augmentation.class); - } - -} diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/AugmentationHolder.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/AugmentationHolder.java deleted file mode 100644 index 231f5f3523..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/AugmentationHolder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.structural; - -import java.util.Map; - -/** - * - * Augmentable (extensible) object which could carry additional data defined by - * third-party extensions, without introducing conflict between various - * extensions. - * - * @param - * Base class which should be target - * for augmentations. - */ -public interface AugmentationHolder { - - /** - * Returns map of all augmentations. - * - * @return map of all augmentations. - */ - Map>,Augmentation> augmentations(); -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/TreeChildNode.java b/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/TreeChildNode.java deleted file mode 100644 index ac6afa0e30..0000000000 --- a/binding2/mdsal-binding2-spec/src/main/java/org/opendaylight/mdsal/binding/javav2/spec/structural/TreeChildNode.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.spec.structural; - -import com.google.common.annotations.Beta; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.yangtools.util.ClassLoaderUtils; - -/** - * - * Replaces org.opendaylight.yangtools.yang.binding.ChildOf from Binding Spec v1 - */ -@Beta -public interface TreeChildNode

    > extends TreeNode { - - I treeIdentifier(); - - - // REPLACES: BindingReflections#findHierarchicalParent() - default Class

    treeParent() { - return ClassLoaderUtils.findFirstGenericArgument(getClass(), TreeChildNode.class); - } - -} diff --git a/binding2/mdsal-binding2-spec/src/site/asciidoc/binding-2.adoc b/binding2/mdsal-binding2-spec/src/site/asciidoc/binding-2.adoc deleted file mode 100644 index b5ec36ad13..0000000000 --- a/binding2/mdsal-binding2-spec/src/site/asciidoc/binding-2.adoc +++ /dev/null @@ -1,1238 +0,0 @@ -= Java Binding Specification 2 -Tony Tkacik ; Robert Varga ; Martin Sunal ; Martin Ciglan -:rfc6020: https://tools.ietf.org/html/rfc6020 -:toc: -:toclevels: 4 - -== Introduction - -=== Terminology - -Namespace:: - naming space, in which all identifiers needs to be unique -identifiers. -Data Node:: -Data Tree:: -Instance Identifier:: -Instantiated Data Node:: -Instantiated Data Tree:: -Transfer Object:: -Builder:: - builder - -=== YANG Identifiers Mapping - -Every non-Java char in identifier is converted to Java char by its unicode name http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8 -JAVA SE SPECIFICATIONS - Identifiers. This mapping solves various issues from Binding Specification v1, which led to compilation issues. - -There are special types of mapping non-java chars to original identifiers according to specific Java type: - -* class, enum, interface - -** without special separator -the first character of identifier, any other first character of identifier part mapped by -** non-Java char name from unicode and char in identifier behind non-java char name are converting to upper case - - examples: - example* - ExampleAsterisk - example*example - ExampleAserisksExample - \example - ReverseSolidusExample - 1example - DigitOneExample - example1 - Example1 - int - IntReservedKeyword - con - ConReservedKeyword - -* enum value, constant -** used underscore as special separator -** converted identifier to upper case - - examples: - example* - EXAMPLE_ASTERISK - example*example - EXAMPLE_ASTERISK_EXAMPLE - \example - REVERSE_SOLIDUS_EXAMPLE - 1example - DIGIT_ONE_EXAMPLE - example1 - EXAMPLE1 - int - INT_RESERVED_KEYWORD - con - CON_RESERVED_KEYWORD - -* method, variable -** without special separator -** the first character of identifier is converting to lower case -** any other first character of identifier part mapped by non-Java char name from unicode and char in identifier behind non-java char name are converting to upper case - - examples: - example* - exampleAsterisk - example*example - exampleAserisksExample - \example - reverseSolidusExample - 1example - digitOneExample - example1 - example1 - int - intReservedKeyword - con - conReservedKeyword - -* package - full package name - https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html -** parts of package name are separated by dots -** parts of package name are converting to lower case -** if parts of package name are reserved Java or Windows keywords, such as 'int' the suggested convention is to add an underscore to keyword -** dash is parsed as underscore according to https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html - - examples: - org.example* - org.exampleasterisk - org.example*example - org.exampleasteriskexample - org.example - org.reversesolidusexample - org.1example - org.digitoneexample - org.example1 - org.example1 - org.int - org.int_ - org.con - org.con_ - org.foo-cont - org.foo_cont - -==== Special case - '-' in identifiers -There is special case in CLASS, INTERFACE, ENUM, ENUM VALUE, CONSTANT, METHOD and VARIABLE if -identifier contains single dash - then the converter ignores the single dash in the way of the -non-java chars. In other way, if dash is the first or the last char in the identifier or there is -more dashes in a row in the identifier, then these dashes are converted as non-java chars. - -Example: - -* class, enum, interface - - foo-cont - FooCont - foo--cont - FooHyphenMinusHyphenMinusCont - -foo - HyphenMinusFoo - foo- - FooHyphenMinus - -* enum value, constant - - foo-cont - FOO_CONT - foo--cont - FOO_HYPHEN_MINUS_HYPHEN_MINUS_CONT - -foo - HYPHEN_MINUS_FOO - foo- - FOO_HYPHEN_MINUS - -* method, variable - - foo-cont - fooCont - foo--cont - fooHyphenMinusHyphenMinusCont - -foo - hyphenMinusFoo - foo- - fooHyphenMinus - -==== Special case - same class (or enum or interface) names with different camel cases -Next special case talks about normalizing class name which already exists in package - but with -different camel cases (foo, Foo, fOo, ...). To every next classes with same names will by added -their actual rank (serial number), except the first one. This working for CLASS, ENUM and -INTEFACE java identifiers. If there exist the same ENUM VALUES in ENUM (with different camel -cases), then it's parsed with same logic like CLASSES, ENUMS and INTERFACES but according to list -of pairs of their ENUM parent. Example: - -* class, enum, interface - - package name org.example, class (or interface or enum) Foo - normalized to Foo - package name org.example, class (or interface or enum) fOo - normalized to Foo1 - -* enum value - - type enumeration { - enum foo; - enum Foo; - } - YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum values. - - -=== Binding Specification v2 Concepts - -<>:: - Represent node, which is instantiable by users as a part of notification, - rpc, action or data tree. -<>:: - Represents node, which is part of instantiated data tree, this interface - is not used directly, but rather via <>. See <> - for more information. -<>:: - Represents virtual root of instantiated data tree. -<>:: - Represents node, which is part of instantiated data tree and is not root of - data tree. -<>:: - Represents instantiated node, which is subjectible to be extended / augmented - by `augment` statement from external module. -<>:: - Represents extension to instantiated node, which is introduced from different - model than instantiated node. -<>:: - Unique identifier of node / subtree in data tree, which provides unambiguous - information, how to reference node / subtree in Instantiated Data Tree. - - -[cols="6"] -|=== -.2+|Statement .2+| In groupings 3+| Instantiable .2+| Augmentable -| In Data | In RPC | In Notification - -| `grouping` | Yes | No | No | No | No - -| `container` | Yes | Yes | Yes | Yes | Yes - -| `leaf` | Yes | Yes | Yes | Yes | No - -| `leaf-list` | Yes | Yes | Yes | Yes | No - -| `list` | Yes | Yes | Yes | Yes | Yes - -| `anydata` | Yes | Yes | Yes | Yes | No - -| `anyxml` | Yes | Yes | Yes | Yes | No - -| `choice` | Yes | Yes | Yes | Yes | Yes - -| `case` | Yes | Yes | Yes | Yes | Yes - -| `input` | Yes | No | Yes | No | Yes - -| `output` | Yes | No | Yes | No | Yes - -| `notification` | Yes | No | No | Yes | Yes - -|=== - -== Namespaces - -YANG defines several namespaces and naming space of YANG is wider then applicable -namespace of JAVA language. In order to decrease conflicts between various -YANG-defined namespaces and classes introduced by Binding Specification, it -is needed to: - -* separate namespaces by Java package hierarchy -** each namespace must define rules how to construct package name, which - will not conflict with other namespace -* if multiple classes are generated for YANG statement they need to be in separate - packages to decrease possible conflicts with siblings. -* if Binding Specification introduces new concepts, which does not have explicit - namespace rules in YANG, these concepts needs to be in their own, separate - namespaces, in order to not conflict on valid YANG namespace items. - - -This rules allows to identify two types of namespaces: - -.Namespace types by source of namespace -YANG namespace:: - Naming space explicitly defined in YANG specification, which needs to be - explicitly supported in order to prevent naming conflicts. -Binding namespace:: - Naming space introduced by Binding Specification for additional properties - and functionality of Binding Specification. This namespaces needs to be separate - from YANG namespaces in order to not have naming conflict with YANG-derived. - - -Binding Specification v2 uses following namespaces: - -.Concrete namespaces used in Binding Specification -<>:: - YANG namespace containing representation for all modules. -<>:: - YANG namespace containing representation for all `identity` statements. Identities - needs to be separated to prevent naming conflict between Grouping, Data, Type - namespaces. -<>:: - YANG namespace containing representation for all `typedef` statements and - annonymous definitions of `union`, `enumeration` and `bits` types. Types needs - to be seperated to prevent naming conflict between Identity, Grouping and Data - namespaces. -<>:: - YANG namespace containing representation for all `grouping` statements and their - child data node statements. Groupings needs to be separated to prevent naming - conflict between Identity, Type, Data namespaces. -<>:: - Binding namespace containing representation for all `key` statements. - Representations of key statements needs to be in separate namespace, since it is not defined - in YANG specification. -<>:: - YANG namespace containing representation of instantiated data tree. - Data needs to be separated to prevent naming conflict between Identity, Type, - Grouping namespaces. -<>:: - Binding namespace containing Transfer Objects and Builders representing - instantiated data tree items. - -NOTE: Most of Binding Namespaces were introduced to decrease possibility of name -conflict between concepts defined in YANG and additional concepts introduced -by Binding Specification. - -=== Package hierarchy - -.Package hierarchy for model -[cols="1,1,4"] -|=== -|Namespace | Package | Description - -| <> | `ident` -| flat package containing representation for all `identity` - -.3+| <> | `type` -| flat package containing representations for all top-level - `typedef` statements - -| `type.grp` -| path-based package hierarchy containing representation - for `typedef` statements nested in grouping statements, or anonymous types - requiring code generation defined inside groupings - -| `type.data` -| path-based package hierarchy containing representation - for `typedef` statements nested in grouping statements, or anonymous types - requiring code generation defined inside instantiated data nodes - -| <> | `key` -| path-based package hierarchy containing representation - of key statements for grouping code generation defined inside groupings - -| <> | `grp` -| path-based package hierarchy containing representation - for `grouping` statements and data node statements nested in these groupings - -| <> | `data` -| path-based package hierarchy containing representation of instantiated - data nodes - -| <> | `dto` -| path-based package hierarchy containing Tranfer Objects and their builders - for instantiated data nodes -|=== - -[[module-namespace]] -=== Module Namespace - - - -[[identity-namespace]] -=== Identity Namespace - - -[[type-namespace]] -=== Type Namespace - -[[grouping-namespace]] -=== Grouping Namespace - -[[key-namespace]] -=== Key Namespace - -[[data-namespace]] -=== Data Namespace - -[[dto-namespace]] -=== Builder Namespace - -== Generic rules - -[[class-naming]] -=== Class Naming - -[[subpackage-structure]] -=== Subpackage Naming - -[[accessor-rules]] -=== Accessor rules - -== Type rules - -=== `typedef` statement - -==== Globally scoped `typedef` - -==== Subtree scoped `typedef` - -Subtree scoped `typedef` statement is type definition, which is not substatement -of `module` or `submodule`, and is only visible to child elements of parent -statement. - -* Representation is generated in Type namespace according to following rules: - - -=== Type mapping - -YANG types does not provide single, simple model of behaviour - some times -exhibits special properties to extensibility or limiting scope of valid values -when type is derived - -//// -.Base types and their behaviours -|=== -| YANG Type | Description | Java Mapping - - -| `binary` | Any binary data | `Binary`? -| `bits` | A set of bits or flags | Custom class -| `boolean` | `true` or `false` | `Boolean` -| `decimal64` | 64-bit signed decimal number | No -| `empty` | A leaf that does not have any value | No -| `enumeration` | Enumerated strings | No -| `identityref` | A reference to an abstract identity | Yes -| `instance-identifier` | References a data tree node | Yes -| `int8` | 8-bit signed integer | No -| `int16` | 16-bit signed integer | No -| `int32` | 32-bit signed integer | No -| `int64` | 64-bit signed integer | No -| `leafref` | A reference to a leaf instance | Maybe -| `string` | Human-readable string | No -| `uint8` | 8-bit unsigned integer | No -| `uint16` | 16-bit unsigned integer | No -| `uint32` | 32-bit unsigned integer | No -| `uint64` | 64-bit unsigned integer | No -| `union` | Choice of member types | Maybe - -|=== -FIXME: Finalize table -//// - -==== `boolean` type -==== `empty` type -==== `int8` type -==== `int16` type -==== `int32` type -==== `int64` type -==== `uint8` type -==== `uint16` type -==== `uint32` type -==== `uint64` type -==== `string` type -==== `binary` type -==== `enumeration` type -==== `bits` type - -==== `identityref` type -==== `instance-identifier` type - -==== `leafref` type -==== `union` type - -[[data-node-rules]] -== Data Node rules - -Data nodes could be separated into two distinct groups, based on presence of -child nodes: - -Leaf node:: - Node, which according to YANG schema does not have child nodes, is leaf node - and carries only simple value. -Interior node:: - Node, which according to YANG schema may have child nodes, node itself does not - carry values, values are stored in descendant leaf nodes. - -=== `leaf` Statement - -=== `leaf-list` Statement - - -=== `container` Statement - -Builders will be located in package "dto" - - -[source,yang] ----- -container foo { -} - -container foo-builder { -} ----- - -[uml, file="container-builder.png"] --- -set namespaceSeparator none - -interface data.Foo { -} - -interface data.FooBuilder { -} --- - -In situations where we have a containing element which has as its child a single container, we should make it easy to autobox it. This should not be implemented in the interfaces themselves, but rather should be a method in the associated builder. - -[source,yang] ----- -container example-outter { - container example-inner { - leaf example { - type string; - } - } -} ----- - -=== `list` Statement - -==== Keyed List - -[source,yang] ----- -list foo { - key "identifier key fookey"; - leaf identifier { - type union { - type string; - } - } - - leaf key { - type string; - } - - leaf fookey { - type string; - } - - leaf boo-non-key { - type string; - } -} ----- -[uml, file="list-Keyed.png"] --- -set namespaceSeparator none - -interface data.Foo { - + getFooIdentifier() : key.foo.FooIdentifier - + getFooKey() : key.foo.FooKey - + getFooFooKey() : key.foo.FooFooKey - + getKey() : key.foo.wrapper.FooKey -} - -interface key.foo.wrapper.FooKey { - + getFooIdentifier() : key.foo.FooIdentifier - + getFooKey() : key.foo.FooKey - + getFooFooKey() : key.foo.FooFooKey -} - -interface type.foo.identifier.IdentifierUnion -interface key.foo.FooIdentifier { - + getIdentifier() : type.foo.identifier.IdentifierUnion -} - -interface key.foo.FooKey { - + getKey() : String -} - -interface key.foo.FooFooKey { - + getFooKey() : String -} - -interface data.foo.FooBooNonKey { - + getBooNonKey() : String -} - -key.foo.FooIdentifier o- type.foo.identifier.IdentifierUnion - -data.foo.FooBooNonKey -u-|> data.Foo -key.foo.wrapper.FooKey -u-|> data.Foo - -key.foo.FooKey -u-|> data.Foo -key.foo.FooFooKey -u-|> data.Foo -key.foo.FooIdentifier -u-|> data.Foo - -key.foo.FooKey -u-|> key.foo.wrapper.FooKey -key.foo.FooFooKey -u-|> key.foo.wrapper.FooKey -key.foo.FooIdentifier -u-|> key.foo.wrapper.FooKey --- - -==== List without Key - -=== `choice` Statement - -=== `case` Statement - -[source,yang] ----- -container top { - choice base { - case foo { - container foo; - } - case bar { - leaf bar { type string; } - } - } -} ----- - -[uml, file="case.png"] --- -set namespaceSeparator none - -package spec { - interface Choice - interface Case -} - -interface data.Top { - + getBase() : data.top.Base; -} -interface data.top.Base -interface data.top.base.Foo { - + getFoo() : data.top.base.foo.Foo -} -interface data.top.base.foo.Foo -interface data.top.base.Bar { - + getBar() : String -} - -data.top.Base -u-|> Choice -data.top.base.Foo -u-|> Case -data.top.base.Bar -u-|> Case - -data.top.base.Foo -u-|> data.top.Base -data.top.base.Bar -u-|> data.top.Base - -data.Top o- data.top.Base -data.top.base.Foo o- data.top.base.foo.Foo --- - -== Specific rules - -[[instantiated-data-node-rules]] -=== Instantiated Data Node Rules - -//// -FIXME: Do we need section per type, or should just general rules be described. -//// - -==== `container` Statement - -//// -FIXME: Here should be Augmentable & Instantiated -//// - -==== `leaf` Statement - -==== `leaf-list` Statement - -==== `choice` Statement - -==== `case` Statement - -//// -FIXME: Here should be Augmentable & Instantiated -//// - -==== `list` Statement - -//// -FIXME: Here should be Augmentable & Instantiated, List signature uses concrete -interfaces -//// - -==== `input` Statement - -//// -FIXME: Here should be Augmentable & Instantiated -//// - -==== `output` Statement - -//// -FIXME: Here should be Augmentable & Instantiated -//// - -==== `notification` Statement - -//// -FIXME: Here should be Augmentable & Instantiated -//// - -[[instantiated-data-tree-rules]] -=== Instantiated Data Tree Rules - - -==== `container` Statement - -//// -FIXME: Here should be Augmentable & Instantied & ChildDataNode -//// - - -==== `leaf` Statement - -==== `leaf-list` Statement - -==== `case` Statement - -//// -FIXME: Here should be Augmentable & Instantied & ChildDataNode -//// - -==== `list` Statement - -//// -FIXME: Here should be Augmentable & Instantied & ChildDataNode -//// - -=== `grouping` Statement - -* `grouping` statement is represented by `interface` -** interface name is generated according to <> with suffix `Grouping` -* Representations of `grouping` statements are generated into <> -* schema nodes under grouping are represented by `interface` and are generated - into <> + name of grouping -** getters (accessors) from parent nodes are generated according to <> -** class name is generated according to <> with suffix `Data` -** schema nodes does not follow <>, these interfaces - are used only in instantiated data tree. - -.Simple Grouping -==== -.YANG Snippet -[source, yang] ----- -grouping simple { <1> - container foo; <2> - leaf bar { type string;} <3> -} ----- -<1> Is represented by interface `grp.SimpleGrouping` -<2> Is represented by interface `grp.simple.FooData` and getter in `grp.SimpleGrouping` - with signature `public grp.simple.FooData getFoo();` -<3> Is represented by getter in `grp.SimpleGrouping` with signature `public String getBar()` - -[uml, file="grouping1.png"] --- -interface grp.SimpleGrouping { - + getBar() : String - + getFoo() : grp.simple.FooData -} -interface grp.simple.FooData -grp.SimpleGrouping o- grp.simple.FooData --- -==== - -==== Data Node substatements - -Representations of data node substatements are generated according to rules -described in <> with following changes: -//// -MS: proposed interface names: -case - Case -choice - <Choice -container, list - -//// -//// -MC: I would keep Data suffix, but idea about distinguishing cases and choices -is to think about -//// -* Interface names for `case`, `choice`, `container` and `list`, is suffixed by - `Data` suffix, in order to not conflict with same named groupings inside same - package -** Getters in parent node, are still generated without `Data` suffix, so - the getter signature is in form `FooData getFoo()` -** If return value of getter is constructed using generics (eg. `list`) - instead of signature `List` or `Map`, wildcarded - `? extends ListItem` generic argument are used to allow for overriding during - <>. - - -==== `list` substatement - -//// -FIXME: Add reasoning / examples for need to use ? extends, instead of directly -using generics. -//// - -==== `leaf-list` susbstatement - -//// -FIXME: Add reasoning / examples for need to use ? extends, instead of directly -using generics for types, which may need instantiation -//// - -[[uses-statement]] -=== `uses` Statement - -* `uses` statement triggers interface of parent statement to extend (implement) - interface of `grouping` referenced by `uses` argument. -* As in YANG `uses` statement triggers instatiation of data children of `grouping` - which will result in generation of these children as-if they were direct - children of parent statement -** data node children are generated according to rules defined for parent statement. - Different rules apply based on parent type (instantiated data tree, `input`, - `output` or `grouping`) -** interfaces generated for data children extends (implements) interfaces for - same children generated for referenced `grouping` - -.Simple Grouping and Uses -==== -.YANG Snippet -[source, yang] ----- -grouping simple { - container foo; - leaf bar { type string;} -} - -container top { - uses simple; -} ----- -[uml, file="grouping2.png"] --- -set namespaceSeparator none - -interface grp.SimpleGrouping { - + getBar() : String - + getFoo() : grp.simple.FooData -} -interface grp.simple.FooData -interface data.Top { - + getFoo() : data.top.Foo -} -interface data.top.Foo - -grp.SimpleGrouping o-- grp.simple.FooData - -data.Top o-- data.top.Foo -data.Top -|> grp.SimpleGrouping -data.top.Foo -|> grp.simple.FooData --- - -NOTE: Diagram does not show all details for `data.Top` and `data.top.Foo`, which -are based on <> - -==== - -.Grouping with Nested Grouping -==== - -.YANG Snippet -[source, yang] ----- -grouping with-inner { - grouping inner { - container cont; - } - uses inner; -} - -container top { - uses with-inner; -} ----- - -[uml, file="grouping3.png"] --- -set namespaceSeparator none - -interface grp.withinner.inner.ContData -interface grp.withinner.InnerGrouping { - + getCont() : grp.withinner.inner.ContData -} - - -interface grp.withinner.ContData - -interface grp.WithInnerGrouping { - + getCont() : grp.withinner.ContData -} - - -interface data.Top { - + getCont() : data.top.Cont -} - -interface data.top.Cont { - -} -data.Top o-- data.top.Cont : contains - -data.Top -|> grp.WithInnerGrouping -data.top.Cont -|> grp.withinner.ContData - -grp.WithInnerGrouping -|> grp.withinner.InnerGrouping : uses (implements) -grp.WithInnerGrouping o-- grp.withinner.ContData : contains -grp.withinner.InnerGrouping o-- grp.withinner.inner.ContData : contains - -grp.withinner.ContData -|> grp.withinner.inner.ContData : is concretization of (implements) - --- - -NOTE: Diagram does not show all details for `data.Top` and `data.top.Cont`, which -are based on <> - -==== - -[[uses-augment]] -==== `augment` substatement - -.Uses & Augment in instantiated Data Tree -==== -[source,yang] ----- -grouping example { - container nested { - leaf foo { - type string; - } - } -} - -container top { - uses example { - augment nested { - container bar { - } - } - } -} - ----- - -[uml, file="grouping4.png"] --- -set namespaceSeparator none - -interface data.Top -interface data.top.Nested -interface data.top.nested.Bar - -data.Top o-- data.top.Nested -data.top.Nested o-- data.top.nested.Bar - -interface grp.ExampleGrouping -interface grp.example.NestedData - - -grp.ExampleGrouping o-- grp.example.NestedData - -data.Top -|> grp.ExampleGrouping -data.top.Nested -|> grp.example.NestedData --- - -NOTE: Diagram does not show all details for `data.Top`, `data.top.Nested` and -`data.top.nested.Bar`, which are based on <> - - -==== - - -.Uses & Augment in grouping -==== -[source,yang] ----- -grouping example { - container nested { - leaf foo { - type string; - } - } -} - -grouping top { - uses example { - augment nested { - container bar { - } - } - } -} - ----- - -[uml, file="grouping5.png"] --- -set namespaceSeparator none - -interface grp.TopGrouping -interface grp.top.NestedData -interface grp.top.nested.BarData - -grp.TopGrouping o-- grp.top.NestedData -grp.top.NestedData o-- grp.top.nested.BarData - -interface grp.ExampleGrouping -interface grp.example.NestedData - -grp.ExampleGrouping o-- grp.example.NestedData - -grp.TopGrouping -|> grp.ExampleGrouping -grp.top.NestedData -|> grp.example.NestedData --- - -==== - -=== `augment` statement - -Representation of `augment` statement depends on module in which target node of -augment statement is defined - -* <> - data nodes are represented - as-if their statements were inlined in target node. - See <> section for details. -* <> - data nodes are - represented as-if their statements were inlined in target. - See <> for details & examples. -* <> - interface representing - augmentation is generated, child data nodes are generated by rules for - <>. - See <> for details & examples. -`augment` statement targets only instantiated data nodes, so child data nodes -representation is always generated. - -[[augment-same-module]] -==== Augmentation target in same module - -All data node children are generated as-if they were directly defined inside -target node. There are no externally observable artefacts in generated -representation of these nodes, which would point out that they were defined -using `augment` statement instead of directly inlining them in target node. - -.Why augment of same module is same as inlining -[IMPORTANT] -==== -This rule may seems counterintuitive at first sight, but YANG defines -backwards compatibility in terms of effective model instead of way how model -is represented. `augment` statement, when targeting node in same module is not -externally observable and could factored out by inlining these statements. - -Definition of `augment` statement in YANG also defines different behaviour when -target is same module and allows all features as-if this statements were -directly inlined. -==== - -.Augment with target in same module -==== -.YANG module written using augmentations -[source,yang] ----- -container top { - -} - -augment "/top" { - container foo { - - } -} ----- -.Same module written without need to augment ----- -container top { - container foo { - - } -} - ----- -.Same module written with grouping ----- -grouping a { - container foo { - } -} - -container top { - uses a; -} - ----- -Java representation for all variants -[uml, file="augment1.png"] --- -set namespaceSeparator none - -interface data.Top -interface data.top.Foo - -data.Top o- data.top.Foo --- - -==== - -[[augment-other-module]] -==== Augmentation target in other module - -.Augment with target in other module -==== -[source,yang] ----- -module top { - ... - - container top { - - } -} - -module foo { - ... - import top { prefix top; } - ... - augment "/top:top" { - container bar { - - } - } -} - ----- - -[uml,file="augment2.png"] --- -set namespaceSeparator none - -interface Augmentable -interface Augmentation - -interface top.data.Top -interface foo.data.FooTop { - + getBar() : Bar -} - -interface foo.data.top.Bar - -top.data.Top -u-|> Augmentable : T = top.data.Top -foo.data.FooTop -u-|> Augmentation : T = top.data.Top -top.data.Top o-- foo.data.FooTop -foo.data.FooTop o-- foo.data.top.Bar --- - -==== - -.Multiple augments with same target -==== -[source,yang] ----- -module top { - ... - - container top { - - } -} - -module foo { - ... - import top { prefix top; } - ... - augment "/top:top" { - container bar { - - } - } - - augment "/top:top" { - container baz { - - } - } -} - ----- - -[uml,file="augment3.png"] --- -set namespaceSeparator none - -interface Augmentable -interface Augmentation - -interface top.data.Top -interface foo.data.FooTop { - + getBar() : Bar - + getBaz() : Baz -} - -interface foo.data.top.Bar -interface foo.data.top.Baz - -top.data.Top -u-|> Augmentable : T = top.data.Top -foo.data.FooTop -u-|> Augmentation : T = top.data.Top -top.data.Top o-- foo.data.FooTop -foo.data.FooTop o-- foo.data.top.Bar -foo.data.FooTop o-- foo.data.top.Baz --- - -==== - -.Multiple augments with different targets -==== -[source,yang] ----- -module target { - ... - - container first { - - } - - container second { - - } -} - -module foo { - ... - import target { prefix t; } - ... - augment "/t:first" { - container bar { - - } - } - - augment "/t:second" { - container baz { - - } - } -} - ----- - -[uml, file="augment4.png"] --- -set namespaceSeparator none - -interface Augmentable -interface Augmentation - -interface target.data.First -interface target.data.Second - -interface foo.data.FooFirst { - + getBar() : Bar -} -interface foo.data.FooSecond { - + getBaz() : Baz -} - -interface foo.data.first.Bar -interface foo.data.second.Baz - -target.data.First -u-|> Augmentable : T = target.data.First -target.data.Second -u-|> Augmentable : T = target.data.Second - -foo.data.FooFirst -u-|> Augmentation : T = target.data.First -foo.data.FooSecond -u-|> Augmentation : T = target.data.Second - - -target.data.First o-- foo.data.FooFirst -target.data.Second o-- foo.data.FooSecond - -foo.data.FooFirst o-- foo.data.first.Bar -foo.data.FooSecond o-- foo.data.second.Baz --- -==== - -.Key in grouping -==== -[source,yang] ----- -grouping nodes { - list node { - key id; - leaf id { - type string; - } - } -} - ----- -grouping key.grp.nodes.node. - -instantiated key.data.nodes.node. diff --git a/binding2/mdsal-binding2-spec/src/test/resources/_.yang b/binding2/mdsal-binding2-spec/src/test/resources/_.yang deleted file mode 100644 index 98122ae904..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/_.yang +++ /dev/null @@ -1,83 +0,0 @@ -module _ { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:underscore"; - include __; - - description - "Testing for the same identifier (single underscore) in different namespaces. - see http://tools.ietf.org/html/rfc6020#section-6.2.1 - - This is basically the same as odl-test-namespaces, - but with "_" instead of a readable identifier. - Additionally, __ submodule is included, which adds container with list. - - Each identifier starts with an uppercase or lowercase ASCII - letter or an underscore character, followed by zero or more ASCII - letters, digits, underscore characters, hyphens, and dots."; - - revision "2016-03-31" { - description - "Initial revision, for ODL Boron."; - } - - extension _ { - description - "All extension names defined in a module and its submodules share - the same extension identifier namespace."; - } - - feature _ { - description - "All feature names defined in a module and its submodules share the - same feature identifier namespace."; - } - - identity _ { - description - "All identity names defined in a module and its submodules share - the same identity identifier namespace."; - } - - typedef _ { - description - "All derived type names defined within a parent node or at the top - level of the module or its submodules share the same type - identifier namespace."; - type string; - } - - grouping _ { - description - "All grouping names defined within a parent node or at the top - level of the module or its submodules share the same grouping - identifier namespace."; - leaf _ { - description - "This namespace is scoped to the parent node or module, unless the - parent node is a case node. In that case, the namespace is scoped - to the closest ancestor node that is not a case or choice node."; - type odl-test-namespaces; - } - } - - container _ { - description - "All leafs, leaf-lists, lists, containers, choices, rpcs, actions, - notifications, anydatas, and anyxmls defined (directly or through - a uses statement) within a parent node or at the top level of the - module or its submodules share the same identifier namespace."; - choice __ { - description - "The leaf from grouping would end up scoped under container, - so the choice has to have a different identifier."; - case _ { - description - "All cases within a choice share the same case identifier - namespace. This namespace is scoped to the parent choice node."; - uses _; - // See descriptions of leaf and choice. - } - } - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/__.yang b/binding2/mdsal-binding2-spec/src/test/resources/__.yang deleted file mode 100644 index 08ec555771..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/__.yang +++ /dev/null @@ -1,26 +0,0 @@ -submodule __ { - yang-version 1; - belongs-to _ { - prefix _; - } - - description - "Testing for an identifier (double underscore). - see http://tools.ietf.org/html/rfc6020#section-6.2.1 - - This is a simple test verifying submodule does not break - handling of _ as identifier."; - - revision "2016-03-31" { - description - "Initial revision, for ODL Boron."; - } - - container __ { - list _ { - key _; - uses _:_; - } - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-double..dot.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-double..dot.yang deleted file mode 100644 index ad03801683..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-double..dot.yang +++ /dev/null @@ -1,14 +0,0 @@ -module odl-test-double..dot { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:double..dot"; - prefix "dd"; - - description - "Module aimed to create package name with two consecutive dots."; - - revision "2016-04-20" { - description - "Initial revision, for ODL Boron."; - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-Bar.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-Bar.yang deleted file mode 100644 index c141c06490..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-Bar.yang +++ /dev/null @@ -1,14 +0,0 @@ -module odl-test-foo-Bar { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:foo-Bar"; - prefix "fmB"; - - description - "One of several modules for testing collisions due to too similar namespaces."; - - revision "2016-04-20" { - description - "Initial revision, for ODL Boron."; - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-bar.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-bar.yang deleted file mode 100644 index 28768a866b..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo-bar.yang +++ /dev/null @@ -1,14 +0,0 @@ -module odl-test-foo-bar { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:foo-bar"; - prefix "fmb"; - - description - "One of several modules for testing collisions due to too similar namespaces."; - - revision "2016-04-20" { - description - "Initial revision, for ODL Boron."; - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo.bar.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo.bar.yang deleted file mode 100644 index 403f0cab21..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-foo.bar.yang +++ /dev/null @@ -1,14 +0,0 @@ -module odl-test-foo.bar { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:foo.bar"; - prefix "fdb"; - - description - "One of several modules for testing collisions due to too similar namespaces."; - - revision "2016-04-20" { - description - "Initial revision, for ODL Boron."; - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-identifiers.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-identifiers.yang deleted file mode 100644 index 1a2ccb30e9..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-identifiers.yang +++ /dev/null @@ -1,52 +0,0 @@ -module odl-test-identifiers { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:identifiers"; - prefix "oti"; - - description - "Testing allowed identifier names. - see http://tools.ietf.org/html/rfc6020#section-6.2"; - - revision "2016-03-31" { - description - "Initial revision, for ODL Boron."; - } - - container items { - list item { - description - "Each identifier starts with an uppercase or lowercase ASCII - letter or an underscore character, followed by zero or more ASCII - letters, digits, underscore characters, hyphens, and dots."; - key "foo Foo FOO fOO foo0 foo_ foo- foo. _foo" - leaf foo { - type string; - } - leaf Foo { - type string; - } - leaf FOO { - type string; - } - leaf fOO { - type string; - } - leaf foo0 { - type string; - } - leaf foo_ { - type string; - } - leaf foo- { - type string; - } - leaf foo. { - type string; - } - leaf _foo { - type string; - } - } - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-namespaces.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-namespaces.yang deleted file mode 100644 index 9fd4d50588..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-namespaces.yang +++ /dev/null @@ -1,78 +0,0 @@ -module odl-test-namespaces { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:namespaces"; - prefix "otn"; - - description - "Testing for the same identifier in different namespaces. - see http://tools.ietf.org/html/rfc6020#section-6.2.1 - - All module and submodule names share the same global module - identifier namespace."; - - revision "2016-03-31" { - description - "Initial revision, for ODL Boron."; - } - - extension odl-test-namespaces { - description - "All extension names defined in a module and its submodules share - the same extension identifier namespace."; - } - - feature odl-test-namespaces { - description - "All feature names defined in a module and its submodules share the - same feature identifier namespace."; - } - - identity odl-test-namespaces { - description - "All identity names defined in a module and its submodules share - the same identity identifier namespace."; - } - - typedef odl-test-namespaces { - description - "All derived type names defined within a parent node or at the top - level of the module or its submodules share the same type - identifier namespace."; - type string; - } - - grouping odl-test-namespaces { - description - "All grouping names defined within a parent node or at the top - level of the module or its submodules share the same grouping - identifier namespace."; - leaf odl-test-namespaces { - description - "This namespace is scoped to the parent node or module, unless the - parent node is a case node. In that case, the namespace is scoped - to the closest ancestor node that is not a case or choice node."; - type odl-test-namespaces; - } - } - - container odl-test-namespaces { - description - "All leafs, leaf-lists, lists, containers, choices, rpcs, actions, - notifications, anydatas, and anyxmls defined (directly or through - a uses statement) within a parent node or at the top level of the - module or its submodules share the same identifier namespace."; - choice nonconflict-identifier { - description - "The leaf from grouping would end up scoped under container, - so the choice has to have a different identifier."; - case odl-test-namespaces { - description - "All cases within a choice share the same case identifier - namespace. This namespace is scoped to the parent choice node."; - uses odl-test-namespaces; - // See descriptions of leaf and choice. - } - } - } - -} diff --git a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-toplevel.yang b/binding2/mdsal-binding2-spec/src/test/resources/odl-test-toplevel.yang deleted file mode 100644 index 7b488ca33c..0000000000 --- a/binding2/mdsal-binding2-spec/src/test/resources/odl-test-toplevel.yang +++ /dev/null @@ -1,99 +0,0 @@ -module odl-test-toplevel { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:binding2:test:toplevel"; - prefix "ott"; - - description - "Testing for various data structures at top level of module. - see http://tools.ietf.org/html/rfc6020#section-7.1.1"; - - revision "2016-03-31" { - description - "Initial revision, for ODL Boron."; - } - - // TODO: Create model with other non-data structures, such as rpc and notification. - // TODO: Test definitions at top level of submodule. - - grouping config-leaf { - leaf config-leaf { - type string; - config true; - } - } - - grouping state-leaf { - leaf state-leaf { - type string; - config false; - } - } - - uses state-leaf; // Top level non-config string leaf named "state-leaf". - - container non-presence-container { - uses config-leaf; - } - - container presence-container { - presence "Container is present."; - uses config-leaf; - } - - leaf-list ordered-leaflist { - ordered-by user; - type string; - } - - leaf-list unordered-leaflist { - ordered-by system; - type string; - } - - list ordered-keyed-list { - ordered-by user; - key config-leaf; - uses config-leaf; - } - - list unordered-keyed-list { - ordered-by system; - key config-leaf; - uses config-leaf; - } - - list ordered-unkeyed-list { - config false; // 'The "key" statement, which MUST be present if the list represents configuration' - ordered-by user; - description - "http://tools.ietf.org/html/rfc6020#section-7.7.5 - says \"This statement is ignored if the list represents state data\", - but we are still hoping for some kind of ordering (perhaps from MD-SAL application?) - to be preserved."; - uses state-leaf; - } - - list unordered-unkeyed-list { - config false; // 'The "key" statement, which MUST be present if the list represents configuration' - ordered-by system; - description - "http://tools.ietf.org/html/rfc6020#section-7.7.5 - says \"This statement is ignored if the list represents state data\", - but we are still hoping the system responds with a reasonable ordering. - - http://tools.ietf.org/html/rfc6020#section-7.7.5.1 - \"An implementation SHOULD use the same order for - the same data, regardless of how the data were created.\""; - uses state-leaf; - } - - choice choice { - case case { - uses config-leaf; - } - } - - anyxml anyxml { - } - -} diff --git a/binding2/mdsal-binding2-spi/pom.xml b/binding2/mdsal-binding2-spi/pom.xml deleted file mode 100644 index cadecf7a65..0000000000 --- a/binding2/mdsal-binding2-spi/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-spi - 0.16.0-SNAPSHOT - bundle - - - - org.opendaylight.mdsal - mdsal-binding2-api - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - org.opendaylight.mdsal - mdsal-common-api - - - org.opendaylight.yangtools - concepts - - - com.google.guava - guava - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - !javax.annotation, - * - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - checkstyle.violationSeverity=error - - - - - - diff --git a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingDataBroker.java b/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingDataBroker.java deleted file mode 100644 index fd66e0eec7..0000000000 --- a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingDataBroker.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright © 2017, 2018 Red Hat, Inc. and others. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.spi; - -import com.google.common.collect.ForwardingObject; -import java.util.Collection; -import javax.annotation.Nonnull; -import org.opendaylight.mdsal.binding.javav2.api.DataBroker; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeListener; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeLoopException; -import org.opendaylight.mdsal.binding.javav2.api.DataTreeProducer; -import org.opendaylight.mdsal.binding.javav2.api.ReadTransaction; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChain; -import org.opendaylight.mdsal.binding.javav2.api.TransactionChainListener; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.yangtools.concepts.ListenerRegistration; - -/** - * Utility {@link DataBroker} implementation which forwards all interface method - * invocation to a delegate instance. - */ -public abstract class ForwardingDataBroker extends ForwardingObject implements DataBroker { - - @Override - protected abstract @Nonnull DataBroker delegate(); - - @Override - public ReadTransaction newReadOnlyTransaction() { - return delegate().newReadOnlyTransaction(); - } - - @Override - public WriteTransaction newWriteOnlyTransaction() { - return delegate().newWriteOnlyTransaction(); - } - - @Nonnull - @Override - public ListenerRegistration registerListener(@Nonnull final T listener, - @Nonnull final Collection> subtrees, final boolean allowRxMerges, - @Nonnull final Collection producers) throws DataTreeLoopException { - return delegate().registerListener(listener, subtrees, allowRxMerges, producers); - } - - @Override - public DataTreeProducer createProducer(final Collection> subtrees) { - return delegate().createProducer(subtrees); - } - - @Override - public TransactionChain createTransactionChain(final TransactionChainListener listener) { - return delegate().createTransactionChain(listener); - } -} diff --git a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingReadTransaction.java b/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingReadTransaction.java deleted file mode 100644 index 7c17bb80d4..0000000000 --- a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingReadTransaction.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright © 2017, 2018 Red Hat, Inc. and others. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.spi; - -import com.google.common.collect.ForwardingObject; -import java.util.function.BiConsumer; -import org.opendaylight.mdsal.binding.javav2.api.ReadTransaction; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; -import org.opendaylight.mdsal.common.api.ReadFailedException; - -/** - * Utility {@link ReadTransaction} implementation which forwards all interface method - * invocation to a delegate instance. - */ -public class ForwardingReadTransaction extends ForwardingObject implements ReadTransaction { - - private final ReadTransaction delegate; - - protected ForwardingReadTransaction(ReadTransaction delegate) { - this.delegate = delegate; - } - - @Override - protected ReadTransaction delegate() { - return delegate; - } - - @Override - public void read(LogicalDatastoreType store, - org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier path, - BiConsumer callback) { - delegate.read(store, path, callback); - } - - @Override - public Object getIdentifier() { - return delegate.getIdentifier(); - } - - @Override - public void close() { - delegate.close(); - } -} diff --git a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingWriteTransaction.java b/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingWriteTransaction.java deleted file mode 100644 index bee94bb4aa..0000000000 --- a/binding2/mdsal-binding2-spi/src/main/java/org/opendaylight/mdsal/binding/javav2/spi/ForwardingWriteTransaction.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright © 2017, 2018 Red Hat, Inc. and others. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.mdsal.binding.javav2.spi; - -import com.google.common.collect.ForwardingObject; -import com.google.common.util.concurrent.FluentFuture; -import org.opendaylight.mdsal.binding.javav2.api.WriteTransaction; -import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier; -import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode; -import org.opendaylight.mdsal.common.api.CommitInfo; -import org.opendaylight.mdsal.common.api.LogicalDatastoreType; - -/** - * Utility {@link WriteTransaction} implementation which forwards all interface method - * invocation to a delegate instance. - */ -public class ForwardingWriteTransaction extends ForwardingObject implements WriteTransaction { - - private final WriteTransaction delegate; - - protected ForwardingWriteTransaction(WriteTransaction delegate) { - this.delegate = delegate; - } - - @Override - protected WriteTransaction delegate() { - return delegate; - } - - @Override - public void put(LogicalDatastoreType store, InstanceIdentifier path, T data) { - delegate.put(store, path, data); - } - - @Override - public void put(LogicalDatastoreType store, InstanceIdentifier path, T data, - boolean createMissingParents) { - delegate.put(store, path, data, createMissingParents); - } - - @Override - public void merge(LogicalDatastoreType store, InstanceIdentifier path, T data) { - delegate.merge(store, path, data); - } - - @Override - public void merge(LogicalDatastoreType store, InstanceIdentifier path, T data, - boolean createMissingParents) { - delegate.merge(store, path, data, createMissingParents); - } - - @Override - public void delete(LogicalDatastoreType store, InstanceIdentifier path) { - delegate.delete(store, path); - } - - @Override - public boolean cancel() { - return delegate.cancel(); - } - - @Override - public FluentFuture commit() { - return delegate.commit(); - } - - @Override - public Object getIdentifier() { - return delegate.getIdentifier(); - } -} diff --git a/binding2/mdsal-binding2-test-model/pom.xml b/binding2/mdsal-binding2-test-model/pom.xml deleted file mode 100644 index f12d99eadf..0000000000 --- a/binding2/mdsal-binding2-test-model/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - org.opendaylight.mdsal - mdsal-model-binding2-parent - 4.0.0-SNAPSHOT - ../mdsal-model-binding2-parent - - - 4.0.0 - mdsal-binding2-test-model - 0.16.0-SNAPSHOT - bundle - ${project.artifactId} - ${project.artifactId} - - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - org.opendaylight.mdsal.model.binding2 - yang-ext - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - - - - diff --git a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContInt32RefUnionInt32Builder.java b/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContInt32RefUnionInt32Builder.java deleted file mode 100644 index f8c9b3e828..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContInt32RefUnionInt32Builder.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data; - -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.ContInt32.RefUnionInt32; - -/** - * The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation. - * In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32). - * The reason behind putting it under src/main/java is: - * This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent - * loss of user code. - */ -public class ContInt32RefUnionInt32Builder { - - public static RefUnionInt32 getDefaultInstance (java.lang.String defaultValue) { - throw new java.lang.UnsupportedOperationException("Not yet implemented"); - } - -} diff --git a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContRefBuilder.java b/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContRefBuilder.java deleted file mode 100644 index 5ae7b9c3e6..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/bug8449/rev170516/data/ContRefBuilder.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data; - -import org.opendaylight.mdsal.gen.javav2.bug8449.rev170516.data.Cont.Ref; - -/** - * The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation. - * In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32). - * The reason behind putting it under src/main/java is: - * This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent - * loss of user code. - */ -public class ContRefBuilder { - - public static Ref getDefaultInstance (java.lang.String defaultValue) { - throw new java.lang.UnsupportedOperationException("Not yet implemented"); - } - -} diff --git a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/opendaylight/params/xml/ns/yang/mdsal/test/binding/rev140701/type/Int32StringUnionBuilder.java b/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/opendaylight/params/xml/ns/yang/mdsal/test/binding/rev140701/type/Int32StringUnionBuilder.java deleted file mode 100755 index db0543d701..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/opendaylight/params/xml/ns/yang/mdsal/test/binding/rev140701/type/Int32StringUnionBuilder.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - - -package org.opendaylight.mdsal.gen.javav2.urn.opendaylight.params.xml.ns.yang.mdsal.test.binding.rev140701.type; - -/** - * The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation. - * In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32). - * The reason behind putting it under src/main/java is: - * This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent - * loss of user code. - */ -public class Int32StringUnionBuilder { - - public static Int32StringUnion getDefaultInstance (java.lang.String defaultValue) { - throw new java.lang.UnsupportedOperationException("Not yet implemented"); - } - -} diff --git a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/test/unsigned/rev180408/type/NumberUnionBuilder.java b/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/test/unsigned/rev180408/type/NumberUnionBuilder.java deleted file mode 100644 index acfd76e348..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/java/org/opendaylight/mdsal/gen/javav2/urn/test/unsigned/rev180408/type/NumberUnionBuilder.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2018 ZTE, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.gen.javav2.urn.test.unsigned.rev180408.type; - -/** - * The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation. - * In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32). - * The reason behind putting it under src/main/java is: - * This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent - * loss of user code. - */ -public class NumberUnionBuilder { - - private NumberUnionBuilder() { - //Exists only to defeat instantiation. - } - - public static NumberUnion getDefaultInstance (java.lang.String defaultValue) { - throw new java.lang.UnsupportedOperationException("Not yet implemented"); - } - -} diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/bug8449.yang b/binding2/mdsal-binding2-test-model/src/main/yang/bug8449.yang deleted file mode 100644 index f21f21e353..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/bug8449.yang +++ /dev/null @@ -1,60 +0,0 @@ -module bug8449 { - yang-version 1; - namespace "bug8449"; - prefix "tst"; - - revision "2017-05-16" { - } - - typedef name1-ref { - type leafref { - path "/tst:top/tst:name1"; - } - } - - typedef name2-ref { - type leafref { - path "/tst:top/tst:name2"; - } - } - - typedef int32-ref { - type leafref { - path "/tst:top-int/tst:leaf-int32"; - } - } - - container top-int { - leaf leaf-int32 { - type uint32; - } - } - - container top { - leaf name1 { - type string; - } - leaf name2 { - type string; - } - } - - container cont-int32 { - leaf ref-union-int32 { - type union { - type int32-ref; - } - } - } - - container cont { - leaf ref { - type union { - type name1-ref; - type name2-ref; - } - mandatory true; - } - } -} - diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang b/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang deleted file mode 100644 index 661bb8a3bb..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang +++ /dev/null @@ -1,189 +0,0 @@ -module opendaylight-mdsal-augment-test { - - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:test:augment"; - prefix aug-test; - - import opendaylight-mdsal-binding-test { - prefix test; - } - import yang-ext { - prefix ext; - } - - description - "This module contains a collection of YANG augmentations used for - some test cases."; - - revision 2014-07-09 { - description - "Test model for testing data broker with nested lists."; - } - - identity third-party { - base test:test-root; - } - - grouping leaf-from-grouping { - leaf leaf-from-grouping { - type string; - } - } - - grouping complex-from-grouping { - container container-with-uses { - uses leaf-from-grouping; - } - list list-via-uses { - key "name"; - leaf name { - type string; - } - } - } - - augment "/test:top/test:top-level-list" { - ext:augment-identifier tree-leaf-only-uses-augment; - uses leaf-from-grouping; - } - - augment "/test:top/test:top-level-list" { - ext:augment-identifier tree-complex-leaves; - leaf simple-type { - type int32; - } - leaf identity { - type test:test-identityref; - } - leaf schema-unaware-union { - type test:int32-string-union; - } - - leaf simple-type-ref { - type leafref { - path "../simple-type"; - } - } - leaf identity-ref { - type leafref { - path "../identity"; - } - } - leaf schema-unaware-union-ref { - type leafref { - path "../schema-unaware-union"; - } - } - } - - - augment "/test:put-top/test:input/test:top-level-list" { - ext:augment-identifier rpc-leaf-only-uses-augment; - uses leaf-from-grouping; - } - - augment "/test:top/test:top-level-list" { - ext:augment-identifier tree-complex-uses-augment; - uses complex-from-grouping; - } - - augment "/test:put-top/test:input/test:top-level-list" { - ext:augment-identifier rpc-complex-uses-augment; - uses complex-from-grouping; - } - - augment "/test:top/test:top-level-list" { - ext:augment-identifier tree-leaf-only-augment; - - leaf simple-value { - type string; - } - } - - augment "/test:top/test:top-level-list" { - ext:augment-identifier tree-second-leaf-only-augment; - - leaf second-simple-value { - type string; - } - } - - augment "/test:put-top/test:input/test:top-level-list" { - ext:augment-identifier rpc-leaf-only-augment; - - leaf simple-value { - type string; - } - } - - augment "/test:put-top/test:input/test:top-level-list" { - ext:augment-identifier rpc-second-leaf-only-augment; - - leaf second-simple-value { - type string; - } - } - - augment "/test:top/test:top-level-list/test:choice-in-list" { - case simple-via-uses { - uses leaf-from-grouping; - } - case empty-leaf { - leaf empty-type { - type empty; - } - } - } - - augment "/test:put-top/test:input/test:top-level-list/test:choice-in-list" { - case simple-via-uses { - uses leaf-from-grouping; - } - } - - augment "/test:top/test:choice-list/test:choice-in-choice-list" { - case complex-via-uses { - uses complex-from-grouping; - } - } - - augment "/test:put-top/test:input/test:choice-list/test:choice-in-choice-list" { - case complex-via-uses-with-different-name { - uses complex-from-grouping; - } - } - - augment "/test:top" { - ext:augment-identifier top-choice-augment1; - choice augment-choice1 { - case case1 { - container case1-container { - leaf case1-leaf { - type string; - } - } - } - - case case2 { - container case2-container { - leaf case2-leaf { - type string; - } - } - } - } - } - - augment "/test:top/augment-choice1/case1" { - ext:augment-identifier top-choice-augment2; - choice augment-choice2 { - case case11 { - container case11-choice-case-container { - leaf case11-choice-case-leaf { - type string; - } - } - } - } - } - -} diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-binding-test.yang b/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-binding-test.yang deleted file mode 100755 index 35c1c17f2f..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/opendaylight-mdsal-binding-test.yang +++ /dev/null @@ -1,147 +0,0 @@ -module opendaylight-mdsal-binding-test { - - namespace "urn:opendaylight:params:xml:ns:yang:mdsal:test:binding"; - prefix list-test; - - - description - "This module contains a collection of YANG definitions used for - some test cases."; - - revision 2014-07-01 { - description - "Test model for testing data broker with nested lists."; - } - - typedef int32-string-union { - type union { - type int32; - type string; - } - } - - identity test-root; - - identity test-one { - base test-root; - } - - identity test-two { - base test-root; - } - - typedef test-identityref { - type identityref { - base test-root; - } - } - - grouping two-level-list { - list top-level-list { - description - "Top Level List"; - key "name"; - leaf name { - type string; - } - - choice choice-in-list { - case simple-case { - leaf simple { - type string; - } - } - } - - list nested-list { - key "name"; - leaf name { - type string; - } - leaf type { - type string; - mandatory true; - description - "Mandatory type of list."; - } - ordered-by user; - description - "A list of service functions that compose the service chain"; - } - } - leaf-list top-level-leaf-list { - type string; - } - - leaf-list top-level-ordered-leaf-list { - type string; - ordered-by user; - } - - list choice-list { - key "name"; - leaf name { - type string; - } - - choice choice-in-choice-list { - - } - } - } - - grouping choice { - choice identifier { - case simple { - container simple-id { - leaf id { - type int32; - } - } - } - case extended { - container extended-id { - leaf id { - type string; - } - } - } - } - } - - container top { - uses two-level-list; - } - - container choice-container { - uses choice; - } - - rpc put-top { - input { - uses two-level-list; - } - } - - notification two-level-list-changed { - uses two-level-list; - } - - rpc get-top { - output { - uses two-level-list; - } - } - - augment "/list-test:top" { - leaf augmented-string { - type string; - } - } - - augment "/list-test:top" { - leaf augmented-int { - type int32; - } - } -} diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-list.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-list.yang deleted file mode 100644 index d593441ffb..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-list.yang +++ /dev/null @@ -1,25 +0,0 @@ -module test-list { - yang-version 1.1; - - namespace "urn:test:simple:test:list"; - prefix test-list; - organization "test.list.org"; - revision "2017-03-14"; - - list my-list { - key "key key1 key2"; - leaf key{ - type string; - } - leaf key1 { - type string; - } - leaf key2 { - type string; - } - leaf foo{ - type string; - } - } - -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-operation-service.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-operation-service.yang deleted file mode 100644 index 49a03cac79..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-operation-service.yang +++ /dev/null @@ -1,76 +0,0 @@ -module test-operation-service { - yang-version 1.1; - namespace "urn:test:operation"; - prefix "operation"; - - revision "2017-06-21" { - description - "Initial revision"; - } - - container my-cont { - action in-cont { - input { - leaf input-leaf { - type string; - } - } - - output { - leaf output-leaf { - type string; - } - } - } - - action in-cont2 { - input { - leaf input-leaf { - type string; - } - } - - output { - leaf output-leaf { - type string; - } - } - } - } - - list my-list { - key "name"; - - leaf name { - type string; - } - - action in-list { - input { - leaf input-list-leaf { - type string; - } - } - - output { - leaf output-list-leaf { - type string; - } - } - } - } - - rpc my-rpc { - input { - leaf rpc-input-leaf { - type string; - } - } - - output { - leaf rpc-output-leaf { - type string; - } - } - } -} diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-pattern.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-pattern.yang deleted file mode 100755 index 43f7f16aef..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-pattern.yang +++ /dev/null @@ -1,37 +0,0 @@ -module test-pattern { - yang-version 1.1; - namespace "urn:test:pattern"; - prefix pattern; - revision 2017-01-01; - - container cont { - leaf test { - type string { - pattern '[a-zA-Z_][a-zA-Z0-9\-_.]*'; - pattern '[xX][mM][lL].*'; - } - } - - leaf test2 { - type string { - pattern '[0-9]*'; - } - } - - - leaf-list test3 { - type string { - pattern '[a-zA-Z_]*'; - pattern '[xX][mM][lL].*' { - modifier invert-match; - } - } - } - - leaf-list test4 { - type string { - pattern '[a-z]*'; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-runtime.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-runtime.yang deleted file mode 100644 index 36526bd156..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-runtime.yang +++ /dev/null @@ -1,22 +0,0 @@ -module test-runtime { - namespace "org.test.runtime"; - prefix "tst"; - revision "2017-07-10" { - } - - container my-cont { - choice my-choice { - case one { - leaf one { - type string; - } - } - case two { - leaf two { - type string; - } - } - - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-typedef.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-typedef.yang deleted file mode 100755 index c87d851d5b..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-typedef.yang +++ /dev/null @@ -1,47 +0,0 @@ -module test-typedef { - yang-version 1; - namespace "urn:test:simple:test:typedef"; - prefix "typedef"; - - revision "2017-08-29" { - } - - typedef policy-logging-flag { - description "false-disable,true-enable"; - type boolean; - } - - typedef typedef-empty { - type empty; - } - - container default-policy{ - leaf action { - type boolean; - } - - leaf action2 { - type policy-logging-flag; - } - - leaf action3 { - type boolean; - default "true"; - } - } - - container test-cont{ - leaf empty-leaf { - type empty; - } - - leaf empty-leaf2 { - type typedef-empty; - } - - leaf empty-leaf3{ - type empty; - default ""; - } - } -} diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test-unsigned-integer.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test-unsigned-integer.yang deleted file mode 100644 index 214687f14f..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test-unsigned-integer.yang +++ /dev/null @@ -1,93 +0,0 @@ -module test-unsigned-integer { - namespace "urn:test:unsigned"; - prefix tst; - - revision 2018-04-08; - - typedef number-union { - type union { - type int8 { - range "-1..100"; - } - - type int16 { - range "-2..2000"; - } - - type int32 { - range "-3..30000"; - } - - type int64 { - range "-4..40000"; - } - - type uint8 { - range "1..100"; - } - - type uint16 { - range "2..2000"; - } - - type uint32 { - range "3..30000"; - } - - type uint64 { - range "4..40000"; - } - } - } - - - container my-cont { - leaf int8-leaf { - type int8 { - range "-1..100"; - } - } - - leaf int16-leaf { - type int16 { - range "-2..2000"; - } - } - - leaf int32-leaf { - type int32 { - range "-3..30000"; - } - } - - leaf int64-leaf { - type int64 { - range "-4..40000"; - } - } - - leaf uint8-leaf { - type uint8 { - range "1..100"; - } - } - - leaf uint16-leaf { - type uint16 { - range "2..2000"; - } - } - - leaf uint32-leaf { - type uint32 { - range "3..30000"; - } - } - - leaf uint64-leaf { - type uint64 { - range "4..40000"; - } - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-test-model/src/main/yang/test.yang b/binding2/mdsal-binding2-test-model/src/main/yang/test.yang deleted file mode 100644 index 3f31fe95cf..0000000000 --- a/binding2/mdsal-binding2-test-model/src/main/yang/test.yang +++ /dev/null @@ -1,18 +0,0 @@ -module test { - namespace "urn:test"; - prefix tst; - - revision 2017-06-27; - - typedef id { - type uint16 { - range "1..4094"; - } - } - - container my-cont { - leaf my-leaf { - type string; - } - } -} \ No newline at end of file diff --git a/binding2/mdsal-binding2-util/pom.xml b/binding2/mdsal-binding2-util/pom.xml deleted file mode 100644 index 96e73a7c63..0000000000 --- a/binding2/mdsal-binding2-util/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - mdsal-binding2-util - 0.16.0-SNAPSHOT - bundle - ${project.artifactId} - ${project.artifactId} - - - - org.opendaylight.yangtools - yang-model-api - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - diff --git a/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/BindingMapping.java b/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/BindingMapping.java deleted file mode 100644 index 56516486b4..0000000000 --- a/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/BindingMapping.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.common.annotations.Beta; -import com.google.common.collect.ImmutableSet; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.opendaylight.yangtools.yang.common.Revision; -import org.opendaylight.yangtools.yang.model.api.Module; - -/** - * Standard Util class that provides generated Java related functionality - */ -@Beta -public final class BindingMapping { - - public static final Set JAVA_RESERVED_WORDS = ImmutableSet.of("abstract", "assert", "boolean", "break", - "byte", "case", "catch", "char", "class", "const", "continue", "default", "double", "do", "else", "enum", - "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", - "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", - "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", - "true", "try", "void", "volatile", "while"); - - public static final Set WINDOWS_RESERVED_WORDS = ImmutableSet.of("CON", "PRN", "AUX", "CLOCK$", "NUL", - "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT0", "LPT1", "LPT2", - "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"); - - public static final String QNAME_STATIC_FIELD_NAME = "QNAME"; - - /** - * Package prefix for Binding v2 generated Java code structures - */ - public static final String PACKAGE_PREFIX = "org.opendaylight.mdsal.gen.javav2"; - - public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl"; - public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider"; - public static final String PATTERN_CONSTANT_NAME = "PATTERN_CONSTANTS"; - public static final String MEMBER_PATTERN_LIST = "patterns"; - public static final String MEMBER_REGEX_LIST = "regexes"; - public static final String RPC_INPUT_SUFFIX = "Input"; - public static final String RPC_OUTPUT_SUFFIX = "Output"; - - private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL); - private static final String QUOTED_DOT = Matcher.quoteReplacement("."); - private static final String NEGATED_PATTERN_PREFIX = "^(?!"; - private static final String NEGATED_PATTERN_SUFFIX = ").*$"; - - private BindingMapping() { - throw new UnsupportedOperationException("Utility class"); - } - - public static String getRootPackageName(final Module module) { - checkArgument(module != null, "Module must not be null"); - checkArgument(module.getRevision() != null, "Revision must not be null"); - checkArgument(module.getNamespace() != null, "Namespace must not be null"); - - final StringBuilder packageNameBuilder = new StringBuilder(); - packageNameBuilder.append(PACKAGE_PREFIX); - packageNameBuilder.append('.'); - - String namespace = module.getNamespace().toString(); - namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT); - - final char[] chars = namespace.toCharArray(); - for (int i = 0; i < chars.length; ++i) { - switch (chars[i]) { - case '/': - case ':': - case '-': - case '@': - case '$': - case '#': - case '\'': - case '*': - case '+': - case ',': - case ';': - case '=': - chars[i] = '.'; - break; - default: - // no-op, any other character is kept as it is - } - } - - packageNameBuilder.append(chars); - if (chars[chars.length - 1] != '.') { - packageNameBuilder.append('.'); - } - - //TODO: per yangtools dev, semantic version not used yet -// final SemVer semVer = module.getSemanticVersion(); -// if (semVer != null) { -// packageNameBuilder.append(semVer.toString()); -// } else { -// packageNameBuilder.append("rev"); -// packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision())); -// } - - final Optional optRev = module.getRevision(); - if (optRev.isPresent()) { - // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the - // right characters. - final String rev = optRev.get().toString(); - checkArgument(rev.length() == 10, "Unsupported revision %s", rev); - packageNameBuilder.append("rev").append(rev, 2, 4).append(rev, 5, 7).append(rev.substring(8)); - } else { - // No-revision packages are special - packageNameBuilder.append("norev"); - } - return packageNameBuilder.toString(); - } - - /** - * Create a {@link Pattern} expression which performs inverted match to the specified pattern. The input pattern - * is expected to be a valid regular expression passing {@link Pattern#compile(String)} and to have both start and - * end of string anchors as the first and last characters. - * - * @param pattern Pattern regular expression to negate - * @return Negated regular expression - * @throws IllegalArgumentException if the pattern does not conform to expected structure - * @throws NullPointerException if pattern is null - */ - public static String negatePatternString(final String pattern) { - checkArgument(pattern.charAt(0) == '^' && pattern.charAt(pattern.length() - 1) == '$', - "Pattern '%s' does not have expected format", pattern); - - /* - * Converting the expression into a negation is tricky. For example, when we have: - * - * pattern "a|b" { modifier invert-match; } - * - * this gets escaped into either "^a|b$" or "^(?:a|b)$". Either format can occur, as the non-capturing group - * strictly needed only in some cases. From that we want to arrive at: - * "^(?!(?:a|b)$).*$". - * - * ^^^ original expression - * ^^^^^^^^ tail of a grouped expression (without head anchor) - * ^^^^ ^^^^ inversion of match - * - * Inversion works by explicitly anchoring at the start of the string and then: - * - specifying a negative lookahead until the end of string - * - matching any string - * - anchoring at the end of the string - */ - final boolean hasGroup = pattern.startsWith("^(?:") && pattern.endsWith(")$"); - final int len = pattern.length(); - final StringBuilder sb = new StringBuilder(len + (hasGroup ? 7 : 11)).append(NEGATED_PATTERN_PREFIX); - - if (hasGroup) { - sb.append(pattern, 1, len); - } else { - sb.append("(?:").append(pattern, 1, len - 1).append(")$"); - } - return sb.append(NEGATED_PATTERN_SUFFIX).toString(); - } - - /** - * Check if the specified {@link Pattern} is the result of {@link #negatePatternString(String)}. This method - * assumes the pattern was not hand-coded but rather was automatically-generated, such that its non-automated - * parts come from XSD regular expressions. If this constraint is violated, this method may result false positives. - * - * @param pattern Pattern to check - * @return True if this pattern is a negation. - * @throws NullPointerException if pattern is null - * @throws IllegalArgumentException if the pattern does not conform to expected structure - */ - public static boolean isNegatedPattern(final Pattern pattern) { - return isNegatedPattern(pattern.toString()); - } - - private static boolean isNegatedPattern(final String pattern) { - return pattern.startsWith(NEGATED_PATTERN_PREFIX) && pattern.endsWith(NEGATED_PATTERN_SUFFIX); - } - - //TODO: further implementation of static util methods... - -} diff --git a/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/StringValueObjectFactory.java b/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/StringValueObjectFactory.java deleted file mode 100644 index 76650c03fd..0000000000 --- a/binding2/mdsal-binding2-util/src/main/java/org/opendaylight/mdsal/binding/javav2/util/StringValueObjectFactory.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.mdsal.binding.javav2.util; - -import static java.util.Objects.requireNonNull; - -import com.google.common.annotations.Beta; -import com.google.common.base.Throwables; -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.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for instantiating value-type generated objects with String being the base type. Unlike the normal - * constructor, instances of this class bypass string validation. - * - * THE USE OF THIS CLASS IS DANGEROUS AND SHOULD ONLY BE USED TO IMPLEMENT WELL-AUDITED AND CORRECT UTILITY METHODS - * SHIPPED WITH MODELS TO PROVIDE INSTANTIATION FROM TYPES DIFFERENT THAN STRING. - * - * APPLICATION CODE MUST NOT USE THIS CLASS DIRECTLY. VIOLATING THIS CONSTRAINT HAS SECURITY AND CORRECTNESS - * IMPLICATIONS ON EVERY USER INTERACTING WITH THE RESULTING OBJECTS. - * - * @param Resulting object type - */ -@Beta -public final class StringValueObjectFactory { - - private static final MethodType CONSTRUCTOR_METHOD_TYPE = MethodType.methodType(Object.class, Object.class); - private static final MethodType SETTER_METHOD_TYPE = MethodType.methodType(void.class, Object.class, String.class); - private static final Logger LOG = LoggerFactory.getLogger(StringValueObjectFactory.class); - private static final Lookup LOOKUP = MethodHandles.lookup(); - - private final MethodHandle constructor; - private final MethodHandle setter; - private final T template; - - private StringValueObjectFactory(final T template, final MethodHandle constructor, final MethodHandle setter) { - this.template = requireNonNull(template); - this.constructor = constructor.bindTo(template); - this.setter = requireNonNull(setter); - } - - public static StringValueObjectFactory create(final Class clazz, final String templateString) { - final Constructor stringConstructor; - try { - stringConstructor = clazz.getConstructor(String.class); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(String.format("%s does not have a String constructor", clazz), e); - } - - final T template; - try { - template = stringConstructor.newInstance(templateString); - } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) { - throw new IllegalArgumentException(String.format("Failed to instantiate template %s for '%s'", clazz, - templateString), e); - } - - final Constructor copyConstructor; - try { - copyConstructor = clazz.getConstructor(clazz); - } catch (NoSuchMethodException e) { - throw new IllegalArgumentException(String.format("%s does not have a copy constructor", clazz), e); - } - - final Field f; - try { - f = clazz.getDeclaredField("_value"); - } catch (NoSuchFieldException e) { - throw new IllegalArgumentException(String.format("%s does not have required internal field", clazz), e); - } - f.setAccessible(true); - - final StringValueObjectFactory ret; - try { - ret = new StringValueObjectFactory<>(template, - LOOKUP.unreflectConstructor(copyConstructor).asType(CONSTRUCTOR_METHOD_TYPE), - LOOKUP.unreflectSetter(f).asType(SETTER_METHOD_TYPE)); - } catch (IllegalAccessException e) { - throw new IllegalStateException("Failed to instantiate method handles", e); - } - - // Let us be very defensive and scream loudly if the invocation does not come from the same package. This - // is far from perfect, but better than nothing. - final Throwable t = new Throwable("Invocation stack"); - t.fillInStackTrace(); - if (matchesPackage(clazz.getPackage().getName(), t.getStackTrace())) { - LOG.info("Instantiated factory for {}", clazz); - } else { - LOG.warn("Instantiated factory for {} outside its package", clazz, t); - } - - return ret; - } - - private static boolean matchesPackage(final String pkg, final StackTraceElement[] stackTrace) { - for (StackTraceElement e : stackTrace) { - final String sp = e.getClassName(); - if (sp.startsWith(pkg) && sp.lastIndexOf('.') == pkg.length()) { - return true; - } - } - - return false; - } - - public T newInstance(final String string) { - requireNonNull(string, "Argument may not be null"); - - try { - final T ret = (T) constructor.invokeExact(); - setter.invokeExact(ret, string); - LOG.trace("Instantiated new object {} value {}", ret.getClass(), string); - return ret; - } catch (Throwable e) { - throw Throwables.propagate(e); - } - } - - public T getTemplate() { - return template; - } -} diff --git a/binding2/mdsal-model-binding2-parent/pom.xml b/binding2/mdsal-model-binding2-parent/pom.xml deleted file mode 100644 index 8229f27574..0000000000 --- a/binding2/mdsal-model-binding2-parent/pom.xml +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - - org.opendaylight.mdsal - dom-parent - 4.0.0-SNAPSHOT - ../../dom/dom-parent - - - 4.0.0 - mdsal-model-binding2-parent - pom - - - ${project.build.directory}/generated-sources/mdsal-binding2 - - - - - - - src/main/resources - - - ${project.build.directory}/generated-sources/spi - - - ${project.build.directory}/generated-sources/yang - - - - - - - binding2-generator - - - src/main/yang - - - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - - - - - org.opendaylight.yangtools - yang-maven-plugin - 2.1.8 - - - org.opendaylight.mdsal - mdsal-binding2-maven-api-gen-plugin - 0.16.0-SNAPSHOT - jar - - - - - binding2 - - generate-sources - - - - - org.opendaylight.mdsal.binding.javav2.maven.api.gen.plugin.CodeGeneratorImpl - ${salGeneratorPath} - - - true - - - - - - maven-clean-plugin - - - - ${salGeneratorPath} - - ** - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-yang-sources - generate-sources - - add-source - - - - ${salGeneratorPath} - - - - - - - - - - org.opendaylight.yangtools - yang-maven-plugin - - - org.codehaus.mojo - build-helper-maven-plugin - - - - - - diff --git a/binding2/pom.xml b/binding2/pom.xml deleted file mode 100644 index 2e12232a24..0000000000 --- a/binding2/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - org.opendaylight.odlparent - odlparent-lite - 4.0.9 - - - - 4.0.0 - org.opendaylight.mdsal - binding2-aggregator - 4.0.0-SNAPSHOT - pom - ${project.artifactId} - ${project.artifactId} - - - mdsal-binding2-spec - mdsal-model-binding2-parent - - - mdsal-binding2-maven-api-gen-plugin - mdsal-binding2-generator-api - mdsal-binding2-generator-impl - mdsal-binding2-java-api-generator - mdsal-binding2-generator-util - - - mdsal-binding2-api - mdsal-binding2-runtime - mdsal-binding2-dom-codec - mdsal-binding2-dom-adapter - mdsal-binding2-spi - - - mdsal-binding2-util - mdsal-binding2-test-model - - - - true - true - - diff --git a/features/features-mdsal-experimental/pom.xml b/features/features-mdsal-experimental/pom.xml index 557882028f..ee9946b884 100644 --- a/features/features-mdsal-experimental/pom.xml +++ b/features/features-mdsal-experimental/pom.xml @@ -42,37 +42,5 @@ features xml - - - - org.opendaylight.mdsal - odl-mdsal-binding2 - features - xml - - - org.opendaylight.mdsal - odl-mdsal-binding2-api - features - xml - - - org.opendaylight.mdsal - odl-mdsal-binding2-base - features - xml - - - org.opendaylight.mdsal - odl-mdsal-binding2-dom-adapter - features - xml - - - org.opendaylight.mdsal - odl-mdsal-binding2-runtime - features - xml - diff --git a/features/odl-mdsal-binding2-api/pom.xml b/features/odl-mdsal-binding2-api/pom.xml deleted file mode 100644 index 0c39b2fa84..0000000000 --- a/features/odl-mdsal-binding2-api/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - feature-parent - 4.0.0-SNAPSHOT - ../feature-parent - - - odl-mdsal-binding2-api - feature - OpenDaylight :: MD-SAL :: Binding2 API - MD-SAL Java Binding 2 APIs (experimental) - - - - org.opendaylight.mdsal - odl-mdsal-common - xml - features - - - org.opendaylight.mdsal - odl-mdsal-binding2-base - xml - features - - - org.opendaylight.mdsal - odl-mdsal-dom-api - xml - features - - - org.opendaylight.mdsal - mdsal-binding2-api - - - org.opendaylight.mdsal - mdsal-binding2-spi - - - org.opendaylight.mdsal - mdsal-binding2-util - - - diff --git a/features/odl-mdsal-binding2-base/pom.xml b/features/odl-mdsal-binding2-base/pom.xml deleted file mode 100644 index edccfe8c30..0000000000 --- a/features/odl-mdsal-binding2-base/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - feature-parent - 4.0.0-SNAPSHOT - ../feature-parent - - - odl-mdsal-binding2-base - feature - OpenDaylight :: MD-SAL :: Binding 2 Base - MD-SAL Java Binding 2 base support (experimental) - - - - org.opendaylight.yangtools - odl-yangtools-parser-api - xml - features - - - org.opendaylight.mdsal - mdsal-binding2-spec - - - org.opendaylight.mdsal.model.binding2 - yang-ext - - - diff --git a/features/odl-mdsal-binding2-base/src/main/feature/feature.xml b/features/odl-mdsal-binding2-base/src/main/feature/feature.xml deleted file mode 100644 index b7ec6de97d..0000000000 --- a/features/odl-mdsal-binding2-base/src/main/feature/feature.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - odl-yangtools-parser-api - - diff --git a/features/odl-mdsal-binding2-dom-adapter/pom.xml b/features/odl-mdsal-binding2-dom-adapter/pom.xml deleted file mode 100644 index deb5232244..0000000000 --- a/features/odl-mdsal-binding2-dom-adapter/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - feature-parent - 4.0.0-SNAPSHOT - ../feature-parent - - - odl-mdsal-binding2-dom-adapter - feature - OpenDaylight :: MD-SAL :: Binding 2 :: DOM Adapter - MD-SAL Java Binding 2/DOM adapter (experimental) - - - - org.opendaylight.mdsal - odl-mdsal-binding2-runtime - xml - features - - - org.opendaylight.mdsal - mdsal-binding2-dom-adapter - provided - - - diff --git a/features/odl-mdsal-binding2-runtime/pom.xml b/features/odl-mdsal-binding2-runtime/pom.xml deleted file mode 100644 index dda996cb6e..0000000000 --- a/features/odl-mdsal-binding2-runtime/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - feature-parent - 4.0.0-SNAPSHOT - ../feature-parent - - - odl-mdsal-binding2-runtime - feature - OpenDaylight :: MD-SAL :: Binding 2 Runtime - MD-SAL Java Binding 2 runtime (experimental) - - - - org.opendaylight.odlparent - odl-apache-commons-lang3 - xml - features - - - org.opendaylight.odlparent - odl-javassist-3 - xml - features - - - org.opendaylight.yangtools - odl-yangtools-data - xml - features - - - org.opendaylight.mdsal - odl-mdsal-binding2-api - xml - features - - - org.opendaylight.mdsal - mdsal-binding2-generator-api - - - org.opendaylight.mdsal - mdsal-binding2-generator-util - - - org.opendaylight.mdsal - mdsal-binding2-dom-codec - provided - - - diff --git a/features/odl-mdsal-binding2-runtime/src/main/feature/feature.xml b/features/odl-mdsal-binding2-runtime/src/main/feature/feature.xml deleted file mode 100644 index 1f95dc7ff6..0000000000 --- a/features/odl-mdsal-binding2-runtime/src/main/feature/feature.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - odl-javassist-3 - odl-apache-commons-lang3 - odl-yangtools-data - - diff --git a/features/odl-mdsal-binding2/pom.xml b/features/odl-mdsal-binding2/pom.xml deleted file mode 100644 index b4a5d403a1..0000000000 --- a/features/odl-mdsal-binding2/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.mdsal - feature-parent - 4.0.0-SNAPSHOT - ../feature-parent - - - odl-mdsal-binding2 - feature - OpenDaylight :: MD-SAL :: Binding 2 - MD-SAL full Java Binding 2 functionality (experimental) - - - - org.opendaylight.mdsal - odl-mdsal-binding2-dom-adapter - features - xml - - - org.opendaylight.mdsal - odl-mdsal-dom - features - xml - - - diff --git a/features/pom.xml b/features/pom.xml index 55a9b6d5ff..6ba20a70d6 100644 --- a/features/pom.xml +++ b/features/pom.xml @@ -34,13 +34,6 @@ odl-mdsal-binding-dom-adapter odl-mdsal-binding-runtime - - odl-mdsal-binding2 - odl-mdsal-binding2-api - odl-mdsal-binding2-base - odl-mdsal-binding2-dom-adapter - odl-mdsal-binding2-runtime - odl-mdsal-common diff --git a/model-binding2/pom.xml b/model-binding2/pom.xml deleted file mode 100644 index 374c9549e1..0000000000 --- a/model-binding2/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - org.opendaylight.odlparent - odlparent-lite - 4.0.9 - - - - 4.0.0 - org.opendaylight.mdsal.model.binding2 - 4.0.0-SNAPSHOT - model-aggregator - pom - ${project.artifactId} - ${project.artifactId} - - - yang-ext - - - - true - true - - diff --git a/model-binding2/yang-ext/pom.xml b/model-binding2/yang-ext/pom.xml deleted file mode 100644 index 6628e13adf..0000000000 --- a/model-binding2/yang-ext/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - org.opendaylight.mdsal - mdsal-model-binding2-parent - 4.0.0-SNAPSHOT - ../../binding2/mdsal-model-binding2-parent - - - 4.0.0 - org.opendaylight.mdsal.model.binding2 - yang-ext - 2013.09.07.16.0-SNAPSHOT - ${project.artifactId} - ${project.artifactId} - bundle - diff --git a/model-binding2/yang-ext/src/main/yang/yang-ext.yang b/model-binding2/yang-ext/src/main/yang/yang-ext.yang deleted file mode 100644 index f8452737f5..0000000000 --- a/model-binding2/yang-ext/src/main/yang/yang-ext.yang +++ /dev/null @@ -1,78 +0,0 @@ -module yang-ext { - yang-version 1; - namespace "urn:opendaylight:yang:extension:yang-ext"; - prefix "ext"; - - contact "Anton Tkacik "; - - description - "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"; - - revision "2013-07-09" { - description ""; - } - - // Augmentation name - - extension "augment-identifier" { - description - "YANG language extension which assigns an identifier to - augmentation. Augment identifier is used to identify - specific augment statement by name. - - The identifier syntax is defined formally defined by the rule - 'identifier' in Section 12 of RFC 6020. - - All augment identifiers defined in a namespace MUST be unique. - The namespace of augment identifiers is shared by module and - its submodules."; - - /* - Discussion: - This extension allows for ease of development / debug - of YANG modules and it is suitable for code generation, - where each augment statement is nicely identified by - unique name instead of combination of augment target - and when condition. - */ - argument "identifier"; - } - - // Context-aware RPCs - - grouping rpc-context-ref { - description - "A reference to RPC context."; - leaf context-instance { - type instance-identifier; - description "Pointer to the context. "; - } - } - - extension "rpc-context-instance" { - description - "YANG language extension which defines enclosing (parent) - schema node as referencable context for RPCs. - - The argument is identity which is used to identify RPC context - type."; - - argument "context-type"; - } - - extension "context-reference" { - argument "context-type"; - } - - extension "context-instance" { - argument "context-type"; - } - - extension "instance-target" { - argument "path"; - } -} diff --git a/pom.xml b/pom.xml index bcbeb96e1b..f97bf80d40 100644 --- a/pom.xml +++ b/pom.xml @@ -30,9 +30,7 @@ features dom binding - binding2 model - model-binding2 entityownership singleton-service trace -- 2.36.6