From 45263f50896a7021cd17d78ce83b29365cb19c29 Mon Sep 17 00:00:00 2001 From: Jozsef Csongvai Date: Mon, 26 Jul 2021 12:00:59 -0400 Subject: Revert "Renaming Files having BluePrint to have Blueprint" The renaming in CCSDK-3098 caused breaking changes to the grpc api and compile issues for kotlin scripts. Issue-ID: CCSDK-3385 Change-Id: I0d745cb858371678eabcb2284671c1fd76a1ab6d Signed-off-by: Jozsef Csongvai --- ms/artifact-manager/README | 38 +- ms/artifact-manager/manager/servicer.py | 60 +- ms/artifact-manager/server.py | 4 +- ms/artifact-manager/tests/servicer_test.py | 64 +- .../BluePrintProcessorCluster.kt | 87 +++ .../BlueprintDatabaseConfiguration.kt | 4 +- .../cds/blueprintsprocessor/BlueprintGRPCServer.kt | 8 +- .../BlueprintProcessorCluster.kt | 87 --- .../actuator/indicator/BluePrintCustomIndicator.kt | 56 ++ .../actuator/indicator/BlueprintCustomIndicator.kt | 56 -- .../blueprintsprocessor/uat/utils/UatExecutor.kt | 8 +- .../blueprintsprocessor/uat/utils/UatServices.kt | 2 +- .../src/main/resources/application-dev.properties | 2 +- .../src/main/resources/application-local.yml | 2 +- .../src/main/resources/application.properties | 2 +- .../uat/BlueprintsAcceptanceTest.kt | 4 +- .../cds/blueprintsprocessor/uat/UatServicesTest.kt | 4 +- .../src/test/resources/application.properties | 4 +- .../executor/ComponentRemoteAnsibleExecutor.kt | 4 +- .../executor/ComponentRemoteAnsibleExecutorTest.kt | 30 +- .../cli/executor/CliExecutorExtensions.kt | 4 +- .../cli/executor/ComponentCliExecutorTest.kt | 32 +- .../snapshots/db/ResourceConfigSnapshotService.kt | 4 +- .../ComponentConfigSnapshotsExecutorTest.kt | 28 +- .../config/snapshots/TestDatabaseConfiguration.kt | 4 +- .../k8s/K8sConnectionPluginConfiguration.kt | 14 +- .../k8s/definition/K8sPluginDefinitionApi.kt | 20 +- .../profile/K8sProfileUploadComponent.kt | 30 +- .../template/K8sConfigTemplateComponent.kt | 24 +- .../definition/template/K8sConfigValueComponent.kt | 28 +- .../functions/k8s/instance/K8sPluginInstanceApi.kt | 60 +- .../prioritization/MessagePrioritizeExtensions.kt | 6 +- .../kafka/AbstractMessagePrioritizeProcessor.kt | 4 +- .../kafka/DefaultMessagePrioritizeProcessor.kt | 6 +- .../kafka/KafkaMessagePrioritizationConsumer.kt | 10 +- .../kafka/MessagePrioritizationSerde.kt | 4 +- .../AbstractNatsMessagePrioritizationService.kt | 4 +- .../nats/NatsMessagePrioritizationConsumer.kt | 14 +- .../MessagePrioritizationStateServiceImpl.kt | 4 +- .../utils/MessageCorrelationUtils.kt | 4 +- .../prioritization/utils/MessageProcessorUtils.kt | 18 +- .../MessagePrioritizationConsumerTest.kt | 30 +- .../netconf/executor/NetconfExecutorExtensions.kt | 4 +- .../executor/ComponentNetconfExecutorTest.kt | 12 +- .../python/executor/ComponentJythonExecutor.kt | 12 +- .../executor/ComponentRemotePythonExecutor.kt | 10 +- .../executor/ComponentRemotePythonExecutorDSL.kt | 44 +- .../python/executor/JythonComponentFunction.kt | 6 +- .../executor/scripts/BlueprintJythonServiceImpl.kt | 16 +- .../python/executor/scripts/BlueprintPythonHost.kt | 8 +- .../scripts/BlueprintPythonInterpreterProxy.kt | 6 +- .../scripts/PythonExecutorConfiguration.kt | 2 +- .../python/executor/ComponentJythonExecutorTest.kt | 12 +- .../ComponentRemotePythonExecutorDSLTest.kt | 6 +- .../executor/ComponentRemotePythonExecutorTest.kt | 42 +- .../executor/scripts/BlueprintJythonServiceTest.kt | 6 +- .../executor/scripts/BlueprintPythonHostTest.kt | 4 +- .../resolution/ResourceAssignmentRuntimeService.kt | 14 +- .../resource/resolution/ResourceDefinitionDSL.kt | 10 +- .../resolution/ResourceResolutionComponent.kt | 8 +- .../resolution/ResourceResolutionComponentDSL.kt | 48 +- .../resolution/ResourceResolutionExtensions.kt | 12 +- .../resolution/ResourceResolutionService.kt | 54 +- .../resource/resolution/ResourceSourceDSL.kt | 104 +-- .../capabilities/IpAssignResolutionCapability.kt | 12 +- .../capabilities/NamingResolutionCapability.kt | 12 +- .../resolution/db/ResourceResolutionDBService.kt | 30 +- .../resolution/db/TemplateResolutionService.kt | 20 +- .../CapabilityResourceResolutionProcessor.kt | 4 +- .../DatabaseResourceAssignmentProcessor.kt | 20 +- .../DefaultResourceResolutionProcessor.kt | 6 +- .../processor/InputResourceResolutionProcessor.kt | 10 +- .../processor/ResourceAssignmentProcessor.kt | 36 +- .../processor/RestResourceResolutionProcessor.kt | 22 +- .../resolution/utils/ResourceAssignmentUtils.kt | 72 +- .../resolution/utils/ResourceDefinitionUtils.kt | 6 +- .../resolution/ResourceDefinitionDSLTest.kt | 10 +- .../ResourceResolutionComponentDSLTest.kt | 6 +- .../resolution/ResourceResolutionComponentTest.kt | 18 +- .../resolution/ResourceResolutionServiceTest.kt | 32 +- .../resource/resolution/ResourceSourceDSLTest.kt | 22 +- .../resolution/TestDatabaseConfiguration.kt | 4 +- .../IpAssignResolutionCapabilityTest.kt | 16 +- .../capabilities/NamingResolutionCapabilityTest.kt | 24 +- .../db/ResourceResolutionDBServiceTest.kt | 18 +- .../resolution/db/TemplateResolutionServiceTest.kt | 14 +- .../mock/MockBluePrintRestLibPropertyService.kt | 36 + .../mock/MockBlueprintRestLibPropertyService.kt | 36 - .../resolution/mock/MockDatabaseConfiguration.kt | 18 +- .../mock/MockRestResourceResolutionProcessor.kt | 18 +- .../CapabilityResourceResolutionProcessorTest.kt | 16 +- .../DatabaseResourceResolutionProcessorTest.kt | 8 +- .../DefaultResourceResolutionProcessorTest.kt | 4 +- .../InputResourceResolutionProcessorTest.kt | 4 +- .../RestResourceResolutionProcessorTest.kt | 20 +- .../utils/ResourceAssignmentUtilsTest.kt | 4 +- .../executor/RestconfExecutorExtensions.kt | 16 +- .../executor/ComponentRestconfExecutorTest.kt | 18 +- .../restful/executor/RestfulCMComponentFunction.kt | 10 +- .../executor/ComponentRestfulExecutorTest.kt | 18 +- .../nrmfunction/RestfulNRMServiceClientTest.kt | 8 +- .../core/BluePrintConstants.kt | 260 +++++++ .../controllerblueprints/core/BluePrintError.kt | 38 + .../core/BluePrintException.kt | 34 + .../core/BluePrintExtensionFunctions.kt | 148 ++++ .../core/BluePrintProcessorException.kt | 175 +++++ .../controllerblueprints/core/BluePrintTypes.kt | 170 +++++ .../core/BlueprintConstants.kt | 260 ------- .../controllerblueprints/core/BlueprintError.kt | 38 - .../core/BlueprintException.kt | 34 - .../core/BlueprintExtensionFunctions.kt | 148 ---- .../core/BlueprintProcessorException.kt | 175 ----- .../controllerblueprints/core/BlueprintTypes.kt | 170 ----- .../controllerblueprints/core/CustomFunctions.kt | 28 +- .../core/FileExtensionFunctions.kt | 8 +- .../core/annotations/BluePrintsAnnotations.kt | 100 +++ .../core/annotations/BlueprintsAnnotations.kt | 100 --- .../core/config/BluePrintLoadConfiguration.kt | 29 + .../core/config/BlueprintLoadConfiguration.kt | 29 - .../core/data/BluePrintExpressionData.kt | 77 ++ .../core/data/BluePrintGraph.kt | 182 +++++ .../core/data/BluePrintModel.kt | 736 +++++++++++++++++++ .../core/data/BlueprintExpressionData.kt | 77 -- .../core/data/BlueprintGraph.kt | 182 ----- .../core/data/BlueprintModel.kt | 736 ------------------- .../controllerblueprints/core/dsl/BluePrintDSL.kt | 424 +++++++++++ .../core/dsl/BluePrintDSLBuilder.kt | 478 ++++++++++++ .../core/dsl/BluePrintDSLData.kt | 83 +++ .../core/dsl/BluePrintServiceTemplateGenerator.kt | 211 ++++++ .../core/dsl/BluePrintTemplateDSLBuilder.kt | 482 +++++++++++++ .../core/dsl/BluePrintTypeDSLBuilder.kt | 585 +++++++++++++++ .../core/dsl/BluePrintWorkflowDSLBuilder.kt | 121 ++++ .../controllerblueprints/core/dsl/BlueprintDSL.kt | 424 ----------- .../core/dsl/BlueprintDSLBuilder.kt | 478 ------------ .../core/dsl/BlueprintDSLData.kt | 83 --- .../core/dsl/BlueprintServiceTemplateGenerator.kt | 211 ------ .../core/dsl/BlueprintTemplateDSLBuilder.kt | 482 ------------- .../core/dsl/BlueprintTypeDSLBuilder.kt | 585 --------------- .../core/dsl/BlueprintWorkflowDSLBuilder.kt | 121 ---- .../core/dsl/ServiceTemplateBuilder.kt | 14 +- .../core/interfaces/BluePrintCatalogService.kt | 57 ++ .../core/interfaces/BluePrintDefinitions.kt | 60 ++ .../core/interfaces/BluePrintEnhancer.kt | 242 +++++++ .../core/interfaces/BluePrintRepoService.kt | 50 ++ .../core/interfaces/BluePrintScriptsService.kt | 39 + .../BluePrintWorkflowExecutionService.kt | 28 + .../core/interfaces/BlueprintCatalogService.kt | 57 -- .../core/interfaces/BlueprintDefinitions.kt | 60 -- .../core/interfaces/BlueprintEnhancer.kt | 242 ------- .../core/interfaces/BlueprintFunctionNode.kt | 20 +- .../core/interfaces/BlueprintRepoService.kt | 50 -- .../core/interfaces/BlueprintScriptsService.kt | 39 - .../core/interfaces/BlueprintTemplateService.kt | 10 +- .../core/interfaces/BlueprintValidator.kt | 94 +-- .../BlueprintWorkflowExecutionService.kt | 28 - .../core/scripts/BluePrintCompileService.kt | 187 +++++ .../core/scripts/BluePrintCompilerCache.kt | 67 ++ .../core/scripts/BluePrintScriptsServiceImpl.kt | 82 +++ .../core/scripts/BlueprintCompileService.kt | 187 ----- .../core/scripts/BlueprintCompilerCache.kt | 67 -- .../core/scripts/BlueprintScriptsServiceImpl.kt | 82 --- .../core/service/BluePrintChainedService.kt | 125 ++++ .../core/service/BluePrintContext.kt | 354 +++++++++ .../core/service/BluePrintDependencyService.kt | 62 ++ .../core/service/BluePrintExpressionService.kt | 235 ++++++ .../core/service/BluePrintImportService.kt | 95 +++ .../core/service/BluePrintJinjaTemplateService.kt | 115 +++ .../core/service/BluePrintRepoFileService.kt | 76 ++ .../core/service/BluePrintRuntimeService.kt | 799 +++++++++++++++++++++ .../core/service/BluePrintTemplateService.kt | 65 ++ .../core/service/BluePrintValidatorService.kt | 711 ++++++++++++++++++ .../service/BluePrintVelocityTemplateService.kt | 99 +++ .../core/service/BluePrintWorkflowService.kt | 353 +++++++++ .../core/service/BlueprintChainedService.kt | 125 ---- .../core/service/BlueprintContext.kt | 354 --------- .../core/service/BlueprintDependencyService.kt | 62 -- .../core/service/BlueprintExpressionService.kt | 235 ------ .../core/service/BlueprintImportService.kt | 95 --- .../core/service/BlueprintJinjaTemplateService.kt | 115 --- .../core/service/BlueprintRepoFileService.kt | 76 -- .../core/service/BlueprintRuntimeService.kt | 799 --------------------- .../core/service/BlueprintTemplateService.kt | 65 -- .../core/service/BlueprintValidatorService.kt | 711 ------------------ .../service/BlueprintVelocityTemplateService.kt | 99 --- .../core/service/BlueprintWorkflowService.kt | 353 --------- .../core/service/PropertyAssignmentService.kt | 90 +-- .../core/utils/BluePrintArchiveUtils.kt | 279 +++++++ .../core/utils/BluePrintFileUtils.kt | 327 +++++++++ .../core/utils/BluePrintIOUtils.kt | 41 ++ .../core/utils/BluePrintMetadataUtils.kt | 280 ++++++++ .../core/utils/BluePrintRuntimeUtils.kt | 64 ++ .../core/utils/BlueprintArchiveUtils.kt | 279 ------- .../core/utils/BlueprintFileUtils.kt | 327 --------- .../core/utils/BlueprintIOUtils.kt | 41 -- .../core/utils/BlueprintMetadataUtils.kt | 280 -------- .../core/utils/BlueprintRuntimeUtils.kt | 64 -- .../core/utils/ClusterUtils.kt | 10 +- .../controllerblueprints/core/utils/DateUtils.kt | 8 +- .../core/utils/JacksonUtils.kt | 110 +-- .../core/utils/PropertyDefinitionUtils.kt | 2 +- .../core/utils/ResourceResolverUtils.kt | 4 +- .../core/utils/WorkflowGraphUtils.kt | 6 +- ...trollerblueprints.scripts.BluePrintKotlinScript | 0 ...trollerblueprints.scripts.BlueprintKotlinScript | 0 .../core/BluePrintErrorTest.kt | 33 + .../core/BlueprintErrorTest.kt | 33 - .../core/CustomFunctionsTest.kt | 16 +- .../controllerblueprints/core/MDCContextTest.kt | 6 +- .../core/annotations/BluePrintsAnnotationsTest.kt | 119 +++ .../core/annotations/BlueprintsAnnotationsTest.kt | 119 --- .../core/dsl/BluePrintDSLTest.kt | 318 ++++++++ .../core/dsl/BlueprintDSLTest.kt | 318 -------- .../scripts/BluePrintScriptsServiceImplTest.kt | 88 +++ .../scripts/BlueprintScriptsServiceImplTest.kt | 88 --- .../core/service/BluePrintContextTest.kt | 588 +++++++++++++++ .../core/service/BluePrintExpressionServiceTest.kt | 140 ++++ .../core/service/BluePrintRepoFileServiceTest.kt | 58 ++ .../core/service/BluePrintRuntimeServiceTest.kt | 299 ++++++++ .../core/service/BluePrintTemplateServiceTest.kt | 82 +++ .../core/service/BluePrintWorkflowServiceTest.kt | 272 +++++++ .../core/service/BlueprintContextTest.kt | 588 --------------- .../core/service/BlueprintExpressionServiceTest.kt | 140 ---- .../core/service/BlueprintRepoFileServiceTest.kt | 58 -- .../core/service/BlueprintRuntimeServiceTest.kt | 299 -------- .../core/service/BlueprintTemplateServiceTest.kt | 82 --- .../core/service/BlueprintWorkflowServiceTest.kt | 272 ------- .../core/utils/BluePrintFileUtilsTest.kt | 57 ++ .../core/utils/BluePrintIOUtilsTest.kt | 41 ++ .../core/utils/BluePrintMetadataUtilsTest.kt | 82 +++ .../core/utils/BlueprintFileUtilsTest.kt | 57 -- .../core/utils/BlueprintIOUtilsTest.kt | 41 -- .../core/utils/BlueprintMetadataUtilsTest.kt | 82 --- .../core/utils/JacksonUtilsTest.kt | 16 +- .../core/utils/PropertyDefinitionUtilsTest.kt | 2 +- .../Scripts/kotlin/ActivateBlueprintDefinitions.kt | 12 +- .../BluePrintArtifactDefinitionValidatorImpl.kt | 99 +++ .../BluePrintArtifactTypeValidatorImpl.kt | 36 + .../BluePrintAttributeDefinitionValidatorImpl.kt | 92 +++ .../validation/BluePrintDataTypeValidatorImpl.kt | 35 + .../BluePrintDesignTimeValidatorService.kt | 86 +++ .../BluePrintNodeTemplateValidatorImpl.kt | 274 +++++++ .../validation/BluePrintNodeTypeValidatorImpl.kt | 179 +++++ .../BluePrintPropertyDefinitionValidatorImpl.kt | 89 +++ .../BluePrintServiceTemplateValidatorImpl.kt | 115 +++ .../BluePrintTopologyTemplateValidatorImpl.kt | 76 ++ .../BluePrintTypeValidatorServiceImpl.kt | 115 +++ .../validation/BluePrintValidationConfiguration.kt | 24 + .../validation/BluePrintWorkflowValidatorImpl.kt | 110 +++ .../BlueprintArtifactDefinitionValidatorImpl.kt | 99 --- .../BlueprintArtifactTypeValidatorImpl.kt | 36 - .../BlueprintAttributeDefinitionValidatorImpl.kt | 92 --- .../validation/BlueprintDataTypeValidatorImpl.kt | 35 - .../BlueprintDesignTimeValidatorService.kt | 86 --- .../BlueprintNodeTemplateValidatorImpl.kt | 274 ------- .../validation/BlueprintNodeTypeValidatorImpl.kt | 179 ----- .../BlueprintPropertyDefinitionValidatorImpl.kt | 89 --- .../BlueprintServiceTemplateValidatorImpl.kt | 115 --- .../BlueprintTopologyTemplateValidatorImpl.kt | 76 -- .../BlueprintTypeValidatorServiceImpl.kt | 115 --- .../validation/BlueprintValidationConfiguration.kt | 24 - .../validation/BlueprintWorkflowValidatorImpl.kt | 110 --- .../extension/ArtifactMappingResourceValidator.kt | 12 +- .../extension/ResourceDefinitionValidation.kt | 12 +- .../utils/PropertyAssignmentValidationUtils.kt | 36 +- .../BluePrintDesignTimeValidatorServiceTest.kt | 117 +++ .../BlueprintDesignTimeValidatorServiceTest.kt | 117 --- .../MockBluePrintTypeValidatorService.kt | 86 +++ .../MockBlueprintTypeValidatorService.kt | 86 --- .../dict/factory/ResourceSourceMappingFactory.kt | 4 +- .../service/ResourceAssignmentValidationService.kt | 10 +- .../dict/utils/BulkResourceSequencingUtils.kt | 4 +- .../resource/dict/utils/ResourceDictionaryUtils.kt | 14 +- .../ResourceAssignmentValidationServiceTest.kt | 6 +- .../dict/utils/ResourceDictionaryUtilsTest.java | 4 +- .../db/BluePrintDBLibConfiguration.kt | 81 +++ .../blueprintsprocessor/db/BluePrintDBLibData.kt | 52 ++ .../db/BluePrintDBLibGenericService.kt | 44 ++ .../db/BlueprintDBLibConfiguration.kt | 81 --- .../blueprintsprocessor/db/BlueprintDBLibData.kt | 52 -- .../db/BlueprintDBLibGenericService.kt | 44 -- .../db/DatabasePropertiesDSL.kt | 30 +- .../db/primary/BluePrintDBLibPropertyService.kt | 79 ++ .../db/primary/BlueprintDBLibPropertyService.kt | 79 -- .../db/primary/MariaDatabaseConfiguration.kt | 4 +- .../db/primary/MySqlDatabaseConfiguration.kt | 4 +- .../primary/service/BlueprintCatalogServiceImpl.kt | 38 +- .../BlueprintProcessorCatalogServiceImpl.kt | 54 +- .../db/BlueprintProcessorCatalogServiceImplTest.kt | 20 +- .../db/DatabasePropertiesDSLTest.kt | 10 +- .../db/TestDatabaseConfiguration.kt | 2 +- .../MockBlueprintProcessorCatalogServiceImpl.kt | 12 +- .../dmaap/AafAuthDmaapClientService.kt | 2 +- .../dmaap/BluePrintDmaapClientService.kt | 106 +++ .../dmaap/BluePrintDmaapLibConfiguration.kt | 48 ++ .../dmaap/BluePrintDmaapLibPropertyService.kt | 202 ++++++ .../dmaap/BlueprintDmaapClientService.kt | 106 --- .../dmaap/BlueprintDmaapLibConfiguration.kt | 48 -- .../dmaap/BlueprintDmaapLibPropertyService.kt | 202 ------ .../dmaap/HttpNoAuthDmaapClientService.kt | 2 +- .../dmaap/TestDmaapEventPublisher.kt | 14 +- .../grpc/BluePrintGrpcExtensions.kt | 27 + .../grpc/BluePrintGrpcLibConfiguration.kt | 55 ++ .../grpc/BluePrintGrpcLibData.kt | 67 ++ .../grpc/BlueprintGrpcExtensions.kt | 27 - .../grpc/BlueprintGrpcLibConfiguration.kt | 55 -- .../grpc/BlueprintGrpcLibData.kt | 67 -- .../blueprintsprocessor/grpc/GrpcPropertiesDSL.kt | 60 +- .../interceptor/GrpcServerLoggingInterceptor.kt | 22 +- .../grpc/service/BasicAuthGrpcClientService.kt | 2 +- .../service/BluePrintGrpcLibPropertyService.kt | 182 +++++ .../grpc/service/BluePrintGrpcService.kt | 31 + .../service/BlueprintGrpcLibPropertyService.kt | 182 ----- .../grpc/service/BlueprintGrpcService.kt | 31 - .../grpc/service/GrpcLoggerService.kt | 14 +- .../grpc/service/TLSAuthGrpcClientService.kt | 2 +- .../grpc/service/TLSAuthGrpcServerService.kt | 2 +- .../grpc/service/TokenAuthGrpcClientService.kt | 2 +- .../grpc/GrpcPropertiesDSLTest.kt | 18 +- .../service/BluePrintGrpcLibPropertyServiceTest.kt | 218 ++++++ .../grpc/service/BluePrintGrpcServerTest.kt | 110 +++ .../service/BlueprintGrpcLibPropertyServiceTest.kt | 218 ------ .../grpc/service/BlueprintGrpcServerTest.kt | 110 --- .../service/MockTLSBluePrintProcessingServer.kt | 92 +++ .../service/MockTLSBlueprintProcessingServer.kt | 92 --- .../message/BluePrintMessageExtensions.kt | 31 + .../message/BluePrintMessageLibConfiguration.kt | 71 ++ .../message/BluePrintMessageLibData.kt | 264 +++++++ .../message/BlueprintMessageExtensions.kt | 31 - .../message/BlueprintMessageLibConfiguration.kt | 71 -- .../message/BlueprintMessageLibData.kt | 264 ------- .../message/MessagePropertiesDSL.kt | 94 +-- .../kafka/AbstractKafkaTopologyComponents.kt | 6 +- .../message/kafka/KafkaJDBCStores.kt | 8 +- .../service/BluePrintMessageLibPropertyService.kt | 228 ++++++ .../service/BlueprintMessageConsumerService.kt | 6 +- .../service/BlueprintMessageLibPropertyService.kt | 228 ------ .../message/service/KafkaStreamsConsumerService.kt | 6 +- .../message/service/MessageLoggerService.kt | 14 +- .../message/utils/BlueprintMessageUtils.kt | 4 +- .../message/MessagePropertiesDSLTest.kt | 18 +- .../service/BlueprintMessageConsumerServiceTest.kt | 12 +- .../service/BlueprintMessageProducerServiceTest.kt | 18 +- .../service/KafkaStreamsConsumerServiceTest.kt | 12 +- .../message/service/MessageLoggerServiceTest.kt | 4 +- .../message/service/MockKafkaTopologyComponents.kt | 4 +- .../message/utils/BlueprintMessageUtilsTest.kt | 4 +- .../nats/BluePrintNatsExtensions.kt | 36 + .../nats/BluePrintNatsLibConfiguration.kt | 49 ++ .../nats/BluePrintNatsLibData.kt | 45 ++ .../nats/BlueprintNatsExtensions.kt | 36 - .../nats/BlueprintNatsLibConfiguration.kt | 49 -- .../nats/BlueprintNatsLibData.kt | 45 -- .../blueprintsprocessor/nats/NatsPropertiesDSL.kt | 30 +- .../service/BluePrintNatsLibPropertyService.kt | 95 +++ .../nats/service/BluePrintNatsService.kt | 143 ++++ .../service/BlueprintNatsLibPropertyService.kt | 95 --- .../nats/service/BlueprintNatsService.kt | 143 ---- .../nats/service/TLSAuthNatsService.kt | 2 +- .../nats/service/TokenAuthNatsService.kt | 2 +- .../nats/utils/NatsClusterUtils.kt | 6 +- .../nats/NatsPropertiesDSLTest.kt | 10 +- .../nats/service/BluePrintNatsExtensionsTest.kt | 51 ++ .../service/BluePrintNatsLibPropertyServiceTest.kt | 56 ++ .../nats/service/BluePrintNatsServiceTest.kt | 267 +++++++ .../nats/service/BlueprintNatsExtensionsTest.kt | 51 -- .../service/BlueprintNatsLibPropertyServiceTest.kt | 56 -- .../nats/service/BlueprintNatsServiceTest.kt | 267 ------- .../core/BluePrintCoreConfiguration.kt | 88 +++ .../core/BlueprintCoreConfiguration.kt | 88 --- .../core/api/data/BlueprintProcessorData.kt | 4 +- .../core/cluster/BluePrintClusterExtensions.kt | 75 ++ .../core/cluster/BlueprintClusterExtensions.kt | 75 -- .../core/cluster/HazelcastClusterService.kt | 24 +- .../core/factory/ComponentNodeFactory.kt | 10 +- .../BlueprintCompilerCacheMessageListener.kt | 12 +- .../core/service/BluePrintClusterService.kt | 106 +++ .../core/service/BlueprintClusterService.kt | 106 --- .../blueprintsprocessor/core/utils/PayloadUtils.kt | 18 +- .../core/BluePrintPropertiesTest.kt | 20 + .../core/BlueprintPropertiesTest.kt | 20 - .../core/cluster/BluePrintClusterExtensionsTest.kt | 74 ++ .../core/cluster/BlueprintClusterExtensionsTest.kt | 74 -- .../core/cluster/HazelcastClusterServiceTest.kt | 30 +- .../core/utils/BluePrintMappingsTest.kt | 137 ++++ .../core/utils/BlueprintMappingsTest.kt | 137 ---- .../rest/BluePrintRestLibConfiguration.kt | 61 ++ .../rest/BluePrintRestLibData.kt | 66 ++ .../rest/BlueprintRestLibConfiguration.kt | 61 -- .../rest/BlueprintRestLibData.kt | 66 -- .../rest/RestClientPropertiesDSL.kt | 34 +- .../service/BluePrintRestLibPropertyService.kt | 222 ++++++ .../service/BlueprintRestLibPropertyService.kt | 222 ------ .../rest/service/BlueprintWebClientService.kt | 18 +- .../rest/service/RestLoggerService.kt | 16 +- .../service/BluePrintRestLibPropertyServiceTest.kt | 532 ++++++++++++++ .../service/BlueprintRestLibPropertyServiceTest.kt | 532 -------------- .../rest/service/RestClientPropertiesDSLTest.kt | 10 +- .../rest/service/RestClientServiceTest.kt | 12 +- .../ssh/BluePrintSshLibConfiguration.kt | 51 ++ .../blueprintsprocessor/ssh/BluePrintSshLibData.kt | 34 + .../ssh/BlueprintSshLibConfiguration.kt | 51 -- .../blueprintsprocessor/ssh/BlueprintSshLibData.kt | 34 - .../blueprintsprocessor/ssh/SshPropertiesDSL.kt | 26 +- .../ssh/service/BasicAuthSshClientService.kt | 10 +- .../ssh/service/BluePrintSshLibPropertyService.kt | 87 +++ .../ssh/service/BlueprintSshLibPropertyService.kt | 87 --- .../ssh/SshPropertiesDSLTest.kt | 10 +- .../service/BluePrintSshLibPropertyServiceTest.kt | 64 ++ .../ssh/service/BlueprintSshClientServiceTest.kt | 14 +- .../service/BlueprintSshLibPropertyServiceTest.kt | 64 -- .../api/ResourceConfigSnapshotControllerTest.kt | 6 +- .../configs/api/TestDatabaseConfiguration.kt | 4 +- .../designer/api/BluePrintManagementGRPCHandler.kt | 320 +++++++++ .../designer/api/BlueprintManagementGRPCHandler.kt | 320 --------- .../designer/api/BlueprintModelController.kt | 36 +- .../designer/api/DesignerApiData.kt | 6 +- .../designer/api/ModelTypeController.kt | 4 +- .../designer/api/ResourceDictionaryController.kt | 8 +- .../BluePrintArtifactDefinitionEnhancerImpl.kt | 92 +++ .../BluePrintAttributeDefinitionEnhancerImpl.kt | 55 ++ .../api/enhancer/BluePrintEnhancerServiceImpl.kt | 103 +++ .../enhancer/BluePrintNodeTemplateEnhancerImpl.kt | 68 ++ .../api/enhancer/BluePrintNodeTypeEnhancerImpl.kt | 157 ++++ .../enhancer/BluePrintPolicyTypeEnhancerImpl.kt | 44 ++ .../BluePrintPropertyDefinitionEnhancerImpl.kt | 64 ++ .../BluePrintRelationshipTemplateEnhancerImpl.kt | 69 ++ .../BluePrintRelationshipTypeEnhancerImpl.kt | 87 +++ .../BluePrintServiceTemplateEnhancerImpl.kt | 67 ++ .../BluePrintTopologyTemplateEnhancerImpl.kt | 74 ++ .../enhancer/BluePrintTypeEnhancerServiceImpl.kt | 84 +++ .../api/enhancer/BluePrintWorkflowEnhancerImpl.kt | 233 ++++++ .../BlueprintArtifactDefinitionEnhancerImpl.kt | 92 --- .../BlueprintAttributeDefinitionEnhancerImpl.kt | 55 -- .../api/enhancer/BlueprintEnhancerServiceImpl.kt | 103 --- .../enhancer/BlueprintNodeTemplateEnhancerImpl.kt | 68 -- .../api/enhancer/BlueprintNodeTypeEnhancerImpl.kt | 157 ---- .../enhancer/BlueprintPolicyTypeEnhancerImpl.kt | 44 -- .../BlueprintPropertyDefinitionEnhancerImpl.kt | 64 -- .../BlueprintRelationshipTemplateEnhancerImpl.kt | 69 -- .../BlueprintRelationshipTypeEnhancerImpl.kt | 87 --- .../BlueprintServiceTemplateEnhancerImpl.kt | 67 -- .../BlueprintTopologyTemplateEnhancerImpl.kt | 74 -- .../enhancer/BlueprintTypeEnhancerServiceImpl.kt | 84 --- .../api/enhancer/BlueprintWorkflowEnhancerImpl.kt | 233 ------ .../enhancer/ResourceAssignmentEnhancerService.kt | 26 +- .../enhancer/ResourceDefinitionEnhancerService.kt | 28 +- .../designer/api/handler/BluePrintModelHandler.kt | 643 +++++++++++++++++ .../designer/api/handler/BlueprintModelHandler.kt | 643 ----------------- .../designer/api/handler/ModelTypeHandler.kt | 6 +- .../api/handler/ResourceDictionaryHandler.kt | 10 +- .../api/load/BluePrintCatalogLoadService.kt | 69 ++ .../api/load/BluePrintDatabaseLoadService.kt | 67 ++ .../api/load/BlueprintCatalogLoadService.kt | 69 -- .../api/load/BlueprintDatabaseLoadService.kt | 67 -- .../designer/api/load/ModelTypeLoadService.kt | 14 +- .../api/load/ResourceDictionaryLoadService.kt | 4 +- .../api/service/BluePrintRepoServiceImpl.kt | 115 +++ .../api/service/BlueprintRepoServiceImpl.kt | 115 --- .../designer/api/utils/BluePrintEnhancerUtils.kt | 191 +++++ .../designer/api/utils/BlueprintEnhancerUtils.kt | 191 ----- .../designer/api/utils/ModelTypeValidator.kt | 28 +- .../api/BluePrintManagementGRPCHandlerTest.kt | 252 +++++++ .../api/BlueprintManagementGRPCHandlerTest.kt | 252 ------- .../designer/api/BlueprintModelControllerTest.kt | 14 +- .../designer/api/ModelTypeControllerTest.kt | 12 +- .../designer/api/TestDatabaseConfiguration.kt | 4 +- .../enhancer/BluePrintEnhancerServiceImplTest.kt | 114 +++ .../enhancer/BlueprintEnhancerServiceImplTest.kt | 114 --- .../designer/api/handler/ModelTypeServiceTest.kt | 14 +- .../api/repository/ModelTypeReactRepositoryTest.kt | 18 +- .../api/utils/BluePrintEnhancerUtilsTest.kt | 68 ++ .../api/utils/BlueprintEnhancerUtilsTest.kt | 68 -- .../configuration/HealthCheckProperties.kt | 4 +- .../service/health/AbstractHealthCheck.kt | 2 +- .../health/BluePrintProcessorHealthCheck.kt | 40 ++ .../health/BlueprintProcessorHealthCheck.kt | 40 -- .../healthapi/HealthCheckServiceTest.kt | 8 +- .../healthapi/controller/CombinedMetrics.kt | 4 +- .../healthapi/service/CombinedHealthService.kt | 4 +- .../healthapi/service/CombinedMetricsService.kt | 4 +- .../healthapi/HealthCheckApplicationTests.kt | 10 +- .../resource/api/ResourceControllerTest.kt | 4 +- .../resource/api/TemplateControllerTest.kt | 8 +- .../resource/api/TestDatabaseConfiguration.kt | 4 +- .../api/BluePrintProcessingGRPCHandler.kt | 111 +++ .../api/BluePrintProcessingKafkaConsumer.kt | 157 ++++ .../api/BlueprintProcessingGRPCHandler.kt | 111 --- .../api/BlueprintProcessingKafkaConsumer.kt | 157 ---- .../selfservice/api/ExecutionServiceController.kt | 8 +- .../selfservice/api/ExecutionServiceHandler.kt | 30 +- .../selfservice/api/KafkaPublishAuditService.kt | 30 +- .../api/utils/BlueprintProcessingUtils.kt | 24 +- .../validation/BluePrintRuntimeValidatorService.kt | 29 + .../validation/BlueprintRuntimeValidatorService.kt | 29 - .../api/BluePrintProcessingGRPCHandlerTest.kt | 133 ++++ .../api/BluePrintProcessingIntegrationTest.kt | 100 +++ .../api/BluePrintProcessingKafkaConsumerTest.kt | 80 +++ .../api/BlueprintProcessingGRPCHandlerTest.kt | 133 ---- .../api/BlueprintProcessingIntegrationTest.kt | 100 --- .../api/BlueprintProcessingKafkaConsumerTest.kt | 80 --- .../api/ExecutionServiceControllerTest.kt | 10 +- .../selfservice/api/ExecutionServiceHandlerTest.kt | 4 +- .../selfservice/api/TestDatabaseConfiguration.kt | 4 +- .../api/utils/BlueprintProcessingUtilsTest.kt | 18 +- .../BluePrintRuntimeValidatorServiceTest.kt | 51 ++ .../BlueprintRuntimeValidatorServiceTest.kt | 51 -- .../execution/AbstractComponentFunction.kt | 38 +- .../execution/AbstractScriptComponentFunction.kt | 26 +- .../services/execution/AbstractServiceFunction.kt | 4 +- .../execution/ComponentFunctionScriptingService.kt | 24 +- .../execution/ComponentRemoteScriptExecutor.kt | 12 +- .../execution/ComponentRemoteScriptExecutorDSL.kt | 34 +- .../execution/ComponentScriptExecutorDSL.kt | 38 +- .../execution/RemoteScriptExecutionService.kt | 8 +- .../execution/StreamingRemoteExecutionService.kt | 22 +- .../execution/scripts/BlueprintJythonService.kt | 10 +- .../execution/ComponentRemoteScriptExecutorTest.kt | 24 +- .../execution/MockBluePrintProcessingServer.kt | 107 +++ .../execution/MockBlueprintProcessingServer.kt | 107 --- .../StreamingRemoteExecutionServiceTest.kt | 8 +- .../scripts/AbstractComponentFunctionTest.kt | 34 +- .../BluePrintWorkflowExecutionServiceImpl.kt | 111 +++ .../services/workflow/BlueprintSvcLogicContext.kt | 8 +- .../services/workflow/BlueprintSvcLogicService.kt | 8 +- .../BlueprintWorkflowExecutionServiceImpl.kt | 111 --- .../workflow/ComponentWorkflowExecutionService.kt | 10 +- .../workflow/DGWorkflowExecutionService.kt | 10 +- .../workflow/ImperativeWorkflowExecutionService.kt | 44 +- .../workflow/NodeTemplateExecutionService.kt | 20 +- .../executor/ComponentExecuteNodeExecutor.kt | 2 +- .../BluePrintWorkflowExecutionServiceImplTest.kt | 185 +++++ .../services/workflow/BlueprintServiceLogicTest.kt | 24 +- .../BlueprintWorkflowExecutionServiceImplTest.kt | 185 ----- .../workflow/DGWorkflowExecutionServiceTest.kt | 18 +- .../ImperativeWorkflowExecutionServiceTest.kt | 24 +- .../workflow/NodeTemplateExecutionServiceTest.kt | 18 +- .../workflow/mock/MockComponentFunction.kt | 4 +- ms/py-executor/blueprints_grpc/__init__.py | 4 +- .../blueprints_grpc/blueprint_processing_server.py | 4 +- ms/py-executor/blueprints_grpc/executor_utils.py | 4 +- ms/py-executor/client.py | 8 +- ms/py-executor/resource_resolution/README.md | 12 +- ms/py-executor/resource_resolution/grpc/client.py | 6 +- .../resource_resolution/resource_resolution.py | 6 +- ms/py-executor/server.py | 18 +- .../SdcListenerNotificationCallback.java | 4 +- .../handler/BluePrintProcesssorHandler.java | 67 ++ .../handler/BlueprintProcesssorHandler.java | 67 -- .../cds/sdclistener/service/ListenerService.java | 4 +- .../sdclistener/service/ListenerServiceImpl.java | 20 +- .../handler/BluePrintProcessorHandlerTest.java | 124 ++++ .../handler/BlueprintProcessorHandlerTest.java | 124 ---- .../service/ListenerServiceImplTest.java | 12 +- 553 files changed, 23784 insertions(+), 23784 deletions(-) create mode 100644 ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BluePrintProcessorCluster.kt delete mode 100644 ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorCluster.kt create mode 100644 ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BluePrintCustomIndicator.kt delete mode 100644 ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BlueprintCustomIndicator.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBluePrintRestLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBlueprintRestLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintConstants.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintError.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintException.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintExtensionFunctions.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintProcessorException.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintTypes.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotations.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BlueprintLoadConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintExpressionData.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintGraph.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintModel.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSL.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLBuilder.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLData.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintServiceTemplateGenerator.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTemplateDSLBuilder.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTypeDSLBuilder.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintWorkflowDSLBuilder.kt create mode 100755 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintCatalogService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintDefinitions.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintEnhancer.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintRepoService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintScriptsService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintWorkflowExecutionService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompileService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompilerCache.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintChainedService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContext.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintDependencyService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintImportService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintJinjaTemplateService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintValidatorService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintVelocityTemplateService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowService.kt create mode 100755 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt create mode 100755 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintRuntimeUtils.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BlueprintKotlinScript create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintErrorTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotationsTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContextTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtilsTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTemplateValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTypeValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactDefinitionValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactTypeValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintAttributeDefinitionValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDataTypeValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTemplateValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTypeValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintPropertyDefinitionValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintServiceTemplateValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTopologyTemplateValidatorImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTypeValidatorServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintValidationConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintWorkflowValidatorImpl.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt delete mode 100644 ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBlueprintTypeValidatorService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibGenericService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BlueprintDBLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcExtensions.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcServerTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBlueprintProcessingServer.kt create mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt create mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageExtensions.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsExtensions.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsExtensions.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsExtensionsTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsExtensionsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintCoreConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensions.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensions.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BluePrintClusterService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BlueprintClusterService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintPropertiesTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensionsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensionsTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BlueprintMappingsTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BlueprintProcessorHealthCheck.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumer.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingIntegrationTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBlueprintProcessingServer.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImplTest.kt create mode 100644 ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcesssorHandler.java delete mode 100644 ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcesssorHandler.java create mode 100644 ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcessorHandlerTest.java delete mode 100644 ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcessorHandlerTest.java (limited to 'ms') diff --git a/ms/artifact-manager/README b/ms/artifact-manager/README index d77762842..290dadfde 100644 --- a/ms/artifact-manager/README +++ b/ms/artifact-manager/README @@ -38,9 +38,9 @@ Upload `CBA.zip` file for storage in artifact manager. File needs to be sent as #### Example ``` -stub: BlueprintManagementServiceStub = BlueprintManagementServiceStub(channel) +stub: BluePrintManagementServiceStub = BluePrintManagementServiceStub(channel) with open(file_path, "rb") as cba_file: - msg: BlueprintUploadInput = BlueprintUploadInput() + msg: BluePrintUploadInput = BluePrintUploadInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" msg.fileChunk.chunk = cba_file.read() @@ -54,8 +54,8 @@ Download existing `CBA.zip` file. #### Example ``` -stub: BlueprintManagementServiceStub = BlueprintManagementServiceStub(channel) -msg: BlueprintDownloadInput = BlueprintDownloadInput() +stub: BluePrintManagementServiceStub = BluePrintManagementServiceStub(channel) +msg: BluePrintDownloadInput = BluePrintDownloadInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" return stub.downloadBlueprint(msg) @@ -67,8 +67,8 @@ Delete existing `CBA.zip` file. #### Example ``` -stub: BlueprintManagementServiceStub = BlueprintManagementServiceStub(channel) -msg: BlueprintRemoveInput = BlueprintRemoveInput() +stub: BluePrintManagementServiceStub = BluePrintManagementServiceStub(channel) +msg: BluePrintRemoveInput = BluePrintRemoveInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" return stub.removeBlueprint(msg) @@ -88,13 +88,13 @@ import zipfile from grpc import Channel, ChannelCredentials, insecure_channel, secure_channel, ssl_channel_credentials -from proto.BlueprintManagement_pb2 import ( - BlueprintDownloadInput, - BlueprintRemoveInput, - BlueprintUploadInput, - BlueprintManagementOutput, +from proto.BluePrintManagement_pb2 import ( + BluePrintDownloadInput, + BluePrintRemoveInput, + BluePrintUploadInput, + BluePrintManagementOutput, ) -from proto.BlueprintManagement_pb2_grpc import BlueprintManagementServiceStub +from proto.BluePrintManagement_pb2_grpc import BluePrintManagementServiceStub logging.basicConfig(level=logging.DEBUG) @@ -139,31 +139,31 @@ class Client: :param config: ConfigParser object with "client" section """ self.channel: Channel = channel - self.stub: BlueprintManagementServiceStub = BlueprintManagementServiceStub(self.channel) + self.stub: BluePrintManagementServiceStub = BluePrintManagementServiceStub(self.channel) self.config = config - def upload(self) -> BlueprintManagementOutput: + def upload(self) -> BluePrintManagementOutput: """Prepare upload message and send it to server.""" logging.info("Call upload client method") with open(self.config.get("client", "cba_file"), "rb") as cba_file: - msg: BlueprintUploadInput = BlueprintUploadInput() + msg: BluePrintUploadInput = BluePrintUploadInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" msg.fileChunk.chunk = cba_file.read() return self.stub.uploadBlueprint(msg) - def download(self) -> BlueprintManagementOutput: + def download(self) -> BluePrintManagementOutput: """Prepare download message and send it to server.""" logging.info("Call download client method") - msg: BlueprintDownloadInput = BlueprintDownloadInput() + msg: BluePrintDownloadInput = BluePrintDownloadInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" return self.stub.downloadBlueprint(msg) - def remove(self) -> BlueprintManagementOutput: + def remove(self) -> BluePrintManagementOutput: """Prepare remove message and send it to server.""" logging.info("Call remove client method") - msg: BlueprintRemoveInput = BlueprintRemoveInput() + msg: BluePrintRemoveInput = BluePrintRemoveInput() msg.actionIdentifiers.blueprintName = "Test" msg.actionIdentifiers.blueprintVersion = "0.0.1" return self.stub.removeBlueprint(msg) diff --git a/ms/artifact-manager/manager/servicer.py b/ms/artifact-manager/manager/servicer.py index fd05fe0cc..be740b0e3 100644 --- a/ms/artifact-manager/manager/servicer.py +++ b/ms/artifact-manager/manager/servicer.py @@ -23,13 +23,13 @@ from manager.configuration import get_logger from manager.errors import ArtifactManagerError, InvalidRequestError from manager.utils import Repository, RepositoryStrategy from onaplogging.mdcContext import MDC -from proto.BlueprintManagement_pb2 import ( - BlueprintDownloadInput, - BlueprintManagementOutput, - BlueprintRemoveInput, - BlueprintUploadInput, +from proto.BluePrintManagement_pb2 import ( + BluePrintDownloadInput, + BluePrintManagementOutput, + BluePrintRemoveInput, + BluePrintUploadInput, ) -from proto.BlueprintManagement_pb2_grpc import BlueprintManagementServiceServicer +from proto.BluePrintManagement_pb2_grpc import BluePrintManagementServiceServicer MDC_DATETIME_FORMAT = r"%Y-%m-%dT%H:%M:%S.%f%z" COMMON_HEADER_DATETIME_FORMAT = r"%Y-%m-%dT%H:%M:%S.%fZ" @@ -47,13 +47,13 @@ def fill_common_header(func): @wraps(func) def _decorator( servicer: "ArtifactManagerServicer", - request: Union[BlueprintDownloadInput, BlueprintRemoveInput, BlueprintUploadInput], + request: Union[BluePrintDownloadInput, BluePrintRemoveInput, BluePrintUploadInput], context: ServicerContext, - ) -> BlueprintManagementOutput: + ) -> BluePrintManagementOutput: if not all([request.actionIdentifiers.blueprintName, request.actionIdentifiers.blueprintVersion]): - raise InvalidRequestError("Request has to have set both Blueprint name and version") - output: BlueprintManagementOutput = func(servicer, request, context) + raise InvalidRequestError("Request has to have set both BluePrint name and version") + output: BluePrintManagementOutput = func(servicer, request, context) # Set same values for every handler output.commonHeader.CopyFrom(request.commonHeader) output.commonHeader.timestamp = datetime.utcnow().strftime(COMMON_HEADER_DATETIME_FORMAT) @@ -72,11 +72,11 @@ def translate_exception_to_response(func): @wraps(func) def _handler( servicer: "ArtifactManagerServicer", - request: Union[BlueprintDownloadInput, BlueprintRemoveInput, BlueprintUploadInput], + request: Union[BluePrintDownloadInput, BluePrintRemoveInput, BluePrintUploadInput], context: ServicerContext, - ) -> BlueprintManagementOutput: + ) -> BluePrintManagementOutput: try: - output: BlueprintManagementOutput = func(servicer, request, context) + output: BluePrintManagementOutput = func(servicer, request, context) output.status.code = 200 output.status.message = "success" except ArtifactManagerError as error: @@ -84,7 +84,7 @@ def translate_exception_to_response(func): # Every ArtifactManagerError based exception has status_code paramenter # which has to be set in output. Use also exception's message to # set errorMessage of the output. - output: BlueprintManagementOutput = BlueprintManagementOutput() + output: BluePrintManagementOutput = BluePrintManagementOutput() output.status.code = error.status_code output.status.message = "failure" output.status.errorMessage = str(error.message) @@ -112,9 +112,9 @@ def prepare_logging_context(func): @wraps(func) def _decorator( servicer: "ArtifactManagerServicer", - request: Union[BlueprintDownloadInput, BlueprintRemoveInput, BlueprintUploadInput], + request: Union[BluePrintDownloadInput, BluePrintRemoveInput, BluePrintUploadInput], context: ServicerContext, - ) -> BlueprintManagementOutput: + ) -> BluePrintManagementOutput: MDC.put("RequestID", request.commonHeader.requestId) MDC.put("InvocationID", request.commonHeader.subRequestId) MDC.put("ServiceName", servicer.__class__.__name__) @@ -129,14 +129,14 @@ def prepare_logging_context(func): MDC.put("TargetServiceName", func.__name__) MDC.put("Server", socket.getfqdn()) - output: BlueprintManagementOutput = func(servicer, request, context) + output: BluePrintManagementOutput = func(servicer, request, context) MDC.clear() return output return _decorator -class ArtifactManagerServicer(BlueprintManagementServiceServicer): +class ArtifactManagerServicer(BluePrintManagementServiceServicer): """ArtifactManagerServer class. Implements methods defined in proto files to manage artifacts repository. @@ -169,15 +169,15 @@ class ArtifactManagerServicer(BlueprintManagementServiceServicer): @prepare_logging_context @translate_exception_to_response @fill_common_header - def downloadBlueprint(self, request: BlueprintDownloadInput, context: ServicerContext) -> BlueprintManagementOutput: + def downloadBlueprint(self, request: BluePrintDownloadInput, context: ServicerContext) -> BluePrintManagementOutput: """Download blueprint file request method. Currently it only logs when is called and all base class method. - :param request: BlueprintDownloadInput + :param request: BluePrintDownloadInput :param context: ServicerContext - :return: BlueprintManagementOutput + :return: BluePrintManagementOutput """ - output: BlueprintManagementOutput = BlueprintManagementOutput() + output: BluePrintManagementOutput = BluePrintManagementOutput() output.fileChunk.chunk = self.repository.download_blueprint( request.actionIdentifiers.blueprintName, request.actionIdentifiers.blueprintVersion ) @@ -193,13 +193,13 @@ class ArtifactManagerServicer(BlueprintManagementServiceServicer): @prepare_logging_context @translate_exception_to_response @fill_common_header - def uploadBlueprint(self, request: BlueprintUploadInput, context: ServicerContext) -> BlueprintManagementOutput: + def uploadBlueprint(self, request: BluePrintUploadInput, context: ServicerContext) -> BluePrintManagementOutput: """Upload blueprint file request method. Currently it only logs when is called and all base class method. - :param request: BlueprintUploadInput + :param request: BluePrintUploadInput :param context: ServicerContext - :return: BlueprintManagementOutput + :return: BluePrintManagementOutput """ self.repository.upload_blueprint( request.fileChunk.chunk, request.actionIdentifiers.blueprintName, request.actionIdentifiers.blueprintVersion @@ -211,18 +211,18 @@ class ArtifactManagerServicer(BlueprintManagementServiceServicer): ), extra={"mdc": MDC.result()}, ) - return BlueprintManagementOutput() + return BluePrintManagementOutput() @prepare_logging_context @translate_exception_to_response @fill_common_header - def removeBlueprint(self, request: BlueprintRemoveInput, context: ServicerContext) -> BlueprintManagementOutput: + def removeBlueprint(self, request: BluePrintRemoveInput, context: ServicerContext) -> BluePrintManagementOutput: """Remove blueprint file request method. Currently it only logs when is called and all base class method. - :param request: BlueprintRemoveInput + :param request: BluePrintRemoveInput :param context: ServicerContext - :return: BlueprintManagementOutput + :return: BluePrintManagementOutput """ self.repository.remove_blueprint( request.actionIdentifiers.blueprintName, request.actionIdentifiers.blueprintVersion @@ -234,4 +234,4 @@ class ArtifactManagerServicer(BlueprintManagementServiceServicer): ), extra={"mdc": MDC.result()}, ) - return BlueprintManagementOutput() + return BluePrintManagementOutput() diff --git a/ms/artifact-manager/server.py b/ms/artifact-manager/server.py index 10034fe58..fe70c8855 100644 --- a/ms/artifact-manager/server.py +++ b/ms/artifact-manager/server.py @@ -19,7 +19,7 @@ import click from grpc import server as grpc_server from manager.configuration import config from manager.servicer import ArtifactManagerServicer -from proto.BlueprintManagement_pb2_grpc import add_BlueprintManagementServiceServicer_to_server +from proto.BluePrintManagement_pb2_grpc import add_BluePrintManagementServiceServicer_to_server @click.command() @@ -34,7 +34,7 @@ def run_server(): max_workers: int = int(config["artifactManagerServer"]["maxWorkers"]) server: grpc_server = grpc_server(ThreadPoolExecutor(max_workers=max_workers)) - add_BlueprintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) + add_BluePrintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) port_number: int = int(config["artifactManagerServer"]["port"]) server.add_insecure_port(f"[::]:{port_number}") diff --git a/ms/artifact-manager/tests/servicer_test.py b/ms/artifact-manager/tests/servicer_test.py index 702e1046a..131e6fb2c 100644 --- a/ms/artifact-manager/tests/servicer_test.py +++ b/ms/artifact-manager/tests/servicer_test.py @@ -19,17 +19,17 @@ from unittest.mock import patch import manager.utils from manager.servicer import ArtifactManagerServicer -from proto.BlueprintCommon_pb2 import ActionIdentifiers, CommonHeader -from proto.BlueprintManagement_pb2 import ( - BlueprintDownloadInput, - BlueprintManagementOutput, - BlueprintRemoveInput, - BlueprintUploadInput, +from proto.BluePrintCommon_pb2 import ActionIdentifiers, CommonHeader +from proto.BluePrintManagement_pb2 import ( + BluePrintDownloadInput, + BluePrintManagementOutput, + BluePrintRemoveInput, + BluePrintUploadInput, FileChunk, ) -from proto.BlueprintManagement_pb2_grpc import ( - BlueprintManagementServiceStub, - add_BlueprintManagementServiceServicer_to_server, +from proto.BluePrintManagement_pb2_grpc import ( + BluePrintManagementServiceStub, + add_BluePrintManagementServiceServicer_to_server, ) from pytest import fixture @@ -50,7 +50,7 @@ class MockZipFile(zipfile.ZipFile): @fixture(scope="module") def grpc_add_to_server(): """pytest-grpcio required function.""" - return add_BlueprintManagementServiceServicer_to_server + return add_BluePrintManagementServiceServicer_to_server @fixture(scope="module") @@ -62,34 +62,34 @@ def grpc_servicer(): @fixture(scope="module") # noqa def grpc_stub_cls(grpc_channel): """pytest-grpcio required function.""" - return BlueprintManagementServiceStub + return BluePrintManagementServiceStub def test_servicer_upload_handler_header_failure(grpc_stub): """Test servicer upload handler.""" - request: BlueprintUploadInput = BlueprintUploadInput() - output: BlueprintManagementOutput = grpc_stub.uploadBlueprint(request) + request: BluePrintUploadInput = BluePrintUploadInput() + output: BluePrintManagementOutput = grpc_stub.uploadBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" - assert output.status.errorMessage == "Request has to have set both Blueprint name and version" + assert output.status.errorMessage == "Request has to have set both BluePrint name and version" def test_servicer_download_handler_header_failure(grpc_stub): """Test servicer download handler.""" - request: BlueprintDownloadInput = BlueprintDownloadInput() - output: BlueprintManagementOutput = grpc_stub.downloadBlueprint(request) + request: BluePrintDownloadInput = BluePrintDownloadInput() + output: BluePrintManagementOutput = grpc_stub.downloadBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" - assert output.status.errorMessage == "Request has to have set both Blueprint name and version" + assert output.status.errorMessage == "Request has to have set both BluePrint name and version" def test_servicer_remove_handler_header_failure(grpc_stub): """Test servicer remove handler.""" - request: BlueprintRemoveInput = BlueprintRemoveInput() - output: BlueprintManagementOutput = grpc_stub.removeBlueprint(request) + request: BluePrintRemoveInput = BluePrintRemoveInput() + output: BluePrintManagementOutput = grpc_stub.removeBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" - assert output.status.errorMessage == "Request has to have set both Blueprint name and version" + assert output.status.errorMessage == "Request has to have set both BluePrint name and version" def test_servicer_upload_handler_failure(grpc_stub): @@ -97,8 +97,8 @@ def test_servicer_upload_handler_failure(grpc_stub): action_identifiers: ActionIdentifiers = ActionIdentifiers() action_identifiers.blueprintName = "sample-cba" action_identifiers.blueprintVersion = "1.0.0" - request: BlueprintUploadInput = BlueprintUploadInput(actionIdentifiers=action_identifiers) - output: BlueprintManagementOutput = grpc_stub.uploadBlueprint(request) + request: BluePrintUploadInput = BluePrintUploadInput(actionIdentifiers=action_identifiers) + output: BluePrintManagementOutput = grpc_stub.uploadBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" assert output.status.errorMessage == "Invalid request" @@ -109,8 +109,8 @@ def test_servicer_download_handler_failure(grpc_stub): action_identifiers: ActionIdentifiers = ActionIdentifiers() action_identifiers.blueprintName = "sample-cba" action_identifiers.blueprintVersion = "2.0.0" - request: BlueprintDownloadInput = BlueprintDownloadInput(actionIdentifiers=action_identifiers) - output: BlueprintManagementOutput = grpc_stub.downloadBlueprint(request) + request: BluePrintDownloadInput = BluePrintDownloadInput(actionIdentifiers=action_identifiers) + output: BluePrintManagementOutput = grpc_stub.downloadBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" assert output.status.errorMessage == "Artifact not found" @@ -121,8 +121,8 @@ def test_servicer_remove_handler_failure(grpc_stub): action_identifiers: ActionIdentifiers = ActionIdentifiers() action_identifiers.blueprintName = "sample-cba" action_identifiers.blueprintVersion = "1.0.0" - request: BlueprintRemoveInput = BlueprintRemoveInput(actionIdentifiers=action_identifiers) - output: BlueprintManagementOutput = grpc_stub.removeBlueprint(request) + request: BluePrintRemoveInput = BluePrintRemoveInput(actionIdentifiers=action_identifiers) + output: BluePrintManagementOutput = grpc_stub.removeBlueprint(request) assert output.status.code == 500 assert output.status.message == "failure" assert output.status.errorMessage == "Artifact not found" @@ -146,10 +146,10 @@ def test_servicer_upload_handler_success(grpc_stub): # fmt: off with patch.object(os, "makedirs", return_value=None), \ patch.object(manager.utils, 'ZipFile', return_value=MockZipFile()): - request: BlueprintUploadInput = BlueprintUploadInput( + request: BluePrintUploadInput = BluePrintUploadInput( commonHeader=header, fileChunk=file_chunk, actionIdentifiers=action_identifiers ) - output: BlueprintManagementOutput = grpc_stub.uploadBlueprint(request) + output: BluePrintManagementOutput = grpc_stub.uploadBlueprint(request) # fmt: on assert output.status.code == 200 assert output.status.message == "success" @@ -168,10 +168,10 @@ def test_servicer_download_handler_success(grpc_stub): action_identifiers.actionName = "SampleScript" with patch.object(os.path, "exists", return_value=True): - request: BlueprintDownloadInput = BlueprintDownloadInput( + request: BluePrintDownloadInput = BluePrintDownloadInput( commonHeader=header, actionIdentifiers=action_identifiers ) - output: BlueprintManagementOutput = grpc_stub.downloadBlueprint(request) + output: BluePrintManagementOutput = grpc_stub.downloadBlueprint(request) assert output.status.code == 200 assert output.status.message == "success" assert output.fileChunk.chunk == ZIP_FILE_BINARY @@ -190,7 +190,7 @@ def test_servicer_remove_handler_success(grpc_stub): action_identifiers.actionName = "SampleScript" with patch.object(shutil, "rmtree", return_value=None) as mock_rmtree: - request: BlueprintRemoveInput = BlueprintRemoveInput(commonHeader=header, actionIdentifiers=action_identifiers) - output: BlueprintManagementOutput = grpc_stub.removeBlueprint(request) + request: BluePrintRemoveInput = BluePrintRemoveInput(commonHeader=header, actionIdentifiers=action_identifiers) + output: BluePrintManagementOutput = grpc_stub.removeBlueprint(request) assert output.status.code == 200 assert output.status.message == "success" diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BluePrintProcessorCluster.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BluePrintProcessorCluster.kt new file mode 100644 index 000000000..513bd5135 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BluePrintProcessorCluster.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor + +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterInfo +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils +import org.springframework.boot.context.event.ApplicationReadyEvent +import org.springframework.context.event.EventListener +import org.springframework.stereotype.Component +import java.util.Properties + +/** + * To Start the cluster, minimum 2 Instances/ Replicas od CDS needed. + * All instance such as Blueprintprocessor, ResourceResolution, MessagePrioritization should be in + * same cluster and should have same cluster name. + * + * Data can be shared only between the clusters, outside the cluster data can't be shared. + * If cds-controller-x instance wants to share data with resource-resolution-x instance, then it should be in the + * same cluster.(cds-cluster) and same network (cds-network) + * + * Assumptions: + * 1. Container, Pod and Host names are same. + * 2. Container names should end with sequence number. + * Blueprintprocessor example be : cds-controller-1, cds-controller-2, cds-controller-3 + * ResourceResolution example be : resource-resolution-1, resource-resolution-2, resource-resolution-3 + * 3. Each contained, should have environment properties CLUSTER_ID, CLUSTER_NODE_ID, CLUSTER_JOIN_AS_CLIENT, + * CLUSTER_CONFIG_FILE + * Example values : + * CLUSTER_ID: cds-cluster + * CLUSTER_NODE_ID: cds-controller-2 + * CLUSTER_JOIN_AS_CLIENT: "true" or "false" + * CLUSTER_CONFIG_FILE: + * 4. Cluster will be enabled only all the above properties present in the environments. + * if CLUSTER_ENABLED is present, then it will try to create cluster. + */ +@Component +open class BluePrintProcessorCluster(private val bluePrintClusterService: BluePrintClusterService) { + + private val log = logger(BluePrintProcessorCluster::class) + + @EventListener(ApplicationReadyEvent::class) + fun startAndJoinCluster() = GlobalScope.launch { + + if (BluePrintConstants.CLUSTER_ENABLED) { + + val clusterId = ClusterUtils.clusterId() + val nodeId = ClusterUtils.clusterNodeId() + + val joinAsClient = + (System.getenv(BluePrintConstants.PROPERTY_CLUSTER_JOIN_AS_CLIENT) ?: "false").toBoolean() + + val clusterConfigFile = System.getenv(BluePrintConstants.PROPERTY_CLUSTER_CONFIG_FILE) + + val properties = Properties() + properties["hazelcast.logging.type"] = "slf4j" + + val clusterInfo = ClusterInfo( + id = clusterId, nodeId = nodeId, + joinAsClient = joinAsClient, + configFile = clusterConfigFile, + properties = properties + ) + bluePrintClusterService.startCluster(clusterInfo) + } else { + log.info("Cluster is disabled, to enable cluster set the environment CLUSTER_* properties.") + } + } +} diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintDatabaseConfiguration.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintDatabaseConfiguration.kt index ec84e2ac3..f5ccdee18 100644 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.controllerblueprints", "org.onap.ccsdk.cds.blueprintsprocessor", diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.kt index bba947647..bfde39aa0 100644 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.kt +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.kt @@ -17,10 +17,10 @@ package org.onap.ccsdk.cds.blueprintsprocessor import io.grpc.ServerBuilder -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BlueprintManagementGRPCHandler +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BluePrintManagementGRPCHandler import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcServerLoggingInterceptor import org.onap.ccsdk.cds.blueprintsprocessor.security.BasicAuthServerInterceptor -import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.BlueprintProcessingGRPCHandler +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.BluePrintProcessingGRPCHandler import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty @@ -31,8 +31,8 @@ import org.springframework.stereotype.Component @ConditionalOnProperty(name = ["blueprintsprocessor.grpcEnable"], havingValue = "true") @Component open class BlueprintGRPCServer( - private val bluePrintProcessingGRPCHandler: BlueprintProcessingGRPCHandler, - private val bluePrintManagementGRPCHandler: BlueprintManagementGRPCHandler, + private val bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler, + private val bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler, private val authInterceptor: BasicAuthServerInterceptor ) : ApplicationListener { diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorCluster.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorCluster.kt deleted file mode 100644 index b7903a2f7..000000000 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorCluster.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor - -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterInfo -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils -import org.springframework.boot.context.event.ApplicationReadyEvent -import org.springframework.context.event.EventListener -import org.springframework.stereotype.Component -import java.util.Properties - -/** - * To Start the cluster, minimum 2 Instances/ Replicas od CDS needed. - * All instance such as Blueprintprocessor, ResourceResolution, MessagePrioritization should be in - * same cluster and should have same cluster name. - * - * Data can be shared only between the clusters, outside the cluster data can't be shared. - * If cds-controller-x instance wants to share data with resource-resolution-x instance, then it should be in the - * same cluster.(cds-cluster) and same network (cds-network) - * - * Assumptions: - * 1. Container, Pod and Host names are same. - * 2. Container names should end with sequence number. - * Blueprintprocessor example be : cds-controller-1, cds-controller-2, cds-controller-3 - * ResourceResolution example be : resource-resolution-1, resource-resolution-2, resource-resolution-3 - * 3. Each contained, should have environment properties CLUSTER_ID, CLUSTER_NODE_ID, CLUSTER_JOIN_AS_CLIENT, - * CLUSTER_CONFIG_FILE - * Example values : - * CLUSTER_ID: cds-cluster - * CLUSTER_NODE_ID: cds-controller-2 - * CLUSTER_JOIN_AS_CLIENT: "true" or "false" - * CLUSTER_CONFIG_FILE: - * 4. Cluster will be enabled only all the above properties present in the environments. - * if CLUSTER_ENABLED is present, then it will try to create cluster. - */ -@Component -open class BlueprintProcessorCluster(private val bluePrintClusterService: BlueprintClusterService) { - - private val log = logger(BlueprintProcessorCluster::class) - - @EventListener(ApplicationReadyEvent::class) - fun startAndJoinCluster() = GlobalScope.launch { - - if (BlueprintConstants.CLUSTER_ENABLED) { - - val clusterId = ClusterUtils.clusterId() - val nodeId = ClusterUtils.clusterNodeId() - - val joinAsClient = - (System.getenv(BlueprintConstants.PROPERTY_CLUSTER_JOIN_AS_CLIENT) ?: "false").toBoolean() - - val clusterConfigFile = System.getenv(BlueprintConstants.PROPERTY_CLUSTER_CONFIG_FILE) - - val properties = Properties() - properties["hazelcast.logging.type"] = "slf4j" - - val clusterInfo = ClusterInfo( - id = clusterId, nodeId = nodeId, - joinAsClient = joinAsClient, - configFile = clusterConfigFile, - properties = properties - ) - bluePrintClusterService.startCluster(clusterInfo) - } else { - log.info("Cluster is disabled, to enable cluster set the environment CLUSTER_* properties.") - } - } -} diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BluePrintCustomIndicator.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BluePrintCustomIndicator.kt new file mode 100644 index 000000000..c795ee5fb --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BluePrintCustomIndicator.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2019-2020 Orange. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.actuator.indicator + +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.BluePrintProcessorHealthCheck +import org.slf4j.LoggerFactory +import org.springframework.boot.actuate.health.AbstractHealthIndicator +import org.springframework.boot.actuate.health.Health +import org.springframework.stereotype.Component + +/** + * Health Indicator for BluePrintProcessor. + * @author Shaaban Ebrahim + * @version 1.0 + */ +@Component +open class BluePrintCustomIndicator(private val bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck) : + AbstractHealthIndicator() { + + private var logger = LoggerFactory.getLogger(BluePrintCustomIndicator::class.java) + + @Throws(Exception::class) + override fun doHealthCheck(builder: Health.Builder) { + runBlocking { + var result: HealthApiResponse? = null + try { + result = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus() + if (result?.status == HealthCheckStatus.UP) { + builder.up() + } else { + builder.down() + } + builder.withDetail("Services", result?.checks) + } catch (exception: IllegalArgumentException) { + logger.error(exception.message) + } + } + } +} diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BlueprintCustomIndicator.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BlueprintCustomIndicator.kt deleted file mode 100644 index 50935196e..000000000 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/actuator/indicator/BlueprintCustomIndicator.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright © 2019-2020 Orange. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.actuator.indicator - -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.BlueprintProcessorHealthCheck -import org.slf4j.LoggerFactory -import org.springframework.boot.actuate.health.AbstractHealthIndicator -import org.springframework.boot.actuate.health.Health -import org.springframework.stereotype.Component - -/** - * Health Indicator for BlueprintProcessor. - * @author Shaaban Ebrahim - * @version 1.0 - */ -@Component -open class BlueprintCustomIndicator(private val bluePrintProcessorHealthCheck: BlueprintProcessorHealthCheck) : - AbstractHealthIndicator() { - - private var logger = LoggerFactory.getLogger(BlueprintCustomIndicator::class.java) - - @Throws(Exception::class) - override fun doHealthCheck(builder: Health.Builder) { - runBlocking { - var result: HealthApiResponse? = null - try { - result = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus() - if (result?.status == HealthCheckStatus.UP) { - builder.up() - } else { - builder.down() - } - builder.withDetail("Services", result?.checks) - } catch (exception: IllegalArgumentException) { - logger.error(exception.message) - } - } - } -} diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatExecutor.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatExecutor.kt index 44f2e7d0d..1e1d3ac2a 100644 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatExecutor.kt +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatExecutor.kt @@ -46,7 +46,7 @@ import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.MatcherAssert.assertThat import org.mockito.Answers import org.mockito.verification.VerificationMode -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService.WebClientResponse import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.COLOR_MOCKITO @@ -73,7 +73,7 @@ import java.util.concurrent.ConcurrentHashMap @Component class UatExecutor( private val environment: ConfigurableEnvironment, - private val restClientFactory: BlueprintRestLibPropertyService, + private val restClientFactory: BluePrintRestLibPropertyService, private val mapper: ObjectMapper ) { @@ -297,7 +297,7 @@ class UatExecutor( return "Basic " + Base64Utils.encodeToString("$username:$plainPassword".toByteArray()) } - private class MockPreInterceptor : BlueprintRestLibPropertyService.PreInterceptor { + private class MockPreInterceptor : BluePrintRestLibPropertyService.PreInterceptor { private val mocks = ConcurrentHashMap() @@ -313,7 +313,7 @@ class UatExecutor( } } - private class SpyPostInterceptor(private val mapper: ObjectMapper) : BlueprintRestLibPropertyService.PostInterceptor { + private class SpyPostInterceptor(private val mapper: ObjectMapper) : BluePrintRestLibPropertyService.PostInterceptor { private val spies = ConcurrentHashMap() diff --git a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatServices.kt b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatServices.kt index 31c7ad4b1..f6dd88dd5 100644 --- a/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatServices.kt +++ b/ms/blueprintsprocessor/application/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/utils/UatServices.kt @@ -24,7 +24,7 @@ import kotlinx.coroutines.runBlocking import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.COLOR_SERVICES import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.resetContextColor import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.setContextColor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.UAT_SPECIFICATION_FILE +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.UAT_SPECIFICATION_FILE import org.springframework.context.annotation.Profile import org.springframework.http.HttpStatus import org.springframework.http.MediaType diff --git a/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties b/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties index f5d1a065c..e7443434a 100755 --- a/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties +++ b/ms/blueprintsprocessor/application/src/main/resources/application-dev.properties @@ -41,7 +41,7 @@ blueprintsprocessor.blueprintArchivePath=blueprints/archive blueprintsprocessor.blueprintWorkingPath=blueprints/work # Controller Blueprint Load Configurations -blueprintsprocessor.loadBlueprintPaths=./../../../components/model-catalog/blueprint-model/service-blueprint +blueprintsprocessor.loadBluePrintPaths=./../../../components/model-catalog/blueprint-model/service-blueprint blueprintsprocessor.loadModeTypePaths=./../../../components/model-catalog/definition-type/starter-type blueprintsprocessor.loadResourceDictionaryPaths=./../../../components/model-catalog/resource-dictionary/starter-dictionary diff --git a/ms/blueprintsprocessor/application/src/main/resources/application-local.yml b/ms/blueprintsprocessor/application/src/main/resources/application-local.yml index 7dac8f8cb..f2843322c 100644 --- a/ms/blueprintsprocessor/application/src/main/resources/application-local.yml +++ b/ms/blueprintsprocessor/application/src/main/resources/application-local.yml @@ -1,4 +1,4 @@ -appName: ControllerBlueprints +appName: ControllerBluePrints appVersion: 1.0.0 blueprints: processor: diff --git a/ms/blueprintsprocessor/application/src/main/resources/application.properties b/ms/blueprintsprocessor/application/src/main/resources/application.properties index 3fdb8d86a..9b48359a1 100755 --- a/ms/blueprintsprocessor/application/src/main/resources/application.properties +++ b/ms/blueprintsprocessor/application/src/main/resources/application.properties @@ -24,7 +24,7 @@ blueprintsprocessor.blueprintArchivePath=/opt/app/onap/blueprints/archive blueprintsprocessor.blueprintWorkingPath=/opt/app/onap/blueprints/working # Controller Blueprint Load Configurations -blueprintsprocessor.loadBlueprintPaths=/opt/app/onap/model-catalog/blueprint-model +blueprintsprocessor.loadBluePrintPaths=/opt/app/onap/model-catalog/blueprint-model blueprintsprocessor.loadModeTypePaths=/opt/app/onap/model-catalog/definition-type blueprintsprocessor.loadResourceDictionaryPaths=/opt/app/onap/model-catalog/resource-dictionary diff --git a/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/BlueprintsAcceptanceTest.kt b/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/BlueprintsAcceptanceTest.kt index 0d9f3dac9..4a8da536f 100644 --- a/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/BlueprintsAcceptanceTest.kt +++ b/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/BlueprintsAcceptanceTest.kt @@ -26,8 +26,8 @@ import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.ExtendedTemporaryFolder import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.UatExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.UAT_SPECIFICATION_FILE -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils.Companion.compressToBytes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.UAT_SPECIFICATION_FILE +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils.Companion.compressToBytes import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.junit4.rules.SpringClassRule import org.springframework.test.context.junit4.rules.SpringMethodRule diff --git a/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/UatServicesTest.kt b/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/UatServicesTest.kt index ecdc564c1..fe2d539e3 100644 --- a/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/UatServicesTest.kt +++ b/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/UatServicesTest.kt @@ -49,8 +49,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.MarkedSlf4jNotifier import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.ServiceDefinition import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.TestSecuritySettings import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.UatDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.UAT_SPECIFICATION_FILE -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils.Companion.compressToBytes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.UAT_SPECIFICATION_FILE +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils.Companion.compressToBytes import org.skyscreamer.jsonassert.JSONAssert import org.skyscreamer.jsonassert.JSONCompareMode import org.springframework.beans.factory.annotation.Autowired diff --git a/ms/blueprintsprocessor/application/src/test/resources/application.properties b/ms/blueprintsprocessor/application/src/test/resources/application.properties index 6db8a5f4e..c6e957b32 100644 --- a/ms/blueprintsprocessor/application/src/test/resources/application.properties +++ b/ms/blueprintsprocessor/application/src/test/resources/application.properties @@ -29,8 +29,8 @@ blueprintsprocessor.blueprintWorkingPath=/opt/app/onap/blueprints/working # Controller Blueprint Load Configurations # blueprints.load.initial-data may be overridden by ENV variables blueprintsprocessor.loadInitialData=false -blueprintsprocessor.loadBlueprint=false -blueprintsprocessor.loadBlueprintPaths=/opt/app/onap/model-catalog/blueprint-model/service-blueprint +blueprintsprocessor.loadBluePrint=false +blueprintsprocessor.loadBluePrintPaths=/opt/app/onap/model-catalog/blueprint-model/service-blueprint blueprintsprocessor.loadModelType=false blueprintsprocessor.loadModeTypePaths=/opt/app/onap/model-catalog/definition-type/starter-type blueprintsprocessor.loadResourceDictionary=false diff --git a/ms/blueprintsprocessor/functions/ansible-awx-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutor.kt b/ms/blueprintsprocessor/functions/ansible-awx-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutor.kt index 2eafcd458..133e4a52b 100644 --- a/ms/blueprintsprocessor/functions/ansible-awx-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutor.kt +++ b/ms/blueprintsprocessor/functions/ansible-awx-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutor.kt @@ -22,7 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.TextNode import kotlinx.coroutines.delay import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode @@ -55,7 +55,7 @@ import java.util.NoSuchElementException @Component("component-remote-ansible-executor") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class ComponentRemoteAnsibleExecutor( - private val blueprintRestLibPropertyService: BlueprintRestLibPropertyService, + private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService, private val mapper: ObjectMapper ) : AbstractComponentFunction() { diff --git a/ms/blueprintsprocessor/functions/ansible-awx-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutorTest.kt b/ms/blueprintsprocessor/functions/ansible-awx-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutorTest.kt index 88cf0992f..7be03333f 100644 --- a/ms/blueprintsprocessor/functions/ansible-awx-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/ansible-awx-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/ansible/executor/ComponentRemoteAnsibleExecutorTest.kt @@ -27,13 +27,13 @@ import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService.WebClientResponse -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.test.context.TestPropertySource import org.springframework.test.context.junit4.SpringRunner @@ -94,7 +94,7 @@ class ComponentRemoteAnsibleExecutorTest { ) } returns WebClientResponse(200, getReport()) val selector = mapper.readTree(endpointSelector) - val bluePrintRestLibPropertyService = mockk() + val bluePrintRestLibPropertyService = mockk() every { bluePrintRestLibPropertyService.blueprintWebClientService(selector) } returns webClientService val awxRemoteExecutor = ComponentRemoteAnsibleExecutor(bluePrintRestLibPropertyService, mapper) awxRemoteExecutor.checkDelay = 1 @@ -112,7 +112,7 @@ class ComponentRemoteAnsibleExecutorTest { } // then - assertTrue(bluePrintRuntimeService.getBlueprintError().allErrors().isEmpty()) + assertTrue(bluePrintRuntimeService.getBluePrintError().allErrors().isEmpty()) } @Test @@ -128,7 +128,7 @@ class ComponentRemoteAnsibleExecutorTest { webClientService.exchangeResource("GET", "/api/v2/inventories/?name=Demo+Inventory", "") } returns WebClientResponse(404, "") val selector = mapper.readTree(endpointSelector) - val bluePrintRestLibPropertyService = mockk() + val bluePrintRestLibPropertyService = mockk() every { bluePrintRestLibPropertyService.blueprintWebClientService(selector) } returns webClientService val awxRemoteExecutor = ComponentRemoteAnsibleExecutor(bluePrintRestLibPropertyService, mapper) awxRemoteExecutor.checkDelay = 1 @@ -146,7 +146,7 @@ class ComponentRemoteAnsibleExecutorTest { } // then - val errors = bluePrintRuntimeService.getBlueprintError().allErrors() + val errors = bluePrintRuntimeService.getBluePrintError().allErrors() assertEquals(1, errors.size) } @@ -169,7 +169,7 @@ class ComponentRemoteAnsibleExecutorTest { ) } returns WebClientResponse(500, "") val selector = mapper.readTree(endpointSelector) - val bluePrintRestLibPropertyService = mockk() + val bluePrintRestLibPropertyService = mockk() every { bluePrintRestLibPropertyService.blueprintWebClientService(selector) } returns webClientService val awxRemoteExecutor = ComponentRemoteAnsibleExecutor(bluePrintRestLibPropertyService, mapper) awxRemoteExecutor.checkDelay = 1 @@ -187,15 +187,15 @@ class ComponentRemoteAnsibleExecutorTest { } // then - val errors = bluePrintRuntimeService.getBlueprintError().allErrors() + val errors = bluePrintRuntimeService.getBluePrintError().allErrors() assertEquals(1, errors.size) } private fun createBlueprintRuntimeService( awxRemoteExecutor: ComponentRemoteAnsibleExecutor, executionServiceInput: ExecutionServiceInput - ): BlueprintRuntimeService> { - val bluePrintRuntimeService = BlueprintMetadataUtils.bluePrintRuntime( + ): BluePrintRuntimeService> { + val bluePrintRuntimeService = BluePrintMetadataUtils.bluePrintRuntime( "123456-1000", "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_ansible" ) @@ -208,9 +208,9 @@ class ComponentRemoteAnsibleExecutorTest { bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-ansible") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemoteAnsibleExecutor") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-ansible") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemoteAnsibleExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") val stepInputData = StepData().apply { name = "execute-remote-ansible" diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorExtensions.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorExtensions.kt index 341455309..b6f2dcb94 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorExtensions.kt +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorExtensions.kt @@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.BlueprintSshClientService import org.onap.ccsdk.cds.blueprintsprocessor.ssh.sshClientService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService /** * Register the CLI module exposed dependency @@ -31,5 +31,5 @@ fun AbstractComponentFunction.cliDeviceInfo(requirementName: String): JsonNode { } fun AbstractComponentFunction.getSshClientService(cliDeviceInfo: JsonNode): BlueprintSshClientService { - return BlueprintDependencyService.sshClientService(cliDeviceInfo) + return BluePrintDependencyService.sshClientService(cliDeviceInfo) } diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/ComponentCliExecutorTest.kt b/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/ComponentCliExecutorTest.kt index c9109a3f1..3cefa3274 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/ComponentCliExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/ComponentCliExecutorTest.kt @@ -23,22 +23,22 @@ import io.mockk.mockk import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BlueprintSshLibConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BluePrintSshLibConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintScriptsServiceImpl -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.annotation.DirtiesContext @@ -52,8 +52,8 @@ import kotlin.test.assertNotNull classes = [ CliExecutorConfiguration::class, ExecutionServiceConfiguration::class, - BlueprintSshLibConfiguration::class, BlueprintScriptsServiceImpl::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class, BlueprintDependencyService::class + BluePrintSshLibConfiguration::class, BluePrintScriptsServiceImpl::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDependencyService::class ] ) @DirtiesContext @@ -76,15 +76,15 @@ class ComponentCliExecutorTest { } payload = JacksonUtils.jsonNode("{}") as ObjectNode } - val bluePrintRuntime = mockk("1234") + val bluePrintRuntime = mockk("1234") componentScriptExecutor.bluePrintRuntimeService = bluePrintRuntime componentScriptExecutor.stepName = "sample-step" val operationInputs = hashMapOf() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-cli".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() - operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_TYPE] = BlueprintConstants.SCRIPT_INTERNAL.asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-cli".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() + operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_TYPE] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive() operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE] = "internal.scripts.TestCliScriptFunction".asJsonPrimitive() @@ -94,7 +94,7 @@ class ComponentCliExecutorTest { } executionServiceInput.stepData = stepInputData - val blueprintContext = mockk() + val blueprintContext = mockk() every { blueprintContext.nodeTemplateOperationImplementation( any(), any(), any() diff --git a/ms/blueprintsprocessor/functions/config-snapshots/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/db/ResourceConfigSnapshotService.kt b/ms/blueprintsprocessor/functions/config-snapshots/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/db/ResourceConfigSnapshotService.kt index 382a1312f..06146c200 100644 --- a/ms/blueprintsprocessor/functions/config-snapshots/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/db/ResourceConfigSnapshotService.kt +++ b/ms/blueprintsprocessor/functions/config-snapshots/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/db/ResourceConfigSnapshotService.kt @@ -19,7 +19,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.apache.logging.log4j.util.Strings import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshot.Status.RUNNING -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.slf4j.LoggerFactory import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service @@ -111,7 +111,7 @@ open class ResourceConfigSnapshotService(private val resourceConfigSnapshotRepos "dated=(${storedSnapshot.createdDate})" ) } catch (ex: DataIntegrityViolationException) { - throw BlueprintException("Failed to store configuration snapshot entry.", ex) + throw BluePrintException("Failed to store configuration snapshot entry.", ex) } storedSnapshot } diff --git a/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/ComponentConfigSnapshotsExecutorTest.kt b/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/ComponentConfigSnapshotsExecutorTest.kt index 99de66489..3a3dd102a 100644 --- a/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/ComponentConfigSnapshotsExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/ComponentConfigSnapshotsExecutorTest.kt @@ -31,9 +31,9 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.Compone import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.ComponentConfigSnapshotsExecutor.Companion.OPERATION_STORE import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshot import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshotService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.ComponentScan @@ -55,7 +55,7 @@ class ComponentConfigSnapshotsExecutorTest { @Autowired lateinit var cfgSnapshotService: ResourceConfigSnapshotService lateinit var cfgSnapshotComponent: ComponentConfigSnapshotsExecutor - private var bluePrintRuntimeService = BlueprintMetadataUtils.bluePrintRuntime( + private var bluePrintRuntimeService = BluePrintMetadataUtils.bluePrintRuntime( "123456-1000", "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" ) @@ -99,7 +99,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_FETCH, resId, resType, ResourceConfigSnapshot.Status.RUNNING.name) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -138,7 +138,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_FETCH, resId, resType, ResourceConfigSnapshot.Status.CANDIDATE.name) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -176,7 +176,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_STORE, resId, resType, snapshotConfig) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -211,7 +211,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_FETCH, "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -238,7 +238,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties("update", "asdasd", "PNF", ResourceConfigSnapshot.Status.RUNNING.name) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -247,7 +247,7 @@ class ComponentConfigSnapshotsExecutorTest { } // then; we should get error in our output properties - assertTrue(bluePrintRuntimeService.getBlueprintError().allErrors().size == 1) + assertTrue(bluePrintRuntimeService.getBluePrintError().allErrors().size == 1) assertEquals( ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_ERROR.asJsonPrimitive(), bluePrintRuntimeService.getNodeTemplateAttributeValue( @@ -278,7 +278,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_DIFF, resId, resType, "YANG") cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot lookup: provide resource-id and resource-type.", e.message @@ -319,7 +319,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_DIFF, resId, resType, DIFF_JSON) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.", e.message @@ -328,7 +328,7 @@ class ComponentConfigSnapshotsExecutorTest { } // then; we should get success - assertTrue(bluePrintRuntimeService.getBlueprintError().allErrors().size == 0) + assertTrue(bluePrintRuntimeService.getBluePrintError().allErrors().size == 0) assertEquals( ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(), bluePrintRuntimeService.getNodeTemplateAttributeValue( @@ -368,7 +368,7 @@ class ComponentConfigSnapshotsExecutorTest { prepareRequestProperties(OPERATION_DIFF, resId, resType, DIFF_XML) cfgSnapshotComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { kotlin.test.assertEquals( "Can't proceed with the cfg snapshot diff: provide resource-id and resource-type.", e.message @@ -377,7 +377,7 @@ class ComponentConfigSnapshotsExecutorTest { } // then; we should get success - assertTrue(bluePrintRuntimeService.getBlueprintError().allErrors().size == 0) + assertTrue(bluePrintRuntimeService.getBluePrintError().allErrors().size == 0) assertEquals( ComponentConfigSnapshotsExecutor.OUTPUT_STATUS_SUCCESS.asJsonPrimitive(), bluePrintRuntimeService.getNodeTemplateAttributeValue( diff --git a/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/TestDatabaseConfiguration.kt index b65191347..96045ee07 100644 --- a/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/functions/config-snapshots/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/config/snapshots/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots"], entityManagerFactoryRef = "primaryEntityManager", diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sConnectionPluginConfiguration.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sConnectionPluginConfiguration.kt index 2419e5a13..cc423a09a 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sConnectionPluginConfiguration.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/K8sConnectionPluginConfiguration.kt @@ -17,9 +17,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @@ -27,12 +27,12 @@ import org.springframework.context.annotation.Import @Configuration @Import( - BlueprintPropertyConfiguration::class, - BlueprintPropertiesService::class, - BlueprintCoreConfiguration::class + BluePrintPropertyConfiguration::class, + BluePrintPropertiesService::class, + BluePrintCoreConfiguration::class ) @EnableConfigurationProperties -open class K8sConnectionPluginConfiguration(private var bluePrintPropertiesService: BlueprintPropertiesService) { +open class K8sConnectionPluginConfiguration(private var bluePrintPropertiesService: BluePrintPropertiesService) { @Bean("k8s-plugin-properties") open fun getProperties(): K8sConnectionPluginProperties { diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sPluginDefinitionApi.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sPluginDefinitionApi.kt index ae2d1f634..73c0e8029 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sPluginDefinitionApi.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/K8sPluginDefinitionApi.kt @@ -25,7 +25,7 @@ import com.fasterxml.jackson.module.kotlin.readValue import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.template.K8sTemplate import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.slf4j.LoggerFactory import org.springframework.http.HttpMethod.DELETE import org.springframework.http.HttpMethod.GET @@ -54,7 +54,7 @@ class K8sPluginDefinitionApi( return result.status in 200..299 } catch (e: Exception) { log.error("Caught exception trying to get k8s rb definition") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -74,7 +74,7 @@ class K8sPluginDefinitionApi( return result.status in 200..299 } catch (e: Exception) { log.error("Caught exception trying to get k8s rb profile") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -96,7 +96,7 @@ class K8sPluginDefinitionApi( } } catch (e: Exception) { log.error("Caught exception trying to create k8s rb profile ${profile.profileName}") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -118,7 +118,7 @@ class K8sPluginDefinitionApi( log.debug("Profile uploaded properly") } catch (e: Exception) { log.error("Caught exception trying to upload k8s rb profile ${profile.profileName}") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -137,7 +137,7 @@ class K8sPluginDefinitionApi( } } catch (e: Exception) { log.error("Caught exception during create template") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -154,7 +154,7 @@ class K8sPluginDefinitionApi( } } catch (e: Exception) { log.error("Caught exception trying to upload k8s rb template ${template.templateName}") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -172,7 +172,7 @@ class K8sPluginDefinitionApi( } } catch (e: Exception) { log.error("Caught exception during get template") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -184,7 +184,7 @@ class K8sPluginDefinitionApi( return objectMapper.readValue(result.body) } catch (e: Exception) { log.error("Caught exception during get template") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -196,7 +196,7 @@ class K8sPluginDefinitionApi( return result.status in 200..299 } catch (e: Exception) { log.error("Caught exception during get template") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt index 80531b13d..067c75b3e 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/profile/K8sProfileUploadComponent.kt @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.commons.io.FileUtils -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi @@ -31,14 +31,14 @@ import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.config.ConfigurableBeanFactory @@ -53,7 +53,7 @@ import java.nio.file.Paths @Component("component-k8s-profile-upload") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class K8sProfileUploadComponent( - private var bluePrintPropertiesService: BlueprintPropertiesService, + private var bluePrintPropertiesService: BluePrintPropertiesService, private val resourceResolutionService: ResourceResolutionService ) : @@ -132,7 +132,7 @@ open class K8sProfileUploadComponent( if ((profileName == null) || (definitionName == null) || (definitionVersion == null)) { log.warn("Prefix $prefix does not have required data for us to continue.") } else if (!api.hasDefinition(definitionName, definitionVersion)) { - throw BlueprintProcessorException("K8s RB Definition ($definitionName/$definitionVersion) not found ") + throw BluePrintProcessorException("K8s RB Definition ($definitionName/$definitionVersion) not found ") } else if (profileName == "") { log.warn("K8s rb profile name is empty! Either define profile name to use or choose default") } else if (api.hasProfile(definitionName, definitionVersion, profileName)) { @@ -144,15 +144,15 @@ open class K8sProfileUploadComponent( val profileK8sVersion: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_K8S_VERSION]?.returnNullIfMissing()?.asText() var profileSource: String? = prefixInputParamsMap[INPUT_K8S_PROFILE_SOURCE]?.returnNullIfMissing()?.asText() if (profileNamespace == null) - throw BlueprintProcessorException("Profile $profileName namespace is missing") + throw BluePrintProcessorException("Profile $profileName namespace is missing") if (profileSource == null) { profileSource = profileName log.info("Profile name used instead of profile source") } val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, profileSource) - if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE) - throw BlueprintProcessorException( + if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE) + throw BluePrintProcessorException( "Unexpected profile artifact type for profile source " + "$profileSource. Expecting: $artifact.type" ) @@ -239,19 +239,19 @@ open class K8sProfileUploadComponent( tempProfilePath, manifestFiles ) } else - throw BlueprintProcessorException("Manifest file is missing") + throw BluePrintProcessorException("Manifest file is missing") // Preparation of the final profile content val finalProfileFilePath = Paths.get( tempMainPath.toString().plus(File.separator).plus( "$k8sRbProfileName.tar.gz" ) ) - if (!BlueprintArchiveUtils.compress( + if (!BluePrintArchiveUtils.compress( tempProfilePath, finalProfileFilePath.toFile(), ArchiveType.TarGz ) ) { - throw BlueprintProcessorException("Profile compression has failed") + throw BluePrintProcessorException("Profile compression has failed") } FileUtils.deleteDirectory(tempProfilePath) @@ -261,7 +261,7 @@ open class K8sProfileUploadComponent( throw t } } else - throw BlueprintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder") + throw BluePrintProcessorException("Profile source $ks8ProfileLocation is missing in CBA folder") } private fun readManifestFiles(profileSource: File, destinationFolder: File): ArrayList? { @@ -353,7 +353,7 @@ open class K8sProfileUploadComponent( if (!isFileInTheManifestFiles(finalFile, manifestFiles)) return val fileContent = templatedFile.bufferedReader().readText() - val finalFileContent = BlueprintVelocityTemplateService.generateContent( + val finalFileContent = BluePrintVelocityTemplateService.generateContent( fileContent, params.toString(), true ) diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigTemplateComponent.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigTemplateComponent.kt index ceb4e80e7..969277751 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigTemplateComponent.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigTemplateComponent.kt @@ -23,21 +23,21 @@ import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import org.apache.commons.io.FileUtils -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.definition.K8sPluginDefinitionApi import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.ArchiveType -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -52,7 +52,7 @@ import java.nio.file.Paths @Component("component-k8s-config-template") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class K8sConfigTemplateComponent( - private var bluePrintPropertiesService: BlueprintPropertiesService, + private var bluePrintPropertiesService: BluePrintPropertiesService, private val resourceResolutionService: ResourceResolutionService ) : @@ -141,8 +141,8 @@ open class K8sConfigTemplateComponent( } val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, templateSource) - if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) - throw BlueprintProcessorException( + if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) + throw BluePrintProcessorException( "Unexpected template artifact type for template source $templateSource. Expecting: $artifact.type" ) val template = K8sTemplate() @@ -222,8 +222,8 @@ open class K8sConfigTemplateComponent( "$k8sRbTemplateName.tar.gz" ) ) - if (!BlueprintArchiveUtils.compress(tempPath, finalTemplateFilePath.toFile(), ArchiveType.TarGz)) { - throw BlueprintProcessorException("Config template compression has failed") + if (!BluePrintArchiveUtils.compress(tempPath, finalTemplateFilePath.toFile(), ArchiveType.TarGz)) { + throw BluePrintProcessorException("Config template compression has failed") } FileUtils.deleteDirectory(tempPath) @@ -233,7 +233,7 @@ open class K8sConfigTemplateComponent( throw t } } else - throw BlueprintProcessorException("Config source $k8sConfigLocation is missing in CBA folder") + throw BluePrintProcessorException("Config source $k8sConfigLocation is missing in CBA folder") } private fun templateLocation(location: File, params: JsonNode, destinationFolder: File) { @@ -256,7 +256,7 @@ open class K8sConfigTemplateComponent( private fun templateFile(templateFile: File, params: JsonNode, destinationFolder: File) { val finalFile = File(destinationFolder.path.plus(File.separator).plus(templateFile.nameWithoutExtension)) val fileContent = templateFile.bufferedReader().readText() - val finalFileContent = BlueprintVelocityTemplateService.generateContent( + val finalFileContent = BluePrintVelocityTemplateService.generateContent( fileContent, params.toString(), true ) diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigValueComponent.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigValueComponent.kt index 7a487f205..f1affacf4 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigValueComponent.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/definition/template/K8sConfigValueComponent.kt @@ -6,7 +6,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.kotlin.convertValue -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.K8sConnectionPluginConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sConfigValueRequest @@ -14,12 +14,12 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.K8sPluginIn import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -33,7 +33,7 @@ import java.nio.file.Paths @Component("component-k8s-config-value") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class K8sConfigValueComponent( - private var bluePrintPropertiesService: BlueprintPropertiesService, + private var bluePrintPropertiesService: BluePrintPropertiesService, private val resourceResolutionService: ResourceResolutionService ) : AbstractComponentFunction() { @@ -105,7 +105,7 @@ open class K8sConfigValueComponent( else if (operationType == OperationType.DELETE.toString()) deleteOperation(instanceId, configName) else - throw BlueprintProcessorException("Unknown operation type: $operationType") + throw BluePrintProcessorException("Unknown operation type: $operationType") } } @@ -124,8 +124,8 @@ open class K8sConfigValueComponent( outputPrefixStatuses[prefix] = OUTPUT_ERROR val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, valueSource) - if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) - throw BlueprintProcessorException( + if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) + throw BluePrintProcessorException( "Unexpected config artifact type for config value source $valueSource. Expecting: $artifact.type" ) val configValueRequest = K8sConfigValueRequest() @@ -153,8 +153,8 @@ open class K8sConfigValueComponent( outputPrefixStatuses[prefix] = OUTPUT_ERROR val bluePrintContext = bluePrintRuntimeService.bluePrintContext() val artifact: ArtifactDefinition = bluePrintContext.nodeTemplateArtifact(nodeTemplateName, valueSource) - if (artifact.type != BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) - throw BlueprintProcessorException( + if (artifact.type != BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG) + throw BluePrintProcessorException( "Unexpected config artifact type for config value source $valueSource. Expecting: $artifact.type" ) if (api.hasConfigurationValues(instanceId, configName)) { @@ -165,7 +165,7 @@ open class K8sConfigValueComponent( configValueRequest.values = parseResult(valueSource, artifact.file) api.editConfigurationValues(configValueRequest, instanceId, configName) } else { - throw BlueprintProcessorException("Error while getting configuration value") + throw BluePrintProcessorException("Error while getting configuration value") } } } @@ -189,7 +189,7 @@ open class K8sConfigValueComponent( ) if (!configeValueSourceFilePath.toFile().exists() || configeValueSourceFilePath.toFile().isDirectory) - throw BlueprintProcessorException("Specified config value source $k8sConfigLocation is not a file") + throw BluePrintProcessorException("Specified config value source $k8sConfigLocation is not a file") var obj: Any? = null val yamlReader = ObjectMapper(YAMLFactory()) @@ -225,7 +225,7 @@ open class K8sConfigValueComponent( private fun templateValues(templateFile: File, params: JsonNode): String { val fileContent = templateFile.bufferedReader().readText() - return BlueprintVelocityTemplateService.generateContent( + return BluePrintVelocityTemplateService.generateContent( fileContent, params.toString(), true ) @@ -238,7 +238,7 @@ open class K8sConfigValueComponent( if (profileSourceFileFolderPath.toFile().exists() && !profileSourceFileFolderPath.toFile().isDirectory) return profileSourceFileFolderPath.toFile() else - throw BlueprintProcessorException("Template value $profileSourceFileFolderPath is missing in CBA folder") + throw BluePrintProcessorException("Template value $profileSourceFileFolderPath is missing in CBA folder") } private fun getTemplatePrefixList(node: JsonNode?): ArrayList { diff --git a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt index 3305481e1..dbcc13395 100644 --- a/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt +++ b/ms/blueprintsprocessor/functions/k8s-connection-plugin/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/k8s/instance/K8sPluginInstanceApi.kt @@ -26,7 +26,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.healthcheck import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.healthcheck.K8sRbInstanceHealthCheckList import org.onap.ccsdk.cds.blueprintsprocessor.functions.k8s.instance.healthcheck.K8sRbInstanceHealthCheckSimple import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.http.HttpMethod.DELETE @@ -55,10 +55,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Did not find any objects with tag")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -77,10 +77,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -116,10 +116,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -155,10 +155,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -180,10 +180,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -205,10 +205,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -230,10 +230,10 @@ class K8sPluginInstanceApi( } else if (result.status == 500 && result.body.contains("Error finding master table")) null else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -252,10 +252,10 @@ class K8sPluginInstanceApi( ) parsedObject } else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to create config instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -274,10 +274,10 @@ class K8sPluginInstanceApi( ) parsedObject } else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to edit config instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -293,7 +293,7 @@ class K8sPluginInstanceApi( return result.status in 200..299 } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -312,10 +312,10 @@ class K8sPluginInstanceApi( ) parsedObject } else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get config instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -329,10 +329,10 @@ class K8sPluginInstanceApi( ) log.debug(result.toString()) if (result.status !in 200..299) - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to delete config instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -351,10 +351,10 @@ class K8sPluginInstanceApi( ) parsedObject } else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -373,10 +373,10 @@ class K8sPluginInstanceApi( ) parsedObject } else - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } @@ -390,10 +390,10 @@ class K8sPluginInstanceApi( ) log.debug(result.toString()) if (result.status !in 200..299) - throw BlueprintProcessorException(result.body) + throw BluePrintProcessorException(result.body) } catch (e: Exception) { log.error("Caught exception trying to get k8s rb instance") - throw BlueprintProcessorException("${e.message}") + throw BluePrintProcessorException("${e.message}") } } } diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizeExtensions.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizeExtensions.kt index 77adb0a87..d8e71d413 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizeExtensions.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizeExtensions.kt @@ -18,19 +18,19 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService /** * Register the MessagePrioritizationStateService and exposed dependency */ -fun BlueprintDependencyService.messagePrioritizationStateService(): MessagePrioritizationStateService = +fun BluePrintDependencyService.messagePrioritizationStateService(): MessagePrioritizationStateService = instance(MessagePrioritizationStateService::class) /** * Expose messagePrioritizationStateService to AbstractComponentFunction */ fun AbstractComponentFunction.messagePrioritizationStateService() = - BlueprintDependencyService.messagePrioritizationStateService() + BluePrintDependencyService.messagePrioritizationStateService() /** * MessagePrioritization correlation extensions diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/AbstractMessagePrioritizeProcessor.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/AbstractMessagePrioritizeProcessor.kt index 341a2aa8d..d4f8470c8 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/AbstractMessagePrioritizeProcessor.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/AbstractMessagePrioritizeProcessor.kt @@ -17,10 +17,10 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.kafka import org.apache.kafka.streams.processor.ProcessorContext -import org.onap.ccsdk.cds.blueprintsprocessor.message.kafka.AbstractBlueprintMessageProcessor +import org.onap.ccsdk.cds.blueprintsprocessor.message.kafka.AbstractBluePrintMessageProcessor /** CDS Message Prioritization Kafka Stream Processor abstract class to implement */ -abstract class AbstractMessagePrioritizeProcessor : AbstractBlueprintMessageProcessor() { +abstract class AbstractMessagePrioritizeProcessor : AbstractBluePrintMessageProcessor() { override fun init(processorContext: ProcessorContext) { this.processorContext = processorContext diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/DefaultMessagePrioritizeProcessor.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/DefaultMessagePrioritizeProcessor.kt index 6c1f7478c..1b0612492 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/DefaultMessagePrioritizeProcessor.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/DefaultMessagePrioritizeProcessor.kt @@ -23,7 +23,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.M import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessagePrioritizationStateService import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessageState import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -37,7 +37,7 @@ open class DefaultMessagePrioritizeProcessor( override suspend fun processNB(key: ByteArray, value: ByteArray) { val messagePrioritize = JacksonUtils.readValue(String(value), MessagePrioritization::class.java) - ?: throw BlueprintProcessorException("failed to convert") + ?: throw BluePrintProcessorException("failed to convert") try { kafkaMessagePrioritizationService.prioritize(messagePrioritize) } catch (e: Exception) { @@ -62,7 +62,7 @@ open class DefaultMessagePrioritizeProcessor( if (kafkaMessagePrioritizationService is AbstractKafkaMessagePrioritizationService) { kafkaMessagePrioritizationService.setKafkaProcessorContext(processorContext) } else { - throw BlueprintProcessorException( + throw BluePrintProcessorException( "messagePrioritizationService is not instance of " + "AbstractKafkaMessagePrioritizationService, it is ${kafkaMessagePrioritizationService.javaClass}" ) diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/KafkaMessagePrioritizationConsumer.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/KafkaMessagePrioritizationConsumer.kt index ecdcbff08..4ab399f54 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/KafkaMessagePrioritizationConsumer.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/KafkaMessagePrioritizationConsumer.kt @@ -24,15 +24,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.P import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.utils.MessageProcessorUtils.bluePrintProcessorSupplier import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService import org.onap.ccsdk.cds.blueprintsprocessor.message.service.KafkaStreamConsumerFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.splitCommaAsList open class KafkaMessagePrioritizationConsumer( - private val bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService, + private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService, private val kafkaMessagePrioritizationService: MessagePrioritizationService ) { @@ -50,7 +50,7 @@ open class KafkaMessagePrioritizationConsumer( return object : KafkaStreamConsumerFunction { val kafkaConsumerConfiguration = prioritizationConfiguration.kafkaConfiguration - ?: throw BlueprintProcessorException("failed to get kafka consumer configuration") + ?: throw BluePrintProcessorException("failed to get kafka consumer configuration") override suspend fun createTopology( messageConsumerProperties: MessageConsumerProperties, @@ -91,7 +91,7 @@ open class KafkaMessagePrioritizationConsumer( suspend fun startConsuming(prioritizationConfiguration: PrioritizationConfiguration) { val kafkaConsumerConfiguration = prioritizationConfiguration.kafkaConfiguration - ?: throw BlueprintProcessorException("failed to get kafka consumer configuration") + ?: throw BluePrintProcessorException("failed to get kafka consumer configuration") streamingConsumerService = consumerService(kafkaConsumerConfiguration.inputTopicSelector) diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/MessagePrioritizationSerde.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/MessagePrioritizationSerde.kt index 4b1a3f375..5595863d4 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/MessagePrioritizationSerde.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/kafka/MessagePrioritizationSerde.kt @@ -20,7 +20,7 @@ import org.apache.kafka.common.serialization.Deserializer import org.apache.kafka.common.serialization.Serde import org.apache.kafka.common.serialization.Serializer import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import java.nio.charset.Charset @@ -37,7 +37,7 @@ open class MessagePrioritizationSerde : Serde { return object : Deserializer { override fun deserialize(topic: String, data: ByteArray): MessagePrioritization { return JacksonUtils.readValue(String(data), MessagePrioritization::class.java) - ?: throw BlueprintProcessorException("failed to convert") + ?: throw BluePrintProcessorException("failed to convert") } override fun configure(configs: MutableMap?, isKey: Boolean) { diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/AbstractNatsMessagePrioritizationService.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/AbstractNatsMessagePrioritizationService.kt index babddbde4..502a7822d 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/AbstractNatsMessagePrioritizationService.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/AbstractNatsMessagePrioritizationService.kt @@ -22,7 +22,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.d import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.ids import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.service.AbstractMessagePrioritizationService import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.utils.MessageProcessorUtils -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsService import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.NatsClusterUtils import org.onap.ccsdk.cds.controllerblueprints.core.asByteArray import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType @@ -34,7 +34,7 @@ abstract class AbstractNatsMessagePrioritizationService( private val log = logger(AbstractNatsMessagePrioritizationService::class) - lateinit var bluePrintNatsService: BlueprintNatsService + lateinit var bluePrintNatsService: BluePrintNatsService override suspend fun output(messages: List) { log.info("$$$$$ received in output processor id(${messages.ids()})") diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/NatsMessagePrioritizationConsumer.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/NatsMessagePrioritizationConsumer.kt index 0976127d1..a0b2cf462 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/NatsMessagePrioritizationConsumer.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/nats/NatsMessagePrioritizationConsumer.kt @@ -22,29 +22,29 @@ import kotlinx.coroutines.runBlocking import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessagePrioritizationService import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization import org.onap.ccsdk.cds.blueprintsprocessor.nats.asJsonType -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsService import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.NatsClusterUtils import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.SubscriptionOptionsUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asType import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils open class NatsMessagePrioritizationConsumer( - private val bluePrintNatsLibPropertyService: BlueprintNatsLibPropertyService, + private val bluePrintNatsLibPropertyService: BluePrintNatsLibPropertyService, private val natsMessagePrioritizationService: MessagePrioritizationService ) { private val log = logger(NatsMessagePrioritizationConsumer::class) - lateinit var bluePrintNatsService: BlueprintNatsService + lateinit var bluePrintNatsService: BluePrintNatsService private lateinit var subscription: Subscription suspend fun startConsuming() { val prioritizationConfiguration = natsMessagePrioritizationService.getConfiguration() val natsConfiguration = prioritizationConfiguration.natsConfiguration - ?: throw BlueprintProcessorException("couldn't get NATS consumer configuration") + ?: throw BluePrintProcessorException("couldn't get NATS consumer configuration") check((natsMessagePrioritizationService is AbstractNatsMessagePrioritizationService)) { "messagePrioritizationService is not of type AbstractNatsMessagePrioritizationService." @@ -73,7 +73,7 @@ open class NatsMessagePrioritizationConsumer( log.info("Nats prioritization consumer listener shutdown complete") } - private fun consumerService(selector: String): BlueprintNatsService { + private fun consumerService(selector: String): BluePrintNatsService { return bluePrintNatsLibPropertyService.bluePrintNatsService(selector) } diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/service/MessagePrioritizationStateServiceImpl.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/service/MessagePrioritizationStateServiceImpl.kt index b66a2bd92..ed16fd44f 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/service/MessagePrioritizationStateServiceImpl.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/service/MessagePrioritizationStateServiceImpl.kt @@ -21,7 +21,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.M import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.PrioritizationMessageRepository import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.toFormatedCorrelation -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.addDate import org.onap.ccsdk.cds.controllerblueprints.core.utils.controllerDate @@ -48,7 +48,7 @@ open class MessagePrioritizationStateServiceImpl( override suspend fun getMessage(id: String): MessagePrioritization { return prioritizationMessageRepository.findById(id).orElseGet(null) - ?: throw BlueprintProcessorException("couldn't find message for id($id)") + ?: throw BluePrintProcessorException("couldn't find message for id($id)") } override suspend fun getMessages(ids: List): List? { diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageCorrelationUtils.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageCorrelationUtils.kt index f42be52af..7ab0be098 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageCorrelationUtils.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageCorrelationUtils.kt @@ -20,7 +20,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.C import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.toFormatedCorrelation import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.toTypeNCorrelation -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException object MessageCorrelationUtils { @@ -50,7 +50,7 @@ object MessageCorrelationUtils { val unknownMessageTypes = collectedMessages.filter { !types.contains(it.type) }.map { it.id } if (!unknownMessageTypes.isNullOrEmpty()) { - throw BlueprintProcessorException("Messages($unknownMessageTypes) is not in type of($types)") + throw BluePrintProcessorException("Messages($unknownMessageTypes) is not in type of($types)") } val copyTypes = types.toTypedArray().copyOf().toMutableList() diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageProcessorUtils.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageProcessorUtils.kt index 3eba4ed86..86cec3697 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageProcessorUtils.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/utils/MessageProcessorUtils.kt @@ -22,14 +22,14 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.MessagePrioritization import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.kafka.AbstractMessagePrioritizeProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.toFormatedCorrelation -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService object MessageProcessorUtils { /** Utility to create the cluster lock for message [messagePrioritization] prioritization procssing.*/ suspend fun prioritizationGrouplock(messagePrioritization: MessagePrioritization): ClusterLock? { - val clusterService = BlueprintDependencyService.optionalClusterService() + val clusterService = BluePrintDependencyService.optionalClusterService() return if (clusterService != null && clusterService.clusterJoined() && !messagePrioritization.correlationId.isNullOrBlank() @@ -39,31 +39,31 @@ object MessageProcessorUtils { val lockName = "prioritize::${messagePrioritization.group}::$correlationId" val clusterLock = clusterService.clusterLock(lockName) clusterLock.lock() - if (!clusterLock.isLocked()) throw BlueprintProcessorException("failed to lock($lockName)") + if (!clusterLock.isLocked()) throw BluePrintProcessorException("failed to lock($lockName)") clusterLock } else null } /** Utility to create the cluster lock for expiry scheduler*/ suspend fun prioritizationExpiryLock(): ClusterLock? { - val clusterService = BlueprintDependencyService.optionalClusterService() + val clusterService = BluePrintDependencyService.optionalClusterService() return if (clusterService != null && clusterService.clusterJoined()) { val lockName = "prioritize-expiry" val clusterLock = clusterService.clusterLock(lockName) clusterLock.lock() - if (!clusterLock.isLocked()) throw BlueprintProcessorException("failed to lock($lockName)") + if (!clusterLock.isLocked()) throw BluePrintProcessorException("failed to lock($lockName)") clusterLock } else null } /** Utility to create the cluster lock for expiry scheduler*/ suspend fun prioritizationCleanLock(): ClusterLock? { - val clusterService = BlueprintDependencyService.optionalClusterService() + val clusterService = BluePrintDependencyService.optionalClusterService() return if (clusterService != null && clusterService.clusterJoined()) { val lockName = "prioritize-clean" val clusterLock = clusterService.clusterLock(lockName) clusterLock.lock() - if (!clusterLock.isLocked()) throw BlueprintProcessorException("failed to lock($lockName)") + if (!clusterLock.isLocked()) throw BluePrintProcessorException("failed to lock($lockName)") clusterLock } else null } @@ -80,7 +80,7 @@ object MessageProcessorUtils { fun bluePrintProcessorSupplier(name: String): ProcessorSupplier { return ProcessorSupplier { // Dynamically resolve the Prioritization Processor - BlueprintDependencyService.instance>(name) + BluePrintDependencyService.instance>(name) } } } diff --git a/ms/blueprintsprocessor/functions/message-prioritization/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizationConsumerTest.kt b/ms/blueprintsprocessor/functions/message-prioritization/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizationConsumerTest.kt index 9f74daa50..e5dbe6af5 100644 --- a/ms/blueprintsprocessor/functions/message-prioritization/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizationConsumerTest.kt +++ b/ms/blueprintsprocessor/functions/message-prioritization/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/message/prioritization/MessagePrioritizationConsumerTest.kt @@ -27,8 +27,8 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.db.PrioritizationMessageRepository import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.kafka.DefaultMessagePrioritizeProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.kafka.KafkaMessagePrioritizationConsumer @@ -38,17 +38,17 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.s import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.service.SampleMessagePrioritizationService import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.service.SampleNatsMessagePrioritizationService import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.utils.MessagePrioritizationSample -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.message.BluePrintMessageLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.message.service.KafkaMessageProducerService -import org.onap.ccsdk.cds.blueprintsprocessor.nats.BlueprintNatsLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.BluePrintNatsLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.NatsClusterUtils import org.onap.ccsdk.cds.controllerblueprints.core.asByteArray import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.boot.test.mock.mockito.MockBean @@ -65,8 +65,8 @@ import kotlin.test.assertNotNull @DirtiesContext @ContextConfiguration( classes = [ - BlueprintMessageLibConfiguration::class, BlueprintNatsLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class, + BluePrintMessageLibConfiguration::class, BluePrintNatsLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, MessagePrioritizationConfiguration::class, TestDatabaseConfiguration::class ] ) @@ -115,10 +115,10 @@ open class MessagePrioritizationConsumerTest { lateinit var prioritizationMessageRepository: PrioritizationMessageRepository @Autowired - lateinit var bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService + lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService @Autowired - lateinit var bluePrintNatsLibPropertyService: BlueprintNatsLibPropertyService + lateinit var bluePrintNatsLibPropertyService: BluePrintNatsLibPropertyService @Autowired lateinit var messagePrioritizationStateService: MessagePrioritizationStateService @@ -128,15 +128,15 @@ open class MessagePrioritizationConsumerTest { @Before fun setup() { - BlueprintDependencyService.inject(applicationContext) + BluePrintDependencyService.inject(applicationContext) } @Test - fun testBlueprintKafkaJDBCKeyStore() { + fun testBluePrintKafkaJDBCKeyStore() { runBlocking { assertNotNull(prioritizationMessageRepository, "failed to get prioritizationMessageRepository") - val messagePrioritizationService: MessagePrioritizationStateService = BlueprintDependencyService + val messagePrioritizationService: MessagePrioritizationStateService = BluePrintDependencyService .instance(MessagePrioritizationStateService::class) assertNotNull(messagePrioritizationService, "failed to get messagePrioritizationService") @@ -248,7 +248,7 @@ open class MessagePrioritizationConsumerTest { ) // Register the processor - BlueprintDependencyService.registerSingleton( + BluePrintDependencyService.registerSingleton( MessagePrioritizationConstants.PROCESSOR_PRIORITIZE, defaultMessagePrioritizeProcessor ) diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfExecutorExtensions.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfExecutorExtensions.kt index 6e667c28b..b964388cb 100644 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfExecutorExtensions.kt +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfExecutorExtensions.kt @@ -22,13 +22,13 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.Dev import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils /** * Register the Netconf module exposed dependency */ -fun BlueprintDependencyService.netconfClientService(): ResourceResolutionService = +fun BluePrintDependencyService.netconfClientService(): ResourceResolutionService = instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) fun AbstractComponentFunction.netconfDevice(requirementName: String): NetconfDevice { diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt index cdfd93c82..f3df55b4b 100644 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt @@ -31,10 +31,10 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.BlueprintJythonService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.context.ApplicationContext @@ -66,7 +66,7 @@ class ComponentNetconfExecutorTest { ExecutionServiceInput::class.java )!! - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -92,9 +92,9 @@ class ComponentNetconfExecutorTest { // TODO("Set Attribute properties") val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-netconf") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentNetconfExecutor") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-netconf") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentNetconfExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") // Set Step Inputs in Blueprint Runtime Service componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService val stepInputData = StepData().apply { diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt index b32ccea13..e2b6f6560 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt @@ -24,8 +24,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts.BlueprintJythonServiceImpl import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts.PythonExecutorConstants import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment import org.slf4j.LoggerFactory @@ -66,12 +66,12 @@ open class ComponentJythonExecutor( .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName) val artifactName: String = operationAssignment.implementation?.primary - ?: throw BlueprintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") + ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) val pythonFileName = artifactDefinition.file - ?: throw BlueprintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)") + ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)") val pythonClassName = FilenameUtils.getBaseName(pythonFileName) @@ -80,7 +80,7 @@ open class ComponentJythonExecutor( checkNotEmpty(content) { "artifact ($artifactName) content is empty" } val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode - ?: throw BlueprintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") + ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") val jythonInstance: MutableMap = hashMapOf() jythonInstance["log"] = LoggerFactory.getLogger(pythonClassName) @@ -99,6 +99,6 @@ open class ComponentJythonExecutor( componentFunction.operationName = operationName componentFunction.processId = processId componentFunction.workflowName = workflowName - componentFunction.scriptType = BlueprintConstants.SCRIPT_JYTHON + componentFunction.scriptType = BluePrintConstants.SCRIPT_JYTHON } } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt index 539e03dc8..b8806b329 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutor.kt @@ -23,7 +23,7 @@ import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.withTimeout -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier @@ -35,7 +35,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintMod import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceConstant import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists @@ -56,7 +56,7 @@ import org.springframework.stereotype.Component @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class ComponentRemotePythonExecutor( private val remoteScriptExecutionService: RemoteScriptExecutionService, - private val bluePrintPropertiesService: BlueprintPropertiesService, + private val bluePrintPropertiesService: BluePrintPropertiesService, private val blueprintModelRepository: BlueprintModelRepository ) : AbstractComponentFunction() { @@ -111,7 +111,7 @@ open class ComponentRemotePythonExecutor( .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName) val artifactName: String = operationAssignment.implementation?.primary - ?: throw BlueprintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") + ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) @@ -314,7 +314,7 @@ open class ComponentRemotePythonExecutor( } private fun noBlueprintErrors() = - bluePrintRuntimeService.getBlueprintError().stepErrors(stepName).isNullOrEmpty() + bluePrintRuntimeService.getBluePrintError().stepErrors(stepName).isNullOrEmpty() override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { addError("Failed in ComponentRemotePythonExecutor : ${runtimeException.message}") diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSL.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSL.kt index 6788310aa..3df25c402 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSL.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSL.kt @@ -18,8 +18,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ArrayNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType @@ -32,53 +32,53 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.nodeType import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils /** Component Extensions **/ -fun BlueprintTypes.nodeTypeComponentRemotePythonExecutor(): NodeType { +fun BluePrintTypes.nodeTypeComponentRemotePythonExecutor(): NodeType { return nodeType( - id = "component-remote-python-executor", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, + id = "component-remote-python-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, description = "This is Remote Python Execution Component." ) { attribute( - ComponentRemotePythonExecutor.ATTRIBUTE_PREPARE_ENV_LOG, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemotePythonExecutor.ATTRIBUTE_PREPARE_ENV_LOG, BluePrintConstants.DATA_TYPE_STRING, false ) attribute( - ComponentRemotePythonExecutor.ATTRIBUTE_EXEC_CMD_LOG, BlueprintConstants.DATA_TYPE_LIST, + ComponentRemotePythonExecutor.ATTRIBUTE_EXEC_CMD_LOG, BluePrintConstants.DATA_TYPE_LIST, false ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } attribute( - ComponentRemotePythonExecutor.ATTRIBUTE_RESPONSE_DATA, BlueprintConstants.DATA_TYPE_JSON, + ComponentRemotePythonExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false ) operation("ComponentRemotePythonExecutor", "ComponentRemotePythonExecutor Operation") { inputs { property( - ComponentRemotePythonExecutor.INPUT_ENDPOINT_SELECTOR, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemotePythonExecutor.INPUT_ENDPOINT_SELECTOR, BluePrintConstants.DATA_TYPE_STRING, false, "Remote Container or Server selector name." ) { defaultValue(ComponentRemotePythonExecutor.DEFAULT_SELECTOR) } property( - ComponentRemotePythonExecutor.INPUT_DYNAMIC_PROPERTIES, BlueprintConstants.DATA_TYPE_JSON, + ComponentRemotePythonExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON, false, "Dynamic Json Content or DSL Json reference." ) property( - ComponentRemotePythonExecutor.INPUT_ARGUMENT_PROPERTIES, BlueprintConstants.DATA_TYPE_JSON, + ComponentRemotePythonExecutor.INPUT_ARGUMENT_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON, false, "Argument Json Content or DSL Json reference." ) property( - ComponentRemotePythonExecutor.INPUT_COMMAND, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemotePythonExecutor.INPUT_COMMAND, BluePrintConstants.DATA_TYPE_STRING, true, "Command to execute." ) property( - ComponentRemotePythonExecutor.INPUT_PACKAGES, BlueprintConstants.DATA_TYPE_LIST, + ComponentRemotePythonExecutor.INPUT_PACKAGES, BluePrintConstants.DATA_TYPE_LIST, false, "Packages to install based on type." ) { entrySchema("dt-system-packages") @@ -88,26 +88,26 @@ fun BlueprintTypes.nodeTypeComponentRemotePythonExecutor(): NodeType { } } -fun BlueprintTypes.dataTypeDtSystemPackages(): DataType { +fun BluePrintTypes.dataTypeDtSystemPackages(): DataType { return dataType( - id = "dt-system-packages", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT, + id = "dt-system-packages", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, description = "This represent System Package Data Type" ) { - property("type", BlueprintConstants.DATA_TYPE_LIST, true, "") { + property("type", BluePrintConstants.DATA_TYPE_LIST, true, "") { constrain { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) validValues(arrayListOf("ansible_galaxy".asJsonPrimitive(), "pip".asJsonPrimitive())) } } - property("package", BlueprintConstants.DATA_TYPE_LIST, true, "") { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + property("package", BluePrintConstants.DATA_TYPE_LIST, true, "") { + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } } } /** Component Builder */ -fun BlueprintTypes.nodeTemplateComponentRemotePythonExecutor( +fun BluePrintTypes.nodeTemplateComponentRemotePythonExecutor( id: String, description: String, block: ComponentRemotePythonExecutorNodeTemplateBuilder.() -> Unit diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/JythonComponentFunction.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/JythonComponentFunction.kt index 0ac542bd0..891b09d88 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/JythonComponentFunction.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/JythonComponentFunction.kt @@ -18,15 +18,15 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException open class JythonComponentFunction : AbstractScriptComponentFunction() { override suspend fun processNB(executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceImpl.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceImpl.kt index 9faacd9de..b0ce73588 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceImpl.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceImpl.kt @@ -20,11 +20,11 @@ import com.fasterxml.jackson.databind.node.ArrayNode import org.apache.commons.io.FilenameUtils import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.BlueprintJythonService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.Logger import org.slf4j.LoggerFactory @@ -42,7 +42,7 @@ class BlueprintJythonServiceImpl( val log: Logger = LoggerFactory.getLogger(BlueprintJythonService::class.java) inline fun jythonInstance( - blueprintContext: BlueprintContext, + blueprintContext: BluePrintContext, pythonClassName: String, content: String, dependencyInstanceNames: MutableMap? @@ -54,7 +54,7 @@ class BlueprintJythonServiceImpl( pythonPath.addAll(pythonExecutorProperty.modulePaths) val blueprintPythonConfigurations = - BlueprintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf()) + BluePrintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf()) val blueprintPythonHost = BlueprintPythonHost(blueprintPythonConfigurations) val pyObject = blueprintPythonHost.getPythonComponent(content, pythonClassName, dependencyInstanceNames) @@ -64,7 +64,7 @@ class BlueprintJythonServiceImpl( return pyObject.__tojava__(T::class.java) as T } - override fun jythonComponentInstance(bluePrintContext: BlueprintContext, scriptClassReference: String): + override fun jythonComponentInstance(bluePrintContext: BluePrintContext, scriptClassReference: String): BlueprintFunctionNode<*, *> { val pythonFileName = bluePrintContext.rootPath @@ -101,13 +101,13 @@ class BlueprintJythonServiceImpl( val blueprintBasePath: String = bluePrintContext.rootPath val artifactName: String = operationAssignment.implementation?.primary - ?: throw BlueprintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") + ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)") val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) val pythonFileName = artifactDefinition.file - ?: throw BlueprintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)") + ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)") val pythonClassName = FilenameUtils.getBaseName(pythonFileName) log.info("Getting Jython Script Class($pythonClassName)") @@ -125,7 +125,7 @@ class BlueprintJythonServiceImpl( val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode - ?: throw BlueprintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") + ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") instanceDependenciesNode.forEach { instanceName -> jythonInstances[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue()) diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHost.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHost.kt index 0fe68cf6a..f8f0e7e32 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHost.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHost.kt @@ -16,13 +16,13 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage import org.python.core.PyObject import org.python.util.PythonInterpreter @Deprecated("CDS won't support JythonService") -open class BlueprintPythonHost(private val bluePrintPython: BlueprintPython) { +open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython) { private val blueprintPythonInterpreterProxy: BlueprintPythonInterpreterProxy @@ -45,14 +45,14 @@ open class BlueprintPythonHost(private val bluePrintPython: BlueprintPython) { bluePrintPython.moduleName = "Blueprint Python Script [Class Name = $interfaceName]" try { return blueprintPythonInterpreterProxy.getPythonInstance(properties) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { val errorMsg = "Failed to get python instance." throw e.updateErrorMessage( ExecutionServiceDomains.PYTHON_EXECUTOR, errorMsg, "Error in environment properties" ) } catch (e: Exception) { - throw BlueprintProcessorException("Failed to execute Jython component $e", e) + throw BluePrintProcessorException("Failed to execute Jython component $e", e) } } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonInterpreterProxy.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonInterpreterProxy.kt index 9d98d90c7..0fb33f9c2 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonInterpreterProxy.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonInterpreterProxy.kt @@ -15,13 +15,13 @@ */ package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.python.core.PyObject import org.python.core.PySyntaxError import org.python.util.PythonInterpreter @Deprecated("CDS won't support JythonService") -open class BlueprintPythonInterpreterProxy(private val bluePrintPython: BlueprintPython) : PythonInterpreter() { +open class BlueprintPythonInterpreterProxy(private val bluePrintPython: BluePrintPython) : PythonInterpreter() { fun getPythonInstance(properties: MutableMap?): PyObject { properties?.forEach { (name, value) -> @@ -34,7 +34,7 @@ open class BlueprintPythonInterpreterProxy(private val bluePrintPython: Blueprin try { this.exec(bluePrintPython.content) } catch (e: PySyntaxError) { - throw BlueprintProcessorException("Error executing Jython code! Python error: '$e'", e) + throw BluePrintProcessorException("Error executing Jython code! Python error: '$e'", e) } } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/PythonExecutorConfiguration.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/PythonExecutorConfiguration.kt index 3484fdbeb..593c0552b 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/PythonExecutorConfiguration.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/PythonExecutorConfiguration.kt @@ -52,7 +52,7 @@ class PythonExecutorConstants { } @Deprecated("CDS won't support JythonService") -open class BlueprintPython( +open class BluePrintPython( executablePath: String, blueprintPythonPlatform: MutableList, val argv: MutableList diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt index 089a33931..d5fa0b20c 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt @@ -26,9 +26,9 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.mock.MockInstanceConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts.PythonExecutorConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.scripts.PythonExecutorProperty -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -63,15 +63,15 @@ class ComponentJythonExecutorTest { ExecutionServiceInput::class.java )!! - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-jython") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentJythonExecutor") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-jython") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentJythonExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") componentJythonExecutor.bluePrintRuntimeService = bluePrintRuntimeService val stepInputData = StepData().apply { name = "activate-jython" diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSLTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSLTest.kt index 0318664a0..46a3120d5 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSLTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorDSLTest.kt @@ -17,21 +17,21 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import kotlin.test.assertNotNull class ComponentRemotePythonExecutorDSLTest { @Test fun testNodeTypeComponentRemotePythonExecutor() { - val nodeType = BlueprintTypes.nodeTypeComponentRemotePythonExecutor() + val nodeType = BluePrintTypes.nodeTypeComponentRemotePythonExecutor() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeComponentRemotePythonExecutor") } @Test fun testNodeTemplateComponentRemotePythonExecutor() { - val nodeTemplate = BlueprintTypes.nodeTemplateComponentRemotePythonExecutor( + val nodeTemplate = BluePrintTypes.nodeTemplateComponentRemotePythonExecutor( "test-nodetemplate", "test nodetemplate" ) { diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt index 2fd33f2a6..b81f05c6e 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentRemotePythonExecutorTest.kt @@ -22,7 +22,7 @@ import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.runBlocking import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput @@ -33,13 +33,13 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.RemoteScriptExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -53,7 +53,7 @@ class ComponentRemotePythonExecutorTest { val componentRemotePythonExecutor = ComponentRemotePythonExecutor( remoteScriptExecutionService, - mockk(), + mockk(), mockk() ) @@ -63,7 +63,7 @@ class ComponentRemotePythonExecutorTest { ExecutionServiceInput::class.java )!! - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "123456-1000", "./../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" ) @@ -75,9 +75,9 @@ class ComponentRemotePythonExecutorTest { ) val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-python") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemotePythonExecutor") - stepMetaData.putJsonElement(BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-python") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemotePythonExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") componentRemotePythonExecutor.bluePrintRuntimeService = bluePrintRuntimeService val stepInputData = StepData().apply { name = "execute-remote-python" @@ -98,12 +98,12 @@ class ComponentRemotePythonExecutorTest { val remoteScriptExecutionService = MockRemoteScriptExecutionService() val componentRemotePythonExecutor = ComponentRemotePythonExecutor( remoteScriptExecutionService, - mockk(), + mockk(), mockk() ) - val bluePrintRuntime = mockk("123456-1000") + val bluePrintRuntime = mockk("123456-1000") - every { bluePrintRuntime.getBlueprintError() } answers { BlueprintError() } // successful case. + every { bluePrintRuntime.getBluePrintError() } answers { BluePrintError() } // successful case. every { bluePrintRuntime.setNodeTemplateAttributeValue(any(), any(), any()) } answers {} val input = getMockedOutput(bluePrintRuntime) @@ -115,20 +115,20 @@ class ComponentRemotePythonExecutorTest { /** * Mocked input information for remote python executor. */ - fun getMockedOutput(svc: DefaultBlueprintRuntimeService): + fun getMockedOutput(svc: DefaultBluePrintRuntimeService): ExecutionServiceInput { val stepMetaData: MutableMap = hashMapOf() stepMetaData.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, + BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-python" ) stepMetaData.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_INTERFACE, + BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemotePythonExecutor" ) stepMetaData.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process" + BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process" ) val mapper = ObjectMapper() @@ -138,15 +138,15 @@ class ComponentRemotePythonExecutorTest { val operationalInputs: MutableMap = hashMapOf() operationalInputs.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, + BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "execute-remote-python" ) operationalInputs.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_INTERFACE, + BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentRemotePythonExecutor" ) operationalInputs.putJsonElement( - BlueprintConstants.PROPERTY_CURRENT_OPERATION, "process" + BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process" ) operationalInputs.putJsonElement("endpoint-selector", "aai") operationalInputs.putJsonElement("dynamic-properties", rootNode) @@ -179,7 +179,7 @@ class ComponentRemotePythonExecutorTest { "ComponentRemotePythonExecutor", "process" ) } returns operationOutputs - val bluePrintRuntimeService = BlueprintMetadataUtils.bluePrintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.bluePrintRuntime( "123456-1000", "./../../../../components/model-" + "catalog/blueprint-model/test-blueprint/" + diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceTest.kt index ad87f3c19..94ec1413f 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintJythonServiceTest.kt @@ -23,7 +23,7 @@ import io.mockk.mockk import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -39,13 +39,13 @@ import kotlin.test.assertNotNull "blueprints.processor.functions.python.executor.executionPath=./../../../../components/scripts/python/ccsdk_blueprints"]) class BlueprintJythonServiceTest { - lateinit var blueprintContext: BlueprintContext + lateinit var blueprintContext: BluePrintContext @Autowired private lateinit var blueprintJythonService: BlueprintJythonServiceImpl @BeforeTest fun init() { - blueprintContext = mockk() + blueprintContext = mockk() every { blueprintContext.rootPath } returns normalizedPathName("target") } diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHostTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHostTest.kt index 2ebd10c38..0efaaa113 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHostTest.kt +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/scripts/BlueprintPythonHostTest.kt @@ -26,7 +26,7 @@ import kotlin.test.BeforeTest import kotlin.test.assertNotNull @RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BlueprintPython::class, PythonExecutorProperty::class, String::class]) +@ContextConfiguration(classes = [BluePrintPython::class, PythonExecutorProperty::class, String::class]) @TestPropertySource( properties = [ @@ -48,7 +48,7 @@ class BlueprintPythonHostTest { pythonPath.add(blueprintBasePath) pythonPath.addAll(pythonExecutorProperty.modulePaths) - blueprintPythonHost = BlueprintPythonHost(BlueprintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf())) + blueprintPythonHost = BlueprintPythonHost(BluePrintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf())) } @Test diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt index 69db6cf8e..8087f7e3f 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt @@ -1,12 +1,12 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService -class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BlueprintContext) : - DefaultBlueprintRuntimeService(id, bluePrintContext) { +class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) : + DefaultBluePrintRuntimeService(id, bluePrintContext) { private lateinit var resolutionId: String private var resourceStore: MutableMap = hashMapOf() @@ -29,7 +29,7 @@ class ResourceAssignmentRuntimeService(private var id: String, private var blueP fun getResolutionStore(key: String): JsonNode { return resourceStore[key] - ?: throw BlueprintProcessorException("failed to get execution property ($key)") + ?: throw BluePrintProcessorException("failed to get execution property ($key)") } fun checkResolutionStore(key: String): Boolean { @@ -62,7 +62,7 @@ class ResourceAssignmentRuntimeService(private var id: String, private var blueP fun getDictionaryStore(key: String): JsonNode { return resourceStore["dictionary-$key"] - ?: throw BlueprintProcessorException("failed to get execution property (dictionary-$key)") + ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)") } fun checkDictionaryStore(key: String): Boolean { diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSL.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSL.kt index 66077c4ed..c755e89bf 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSL.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSL.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.dsl.PropertyDefinitionBuilder @@ -24,12 +24,12 @@ import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition /** Resource Definition DSL **/ -fun BlueprintTypes.resourceDefinitions(block: ResourceDefinitionsBuilder.() -> Unit): +fun BluePrintTypes.resourceDefinitions(block: ResourceDefinitionsBuilder.() -> Unit): MutableMap { return ResourceDefinitionsBuilder().apply(block).build() } -fun BlueprintTypes.resourceDefinition( +fun BluePrintTypes.resourceDefinition( name: String, description: String, block: ResourceDefinitionBuilder.() -> Unit @@ -38,12 +38,12 @@ fun BlueprintTypes.resourceDefinition( } /** Resource Mapping DSL **/ -fun BlueprintTypes.resourceAssignments(block: ResourceAssignmentsBuilder.() -> Unit): +fun BluePrintTypes.resourceAssignments(block: ResourceAssignmentsBuilder.() -> Unit): MutableMap { return ResourceAssignmentsBuilder().apply(block).build() } -fun BlueprintTypes.resourceAssignment( +fun BluePrintTypes.resourceAssignment( name: String, dictionaryName: String, dictionarySource: String, diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt index ada1a720e..0435d1d2c 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt @@ -22,7 +22,7 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.ObjectNode import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asObjectNode import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing @@ -94,11 +94,11 @@ open class ResourceResolutionComponent(private val resourceResolutionService: Re // validate inputs if we need to store the resource and template resolution. if (storeResult) { if (resolutionKey.isNotEmpty() && (resourceId.isNotEmpty() || resourceType.isNotEmpty())) { - throw BlueprintProcessorException("Can't proceed with the resolution: either provide resolution-key OR combination of resource-id and resource-type.") + throw BluePrintProcessorException("Can't proceed with the resolution: either provide resolution-key OR combination of resource-id and resource-type.") } else if ((resourceType.isNotEmpty() && resourceId.isEmpty()) || (resourceType.isEmpty() && resourceId.isNotEmpty())) { - throw BlueprintProcessorException("Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.") + throw BluePrintProcessorException("Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.") } else if (resourceType.isEmpty() && resourceId.isEmpty() && resolutionKey.isEmpty()) { - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Can't proceed with the resolution: can't persist resolution without a correlation key. " + "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false." ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSL.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSL.kt index c8b9e2c87..774873a43 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSL.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType @@ -33,94 +33,94 @@ import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType /** Component Extensions **/ fun ServiceTemplateBuilder.nodeTypeComponentResourceResolution() { - val nodeType = BlueprintTypes.nodeTypeComponentResourceResolution() + val nodeType = BluePrintTypes.nodeTypeComponentResourceResolution() if (this.nodeTypes == null) this.nodeTypes = hashMapOf() this.nodeTypes!![nodeType.id!!] = nodeType } -fun BlueprintTypes.nodeTypeComponentResourceResolution(): NodeType { +fun BluePrintTypes.nodeTypeComponentResourceResolution(): NodeType { return nodeType( - id = "component-resource-resolution", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, + id = "component-resource-resolution", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, description = "Resource Assignment Component" ) { attribute( - ResourceResolutionComponent.ATTRIBUTE_ASSIGNMENT_PARAM, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.ATTRIBUTE_ASSIGNMENT_PARAM, BluePrintConstants.DATA_TYPE_STRING, true ) attribute( - ResourceResolutionComponent.ATTRIBUTE_STATUS, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true ) operation("ResourceResolutionComponent", "ResourceResolutionComponent Operation") { inputs { property( - ResourceResolutionComponent.INPUT_REQUEST_ID, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.INPUT_REQUEST_ID, BluePrintConstants.DATA_TYPE_STRING, true, "Request Id, Unique Id for the request." ) property( - ResourceResolutionComponent.INPUT_RESOURCE_ID, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.INPUT_RESOURCE_ID, BluePrintConstants.DATA_TYPE_STRING, false, "Resource Id." ) property( - ResourceResolutionComponent.INPUT_ACTION_NAME, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.INPUT_ACTION_NAME, BluePrintConstants.DATA_TYPE_STRING, false, "Action Name of the process" ) property( - ResourceResolutionComponent.INPUT_DYNAMIC_PROPERTIES, BlueprintConstants.DATA_TYPE_JSON, + ResourceResolutionComponent.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON, false, "Dynamic Json Content or DSL Json reference." ) property( - ResourceResolutionComponent.INPUT_RESOLUTION_KEY, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.INPUT_RESOLUTION_KEY, BluePrintConstants.DATA_TYPE_STRING, false, "Key for service instance related correlation." ) property( - ResourceResolutionComponent.INPUT_RESOLUTION_SUMMARY, BlueprintConstants.DATA_TYPE_BOOLEAN, + ResourceResolutionComponent.INPUT_RESOLUTION_SUMMARY, BluePrintConstants.DATA_TYPE_BOOLEAN, false, "Enables ResolutionSummary output" ) property( - ResourceResolutionComponent.INPUT_OCCURRENCE, BlueprintConstants.DATA_TYPE_INTEGER, + ResourceResolutionComponent.INPUT_OCCURRENCE, BluePrintConstants.DATA_TYPE_INTEGER, false, "Number of time to perform the resolution." ) { defaultValue(1) } property( - ResourceResolutionComponent.INPUT_STORE_RESULT, BlueprintConstants.DATA_TYPE_BOOLEAN, + ResourceResolutionComponent.INPUT_STORE_RESULT, BluePrintConstants.DATA_TYPE_BOOLEAN, false, "Whether or not to store the output." ) property( - ResourceResolutionComponent.INPUT_RESOURCE_TYPE, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.INPUT_RESOURCE_TYPE, BluePrintConstants.DATA_TYPE_STRING, false, "Request type." ) property( - ResourceResolutionComponent.INPUT_ARTIFACT_PREFIX_NAMES, BlueprintConstants.DATA_TYPE_LIST, + ResourceResolutionComponent.INPUT_ARTIFACT_PREFIX_NAMES, BluePrintConstants.DATA_TYPE_LIST, true, "Template , Resource Assignment Artifact Prefix names" ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } } outputs { property( - ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_PARAMS, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_PARAMS, BluePrintConstants.DATA_TYPE_STRING, true, "Output Response" ) property( - ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_MAP, BlueprintConstants.DATA_TYPE_MAP, + ResourceResolutionComponent.OUTPUT_RESOURCE_ASSIGNMENT_MAP, BluePrintConstants.DATA_TYPE_MAP, true, "Output Resolved Values" ) property( - ResourceResolutionComponent.OUTPUT_STATUS, BlueprintConstants.DATA_TYPE_STRING, + ResourceResolutionComponent.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING, true, "Status of the Component Execution ( success or failure )" ) } @@ -134,7 +134,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentResourceResolution( description: String, block: ComponentResourceResolutionNodeTemplateBuilder.() -> Unit ) { - val nodeTemplate = BlueprintTypes.nodeTemplateComponentResourceResolution( + val nodeTemplate = BluePrintTypes.nodeTemplateComponentResourceResolution( id, description, block ) @@ -142,7 +142,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentResourceResolution( nodeTemplates!![nodeTemplate.id!!] = nodeTemplate } -fun BlueprintTypes.nodeTemplateComponentResourceResolution( +fun BluePrintTypes.nodeTemplateComponentResourceResolution( id: String, description: String, block: ComponentResourceResolutionNodeTemplateBuilder.() -> Unit diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionExtensions.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionExtensions.kt index a3cc1ef18..4774ad57a 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionExtensions.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionExtensions.kt @@ -20,22 +20,22 @@ import kotlinx.coroutines.runBlocking import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolution import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionDBService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService /** * Register the Resolution module exposed dependency */ -fun BlueprintDependencyService.resourceResolutionService(): ResourceResolutionService = +fun BluePrintDependencyService.resourceResolutionService(): ResourceResolutionService = instance(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) -fun BlueprintDependencyService.resourceResolutionDBService(): ResourceResolutionDBService = +fun BluePrintDependencyService.resourceResolutionDBService(): ResourceResolutionDBService = instance(ResourceResolutionDBService::class.java) suspend fun AbstractComponentFunction.storedContentFromResolvedArtifactNB( resolutionKey: String, artifactName: String ): String { - return BlueprintDependencyService.resourceResolutionService() + return BluePrintDependencyService.resourceResolutionService() .resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey) } @@ -44,7 +44,7 @@ suspend fun AbstractComponentFunction.storedResourceResolutionsNB( artifactName: String, occurrence: Int = 1 ): List { - return BlueprintDependencyService.resourceResolutionDBService() + return BluePrintDependencyService.resourceResolutionDBService() .findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence( bluePrintRuntimeService, resolutionKey, @@ -57,7 +57,7 @@ suspend fun AbstractComponentFunction.storedResourceResolutionsNB( * Return resolved and mashed artifact content for artifact prefix [artifactPrefix] */ suspend fun AbstractComponentFunction.contentFromResolvedArtifactNB(artifactPrefix: String): String { - return BlueprintDependencyService.resourceResolutionService() + return BluePrintDependencyService.resourceResolutionService() .resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactPrefix, mapOf()) .first } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt index ea420dca4..6b4260ad0 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt @@ -27,15 +27,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.T import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceDefinitionUtils.createResourceAssignments -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -56,13 +56,13 @@ interface ResourceResolutionService { fun registeredResourceSources(): List suspend fun resolveFromDatabase( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, resolutionKey: String ): String suspend fun resolveResources( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, artifactNames: List, properties: Map, @@ -70,7 +70,7 @@ interface ResourceResolutionService { ): ResourceResolutionResult suspend fun resolveResources( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, artifactPrefix: String, properties: Map @@ -80,7 +80,7 @@ interface ResourceResolutionService { * with other [resourceDefinitions] dependencies for the sources [sources] * Used to get the same resource values from multiple sources. **/ suspend fun resolveResourceDefinition( - blueprintRuntimeService: BlueprintRuntimeService<*>, + blueprintRuntimeService: BluePrintRuntimeService<*>, resourceDefinitions: MutableMap, resolveDefinition: String, sources: List @@ -88,7 +88,7 @@ interface ResourceResolutionService { MutableMap suspend fun resolveResourceAssignments( - blueprintRuntimeService: BlueprintRuntimeService<*>, + blueprintRuntimeService: BluePrintRuntimeService<*>, resourceDefinitions: MutableMap, resourceAssignments: MutableList, artifactPrefix: String, @@ -100,7 +100,7 @@ interface ResourceResolutionService { open class ResourceResolutionServiceImpl( private var applicationContext: ApplicationContext, private var templateResolutionDBService: TemplateResolutionService, - private var blueprintTemplateService: BlueprintTemplateService, + private var blueprintTemplateService: BluePrintTemplateService, private var resourceResolutionDBService: ResourceResolutionDBService ) : ResourceResolutionService { @@ -114,7 +114,7 @@ open class ResourceResolutionServiceImpl( } override suspend fun resolveFromDatabase( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, resolutionKey: String ): String { @@ -126,7 +126,7 @@ open class ResourceResolutionServiceImpl( } override suspend fun resolveResources( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, artifactNames: List, properties: Map, @@ -153,16 +153,16 @@ open class ResourceResolutionServiceImpl( val failedResolution = resourceAssignmentList.filter { it.status != "success" && it.property?.required == true }.map { it.name } if (failedResolution.isNotEmpty()) { val errorMessages = mutableListOf("Failed to resolve required values: $failedResolution").apply { - this.addAll(resourceAssignmentRuntimeService.getBlueprintError().allErrors()) + this.addAll(resourceAssignmentRuntimeService.getBluePrintError().allErrors()) } - bluePrintRuntimeService.getBlueprintError().addErrors(stepName, errorMessages) + bluePrintRuntimeService.getBluePrintError().addErrors(stepName, errorMessages) } } return ResourceResolutionResult(templateMap, assignmentMap) } override suspend fun resolveResources( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, artifactPrefix: String, properties: Map @@ -181,7 +181,7 @@ open class ResourceResolutionServiceImpl( val resourceAssignments: MutableList = JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java) as? MutableList - ?: throw BlueprintProcessorException("couldn't get Dictionary Definitions") + ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions") if (isToStore(properties)) { val existingResourceResolution = isNewResolution(bluePrintRuntimeService, properties, artifactPrefix) @@ -245,7 +245,7 @@ open class ResourceResolutionServiceImpl( } override suspend fun resolveResourceDefinition( - blueprintRuntimeService: BlueprintRuntimeService<*>, + blueprintRuntimeService: BluePrintRuntimeService<*>, resourceDefinitions: MutableMap, resolveDefinition: String, sources: List @@ -269,7 +269,7 @@ open class ResourceResolutionServiceImpl( * request. */ override suspend fun resolveResourceAssignments( - blueprintRuntimeService: BlueprintRuntimeService<*>, + blueprintRuntimeService: BluePrintRuntimeService<*>, resourceDefinitions: MutableMap, resourceAssignments: MutableList, artifactPrefix: String, @@ -292,7 +292,7 @@ open class ResourceResolutionServiceImpl( // Execute Non Dependent Assignments in parallel ( ie asynchronously ) val deferred = batchResourceAssignments .filter { it.name != "*" && it.name != "start" } - .filter { it.status != BlueprintConstants.STATUS_SUCCESS } + .filter { it.status != BluePrintConstants.STATUS_SUCCESS } .map { resourceAssignment -> async { val dictionaryName = resourceAssignment.dictionaryName @@ -302,12 +302,12 @@ open class ResourceResolutionServiceImpl( val resourceAssignmentProcessor = applicationContext.getBean(processorName) as? ResourceAssignmentProcessor - ?: throw BlueprintProcessorException( + ?: throw BluePrintProcessorException( "failed to get resource processor ($processorName) " + "for resource assignment(${resourceAssignment.name})" ) try { - // Set Blueprint Runtime Service + // Set BluePrint Runtime Service resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService // Set Resource Dictionaries resourceAssignmentProcessor.resourceDictionaries = resourceDefinitions @@ -328,10 +328,10 @@ open class ResourceResolutionServiceImpl( } // Set errors from RA - blueprintRuntimeService.setBlueprintError(resourceAssignmentRuntimeService.getBlueprintError()) + blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError()) } catch (e: RuntimeException) { log.error("Fail in processing ${resourceAssignment.name}", e) - throw BlueprintProcessorException(e) + throw BluePrintProcessorException(e) } } } @@ -359,10 +359,10 @@ open class ResourceResolutionServiceImpl( } else -> { val resourceDefinition = resourceDefinitions[dictionaryName] - ?: throw BlueprintProcessorException("couldn't get resource dictionary definition for $dictionaryName") + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName") val resourceSource = resourceDefinition.sources[dictionarySource] - ?: throw BlueprintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)") ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR.plus(resourceSource.type) } @@ -382,7 +382,7 @@ open class ResourceResolutionServiceImpl( // Check whether resolution already exist in the database for the specified resolution-key or resourceId/resourceType private suspend fun isNewResolution( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, properties: Map, artifactPrefix: String ): List { @@ -434,7 +434,7 @@ open class ResourceResolutionServiceImpl( resourceAssignmentList: MutableList ) { resourceResolutionList.forEach { resourceResolution -> - if (resourceResolution.status == BlueprintConstants.STATUS_SUCCESS) { + if (resourceResolution.status == BluePrintConstants.STATUS_SUCCESS) { resourceAssignmentList.forEach { if (compareOne(resourceResolution, it)) { log.info( diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSL.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSL.kt index a681b4f68..62ec2bdf4 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSL.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSL.kt @@ -18,8 +18,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType @@ -30,30 +30,30 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.PropertiesAssignmentBuil import org.onap.ccsdk.cds.controllerblueprints.core.dsl.nodeType import kotlin.reflect.KClass -fun BlueprintTypes.nodeTypeSourceInput(): NodeType { +fun BluePrintTypes.nodeTypeSourceInput(): NodeType { return nodeType( - id = "source-input", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + id = "source-input", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, description = "This is Input Resource Source Node Type" ) {} } -fun BlueprintTypes.nodeTypeSourceDefault(): NodeType { +fun BluePrintTypes.nodeTypeSourceDefault(): NodeType { return nodeType( - id = "source-default", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + id = "source-default", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, description = "This is Default Resource Source Node Type" ) {} } -fun BlueprintTypes.nodeTypeSourceDb(): NodeType { +fun BluePrintTypes.nodeTypeSourceDb(): NodeType { return nodeType( - id = "source-db", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + id = "source-db", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, description = "This is Database Resource Source Node Type" ) { property( - "type", BlueprintConstants.DATA_TYPE_STRING, + "type", BluePrintConstants.DATA_TYPE_STRING, true, "" ) { defaultValue("SQL".asJsonPrimitive()) @@ -62,42 +62,42 @@ fun BlueprintTypes.nodeTypeSourceDb(): NodeType { } } property( - "endpoint-selector", BlueprintConstants.DATA_TYPE_STRING, + "endpoint-selector", BluePrintConstants.DATA_TYPE_STRING, false, "" ) property( - "query", BlueprintConstants.DATA_TYPE_STRING, + "query", BluePrintConstants.DATA_TYPE_STRING, true, "" ) property( - "input-key-mapping", BlueprintConstants.DATA_TYPE_MAP, + "input-key-mapping", BluePrintConstants.DATA_TYPE_MAP, true, "" ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } property( - "output-key-mapping", BlueprintConstants.DATA_TYPE_MAP, + "output-key-mapping", BluePrintConstants.DATA_TYPE_MAP, false, "" ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } property( - "key-dependencies", BlueprintConstants.DATA_TYPE_LIST, + "key-dependencies", BluePrintConstants.DATA_TYPE_LIST, true, "Resource Resolution dependency dictionary names." ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } } } -fun BlueprintTypes.nodeTypeSourceRest(): NodeType { +fun BluePrintTypes.nodeTypeSourceRest(): NodeType { return nodeType( - id = "source-rest", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + id = "source-rest", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, description = "This is Rest Resource Source Node Type" ) { property( - "type", BlueprintConstants.DATA_TYPE_STRING, + "type", BluePrintConstants.DATA_TYPE_STRING, true, "" ) { defaultValue("JSON".asJsonPrimitive()) @@ -106,7 +106,7 @@ fun BlueprintTypes.nodeTypeSourceRest(): NodeType { } } property( - "verb", BlueprintConstants.DATA_TYPE_STRING, + "verb", BluePrintConstants.DATA_TYPE_STRING, true, "" ) { defaultValue("GET".asJsonPrimitive()) @@ -120,25 +120,25 @@ fun BlueprintTypes.nodeTypeSourceRest(): NodeType { } } property( - "payload", BlueprintConstants.DATA_TYPE_STRING, + "payload", BluePrintConstants.DATA_TYPE_STRING, false, "" ) { defaultValue("".asJsonPrimitive()) } property( - "endpoint-selector", BlueprintConstants.DATA_TYPE_STRING, + "endpoint-selector", BluePrintConstants.DATA_TYPE_STRING, false, "" ) property( - "url-path", BlueprintConstants.DATA_TYPE_STRING, + "url-path", BluePrintConstants.DATA_TYPE_STRING, true, "" ) property( - "path", BlueprintConstants.DATA_TYPE_STRING, + "path", BluePrintConstants.DATA_TYPE_STRING, true, "" ) property( - "expression-type", BlueprintConstants.DATA_TYPE_STRING, + "expression-type", BluePrintConstants.DATA_TYPE_STRING, false, "" ) { defaultValue("JSON_PATH".asJsonPrimitive()) @@ -147,62 +147,62 @@ fun BlueprintTypes.nodeTypeSourceRest(): NodeType { } } property( - "input-key-mapping", BlueprintConstants.DATA_TYPE_MAP, + "input-key-mapping", BluePrintConstants.DATA_TYPE_MAP, true, "" ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } property( - "output-key-mapping", BlueprintConstants.DATA_TYPE_MAP, + "output-key-mapping", BluePrintConstants.DATA_TYPE_MAP, false, "" ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } property( - "key-dependencies", BlueprintConstants.DATA_TYPE_LIST, + "key-dependencies", BluePrintConstants.DATA_TYPE_LIST, true, "Resource Resolution dependency dictionary names." ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } } } -fun BlueprintTypes.nodeTypeSourceCapability(): NodeType { +fun BluePrintTypes.nodeTypeSourceCapability(): NodeType { return nodeType( - id = "source-capability", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + id = "source-capability", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, description = "This is Component Resource Source Node Type" ) { property( - ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BlueprintConstants.DATA_TYPE_STRING, + ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING, true, "Request Id, Unique Id for the request." ) { - defaultValue(BlueprintConstants.SCRIPT_KOTLIN) + defaultValue(BluePrintConstants.SCRIPT_KOTLIN) constrain { validValues( arrayListOf( - BlueprintConstants.SCRIPT_KOTLIN.asJsonPrimitive(), - BlueprintConstants.SCRIPT_INTERNAL.asJsonPrimitive(), - BlueprintConstants.SCRIPT_JYTHON.asJsonPrimitive() + BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive(), + BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(), + BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive() ) ) } } property( - ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BlueprintConstants.DATA_TYPE_STRING, + ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING, true, "Kotlin Script class name or jython script name." ) property( - "key-dependencies", BlueprintConstants.DATA_TYPE_LIST, + "key-dependencies", BluePrintConstants.DATA_TYPE_LIST, true, "Resource Resolution dependency dictionary names." ) { - entrySchema(BlueprintConstants.DATA_TYPE_STRING) + entrySchema(BluePrintConstants.DATA_TYPE_STRING) } } } /** Node Template Source Input **/ -fun BlueprintTypes.nodeTemplateSourceInput( +fun BluePrintTypes.nodeTemplateSourceInput( id: String, description: String, block: SourceInputNodeTemplateBuilder.() -> Unit @@ -217,7 +217,7 @@ class SourceInputNodeTemplateBuilder(id: String, description: String) : ) /** Node Template Source Default **/ -fun BlueprintTypes.nodeTemplateSourceDefault( +fun BluePrintTypes.nodeTemplateSourceDefault( id: String, description: String, block: SourceDefaultNodeTemplateBuilder.() -> Unit @@ -232,7 +232,7 @@ class SourceDefaultNodeTemplateBuilder(id: String, description: String) : ) /** Node Template Source DB **/ -fun BlueprintTypes.nodeTemplateSourceDb( +fun BluePrintTypes.nodeTemplateSourceDb( id: String, description: String, block: SourceDbNodeTemplateBuilder.() -> Unit @@ -299,7 +299,7 @@ class KeyMappingBuilder() { } /** Node Template Source Rest **/ -fun BlueprintTypes.nodeTemplateSourceRest( +fun BluePrintTypes.nodeTemplateSourceRest( id: String, description: String, block: SourceRestNodeTemplateBuilder.() -> Unit @@ -378,7 +378,7 @@ class SourceRestNodeTemplateBuilder(id: String, description: String) : } /** Node Template Source Rest **/ -fun BlueprintTypes.nodeTemplateSourceCapability( +fun BluePrintTypes.nodeTemplateSourceCapability( id: String, description: String, block: SourceCapabilityNodeTemplateBuilder.() -> Unit diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapability.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapability.kt index a1f3249ab..71cf6ceea 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapability.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapability.kt @@ -20,10 +20,10 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.Reso import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.rest.restClientService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -51,7 +51,7 @@ open class IpAssignResolutionCapability : ResourceAssignmentProcessor() { /** Check Resource Assignment has the source definitions, If not get from Resource Definitions **/ val resourceSource = resourceAssignment.dictionarySourceDefinition ?: resourceDefinition?.sources?.get(dSource) - ?: throw BlueprintProcessorException("couldn't get resource definition $dName source($dSource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } @@ -81,7 +81,7 @@ open class IpAssignResolutionCapability : ResourceAssignmentProcessor() { resourceSourceProperties["resolved-payload"] = JacksonUtils.jsonNode(generatedPayload) // Get the Rest Client service, selector will be included in application.properties - val restClientService = BlueprintDependencyService.restClientService( + val restClientService = BluePrintDependencyService.restClientService( "ipassign-ms" ) @@ -100,7 +100,7 @@ open class IpAssignResolutionCapability : ResourceAssignmentProcessor() { "Failed to dictionary name ($dName), dictionary source($($dName) " + "response_code: ($responseStatusCode)" log.warn(errMsg) - throw BlueprintProcessorException(errMsg) + throw BluePrintProcessorException(errMsg) } // Parse the error Body and assign the property value } @@ -108,7 +108,7 @@ open class IpAssignResolutionCapability : ResourceAssignmentProcessor() { ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Failed in template key ($resourceAssignment) assignments with: ${e.message}", e ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapability.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapability.kt index 4f656a8f0..139d8232f 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapability.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapability.kt @@ -20,10 +20,10 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.Reso import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.rest.restClientService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.KeyIdentifier import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -51,7 +51,7 @@ open class NamingResolutionCapability : ResourceAssignmentProcessor() { /** Check Resource Assignment has the source definitions, If not get from Resource Definitions **/ val resourceSource = resourceAssignment.dictionarySourceDefinition ?: resourceDefinition?.sources?.get(dSource) - ?: throw BlueprintProcessorException("couldn't get resource definition $dName source($dSource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } @@ -82,7 +82,7 @@ open class NamingResolutionCapability : ResourceAssignmentProcessor() { resourceSourceProperties["resolved-payload"] = JacksonUtils.jsonNode(generatedPayload) // Get the Rest Client service, selector will be included in application.properties - val restClientService = BlueprintDependencyService.restClientService( + val restClientService = BluePrintDependencyService.restClientService( "naming-ms" ) @@ -102,7 +102,7 @@ open class NamingResolutionCapability : ResourceAssignmentProcessor() { "Failed to dictionary name ($dName), dictionary source($($dName) " + "response_code: ($responseStatusCode)" log.warn(errMsg) - throw BlueprintProcessorException(errMsg) + throw BluePrintProcessorException(errMsg) } // Parse the error Body and assign the property value } @@ -110,7 +110,7 @@ open class NamingResolutionCapability : ResourceAssignmentProcessor() { ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Failed in template key ($resourceAssignment) assignments with: ${e.message}", e ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBService.kt index 592408b67..5958c7899 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBService.kt @@ -18,9 +18,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -34,7 +34,7 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso private val log = LoggerFactory.getLogger(ResourceResolutionDBService::class.toString()) suspend fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, key: String, occurrence: Int, artifactPrefix: String @@ -42,8 +42,8 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso return try { val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION]!! - val blueprintName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME]!! + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!! + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!! resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResolutionKeyAndOccurrence( blueprintName, @@ -58,7 +58,7 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso } suspend fun findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceId: String, resourceType: String, occurrence: Int, @@ -68,8 +68,8 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION]!! - val blueprintName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME]!! + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!! + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!! resourceResolutionRepository.findByBlueprintNameAndBlueprintVersionAndArtifactNameAndResourceIdAndResourceTypeAndOccurrence( blueprintName, @@ -134,15 +134,15 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso suspend fun write( properties: Map, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactPrefix: String, resourceAssignment: ResourceAssignment ): ResourceResolution = withContext(Dispatchers.IO) { val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION]!! - val blueprintName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME]!! + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!! + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!! val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String @@ -182,7 +182,7 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso resourceResolution.resourceType = resourceType resourceResolution.resourceId = resourceId resourceResolution.value = resourceAssignment.property?.value?.let { - if (BlueprintConstants.STATUS_SUCCESS == resourceAssignment.status) + if (BluePrintConstants.STATUS_SUCCESS == resourceAssignment.status) JacksonUtils.getValue(it).toString() else "" } ?: "" @@ -190,12 +190,12 @@ class ResourceResolutionDBService(private val resourceResolutionRepository: Reso resourceResolution.dictionaryName = resourceAssignment.dictionaryName resourceResolution.dictionaryVersion = resourceAssignment.version resourceResolution.dictionarySource = resourceAssignment.dictionarySource - resourceResolution.status = resourceAssignment.status ?: BlueprintConstants.STATUS_FAILURE + resourceResolution.status = resourceAssignment.status ?: BluePrintConstants.STATUS_FAILURE try { resourceResolutionRepository.saveAndFlush(resourceResolution) } catch (ex: Exception) { - throw BlueprintException("Failed to store resource resolution result.", ex) + throw BluePrintException("Failed to store resource resolution result.", ex) } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionService.kt index cbd8b8310..4bdd5d985 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionService.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionService.kt @@ -18,9 +18,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.slf4j.LoggerFactory import org.springframework.dao.DataIntegrityViolationException import org.springframework.dao.EmptyResultDataAccessException @@ -33,7 +33,7 @@ class TemplateResolutionService(private val templateResolutionRepository: Templa private val log = LoggerFactory.getLogger(TemplateResolutionService::class.toString()) suspend fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactPrefix: String, resolutionKey: String ): String = @@ -41,8 +41,8 @@ class TemplateResolutionService(private val templateResolutionRepository: Templa val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION]!! - val blueprintName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME]!! + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!! + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!! findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName( blueprintName, @@ -93,14 +93,14 @@ class TemplateResolutionService(private val templateResolutionRepository: Templa suspend fun write( properties: Map, result: String, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactPrefix: String ): TemplateResolution = withContext(Dispatchers.IO) { val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - val blueprintVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION]!! - val blueprintName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME]!! + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION]!! + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME]!! val resolutionKey = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] as String val resourceId = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] as String val resourceType = properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_TYPE] as String @@ -187,7 +187,7 @@ class TemplateResolutionService(private val templateResolutionRepository: Templa " (resourceId: $resourceId resourceType: $resourceType) occurrence:$occurrence error: {}", ex.message ) - throw BlueprintException("Failed to store resource api result.", ex) + throw BluePrintException("Failed to store resource api result.", ex) } } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt index 5e834d73d..9f318a314 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt @@ -22,7 +22,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.Capa import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -53,7 +53,7 @@ open class CapabilityResourceResolutionProcessor(private var componentFunctionSc /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/ val resourceSource = resourceAssignment.dictionarySourceDefinition ?: resourceDefinition?.sources?.get(dSource) - ?: throw BlueprintProcessorException("couldn't get resource definition $dName source($dSource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") val resourceSourceProps = checkNotNull(resourceSource.properties) { "failed to get $resourceSource properties" } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt index db5307f17..c8bef5200 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt @@ -17,14 +17,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDBLibGenericService -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BlueprintDBLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty @@ -47,7 +47,7 @@ import java.util.HashMap @Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-db") @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) open class DatabaseResourceAssignmentProcessor( - private val bluePrintDBLibPropertyService: BlueprintDBLibPropertyService, + private val bluePrintDBLibPropertyService: BluePrintDBLibPropertyService, private val primaryDBLibGenericService: PrimaryDBLibGenericService ) : ResourceAssignmentProcessor() { @@ -66,7 +66,7 @@ open class DatabaseResourceAssignmentProcessor( } // Check the value has populated for mandatory case ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { val errorMsg = "Failed to process Database resource resolution in template key ($resourceAssignment) assignments." throw e.updateErrorMessage( ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg, @@ -74,7 +74,7 @@ open class DatabaseResourceAssignmentProcessor( ) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) } } @@ -86,7 +86,7 @@ open class DatabaseResourceAssignmentProcessor( /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/ val resourceSource = resourceAssignment.dictionarySourceDefinition ?: resourceDefinition?.sources?.get(dSource) - ?: throw BlueprintProcessorException("couldn't get resource definition $dName source($dSource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } @@ -119,7 +119,7 @@ open class DatabaseResourceAssignmentProcessor( } } - private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BlueprintDBLibGenericService { + private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource, selector: String): BluePrintDBLibGenericService { return if (isNotEmpty(sourceProperties.endpointSelector)) { val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!) bluePrintDBLibPropertyService.JdbcTemplate(dbPropertiesJson) @@ -128,7 +128,7 @@ open class DatabaseResourceAssignmentProcessor( } } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) private fun validate(resourceAssignment: ResourceAssignment) { checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" } checkNotEmpty(resourceAssignment.dictionaryName) { @@ -156,7 +156,7 @@ open class DatabaseResourceAssignmentProcessor( return namedParameters } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) private fun populateResource( resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt index e904ebcb4..9e5bd08cd 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt @@ -20,7 +20,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.pro import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ExecutionServiceDomains -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -51,7 +51,7 @@ open class DefaultResourceResolutionProcessor : ResourceAssignmentProcessor() { } // Check the value has populated for mandatory case ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { val errorMsg = "Failed to process default resource resolution in template key ($resourceAssignment) assignments." throw e.updateErrorMessage( ExecutionServiceDomains.RESOURCE_RESOLUTION, errorMsg, @@ -59,7 +59,7 @@ open class DefaultResourceResolutionProcessor : ResourceAssignmentProcessor() { ) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt index c3add86fd..caf6b6acb 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt @@ -20,7 +20,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.pro import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -52,13 +52,13 @@ open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() { } // Check the value has populated for mandatory case ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { val errorMsg = "Failed to process input resource resolution in template key ($resourceAssignment) assignments." ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) logger.error(errorMsg) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException("Failed in template key ($resourceAssignment) assignments with : (${e.message})", e) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with : (${e.message})", e) } } @@ -71,7 +71,7 @@ open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() { /** Check Resource Assignment has the source definitions, If not get from Resource Definition **/ val resourceSource = resourceAssignment.dictionarySourceDefinition ?: resourceDefinition?.sources?.get(dSource) - ?: throw BlueprintProcessorException("couldn't get resource definition $dName source($dSource)") + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") try { val resourceSourceProperties = checkNotNull(resourceSource.properties) { @@ -86,7 +86,7 @@ open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() { // keyDependency = service-instance.service-instance-id setFromInputKeyDependencies(keyDependency, resourceAssignment); // New API which picks attribute from Input } catch (e: IllegalStateException) { - throw BlueprintProcessorException(e) + throw BluePrintProcessorException(e) } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt index ce00ac17b..c075e1b4d 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt @@ -22,13 +22,13 @@ import com.fasterxml.jackson.databind.JsonNode import org.apache.commons.collections.MapUtils import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.slf4j.LoggerFactory @@ -50,7 +50,7 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode scriptPropertyInstanceType(name: String): T { return scriptPropertyInstances as? T - ?: throw BlueprintProcessorException("couldn't get script property instance ($name)") + ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") } open fun setFromInput(resourceAssignment: ResourceAssignment): Boolean { @@ -64,7 +64,7 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode { + BluePrintConstants.SCRIPT_JYTHON -> { executeScriptBlocking(resourceAssignment) } else -> { @@ -163,39 +163,39 @@ abstract class ResourceAssignmentProcessor : BlueprintFunctionNode> outputKeyMapping==null, will not populateResource") } else if (responseStatusCode in 200..299 && !responseBody.isBlank()) { populateResource(resourceAssignment, sourceProperties, responseBody, path) @@ -112,12 +112,12 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)" logger.warn(errMsg) - throw BlueprintProcessorException(errMsg) + throw BluePrintProcessorException(errMsg) } } // Check the value has populated for mandatory case ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { val errorMsg = "Failed to process REST resource resolution in template key ($resourceAssignment) assignments." ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, errorMsg) throw e.updateErrorMessage( @@ -126,7 +126,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS ) } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BlueprintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) } } @@ -142,7 +142,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS } } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) private fun populateResource( resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, @@ -175,7 +175,7 @@ open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyS ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, parsedResponseNode) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) private fun validate(resourceAssignment: ResourceAssignment) { checkNotEmpty(resourceAssignment.name) { "resource assignment template key is not defined" } checkNotEmpty(resourceAssignment.dictionaryName) { diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt index 5a03450ed..7ab3126bb 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt @@ -26,9 +26,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.databind.node.TextNode import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty @@ -39,8 +39,8 @@ import org.onap.ccsdk.cds.controllerblueprints.core.isNullOrMissing import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect @@ -59,14 +59,14 @@ class ResourceAssignmentUtils { suspend fun resourceDefinitions(blueprintBasePath: String): MutableMap { val dictionaryFile = normalizedFile( - blueprintBasePath, BlueprintConstants.TOSCA_DEFINITIONS_DIR, + blueprintBasePath, BluePrintConstants.TOSCA_DEFINITIONS_DIR, ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES ) checkFileExists(dictionaryFile) { "resource definition file(${dictionaryFile.absolutePath}) is missing" } return JacksonReactorUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun setResourceDataValue( resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, @@ -76,7 +76,7 @@ class ResourceAssignmentUtils { return setResourceDataValue(resourceAssignment, raRuntimeService, value.asJsonType()) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun setResourceDataValue( resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, @@ -108,11 +108,11 @@ class ResourceAssignmentUtils { ) setResourceValue(resourceAssignment, raRuntimeService, value) resourceAssignment.updatedDate = Date() - resourceAssignment.updatedBy = BlueprintConstants.USER_SYSTEM - resourceAssignment.status = BlueprintConstants.STATUS_SUCCESS + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS } } catch (e: Exception) { - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Failed in setting value for template key " + "(${resourceAssignment.name}) and dictionary key (${resourceAssignment.dictionaryName}) of " + "type (${resourceProp.type}) with error message (${e.message})", @@ -139,7 +139,7 @@ class ResourceAssignmentUtils { .mapValues { e -> e.value.asText() } as MutableMap val newValue: JsonNode try { - newValue = BlueprintVelocityTemplateService + newValue = BluePrintVelocityTemplateService .generateContent(template, null, true, resolutionStore) .also { if (hasLogProtect(metadata)) @@ -149,7 +149,7 @@ class ResourceAssignmentUtils { } .let { v -> v.asJsonType() } } catch (e: Exception) { - throw BlueprintProcessorException( + throw BluePrintProcessorException( "transform-template failed: $template", e ) } @@ -164,24 +164,24 @@ class ResourceAssignmentUtils { fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) { if (isNotEmpty(resourceAssignment.name)) { resourceAssignment.updatedDate = Date() - resourceAssignment.updatedBy = BlueprintConstants.USER_SYSTEM - resourceAssignment.status = BlueprintConstants.STATUS_FAILURE + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_FAILURE resourceAssignment.message = message } } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) { val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" } if (resourceProp.required != null && resourceProp.required!! && resourceProp.value.isNullOrMissing()) { logger.error("failed to populate mandatory resource mapping ($resourceAssignment)") - throw BlueprintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)") + throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)") } } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun generateResourceDataForAssignments(assignments: List): String { val result: String try { @@ -209,13 +209,13 @@ class ResourceAssignmentUtils { logger.info("Generated Resource Param Data ($result)") } } catch (e: Exception) { - throw BlueprintProcessorException("Resource Assignment is failed with $e.message", e) + throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e) } return result } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun generateResourceForAssignments(assignments: List): MutableMap { val data: MutableMap = hashMapOf() assignments.forEach { @@ -291,7 +291,7 @@ class ResourceAssignmentUtils { } fun transformToRARuntimeService( - blueprintRuntimeService: BlueprintRuntimeService<*>, + blueprintRuntimeService: BluePrintRuntimeService<*>, templateArtifactName: String ): ResourceAssignmentRuntimeService { @@ -305,7 +305,7 @@ class ResourceAssignmentUtils { return resourceAssignmentRuntimeService } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun getPropertyType( raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String, @@ -321,12 +321,12 @@ class ResourceAssignmentUtils { logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type) } catch (e: Exception) { logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e") - throw BlueprintProcessorException("${e.message}", e) + throw BluePrintProcessorException("${e.message}", e) } return type } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun parseResponseNode( responseNode: JsonNode, resourceAssignment: ResourceAssignment, @@ -336,18 +336,18 @@ class ResourceAssignmentUtils { val metadata = resourceAssignment.property!!.metadata try { if ((resourceAssignment.property?.type).isNullOrEmpty()) { - throw BlueprintProcessorException("Couldn't get data dictionary type for dictionary name (${resourceAssignment.name})") + throw BluePrintProcessorException("Couldn't get data dictionary type for dictionary name (${resourceAssignment.name})") } val type = resourceAssignment.property!!.type val valueToPrint = getValueToLog(metadata, responseNode) logger.info("For template key (${resourceAssignment.name}) trying to get value from responseNode ($valueToPrint)") return when (type) { - in BlueprintTypes.validPrimitiveTypes() -> { + in BluePrintTypes.validPrimitiveTypes() -> { // Primitive Types parseResponseNodeForPrimitiveTypes(responseNode, resourceAssignment, outputKeyMapping) } - in BlueprintTypes.validCollectionTypes() -> { + in BluePrintTypes.validCollectionTypes() -> { // Array Types parseResponseNodeForCollection(responseNode, resourceAssignment, raRuntimeService, outputKeyMapping) } @@ -358,7 +358,7 @@ class ResourceAssignmentUtils { } } catch (e: Exception) { logger.error("Fail to parse response data, error message $e") - throw BlueprintProcessorException("${e.message}", e) + throw BluePrintProcessorException("${e.message}", e) } } @@ -387,7 +387,7 @@ class ResourceAssignmentUtils { } if (returnNode.isNullOrMissing() || returnNode!!.isComplexType() && !returnNode.has(outputKeyMapping[outputKey])) { - throw BlueprintProcessorException("Fail to find output key mapping ($outputKey) in the responseNode.") + throw BluePrintProcessorException("Fail to find output key mapping ($outputKey) in the responseNode.") } val returnValue = if (returnNode.isComplexType()) { @@ -411,7 +411,7 @@ class ResourceAssignmentUtils { val metadata = resourceAssignment.property!!.metadata var resultNode: JsonNode if ((resourceAssignment.property?.entrySchema?.type).isNullOrEmpty()) { - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Couldn't get data type for dictionary type " + "(${resourceAssignment.property!!.type}) and dictionary name ($dName)" ) @@ -441,7 +441,7 @@ class ResourceAssignmentUtils { ) } else -> { - throw BlueprintProcessorException("Key-value response expected to match the responseNode.") + throw BluePrintProcessorException("Key-value response expected to match the responseNode.") } } } else { @@ -486,7 +486,7 @@ class ResourceAssignmentUtils { ): ObjectNode { val outputKeyMappingHasOnlyOneElement = checkIfOutputKeyMappingProvideOneElement(outputKeyMapping) when (entrySchemaType) { - in BlueprintTypes.validPrimitiveTypes() -> { + in BluePrintTypes.validPrimitiveTypes() -> { if (outputKeyMappingHasOnlyOneElement) { val outputKeyMap = outputKeyMapping.entries.first() if (resourceAssignment.keyIdentifiers.none { it.name == outputKeyMap.key }) { @@ -503,7 +503,7 @@ class ResourceAssignmentUtils { metadata ) } else { - throw BlueprintProcessorException("Expect one entry in output-key-mapping") + throw BluePrintProcessorException("Expect one entry in output-key-mapping") } } else -> { @@ -533,7 +533,7 @@ class ResourceAssignmentUtils { ) } else -> { - throw BlueprintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") + throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") } } } @@ -557,7 +557,7 @@ class ResourceAssignmentUtils { resourceAssignment.keyIdentifiers.add(KeyIdentifier(outputKeyMap.key, returnValue)) return returnValue } else { - throw BlueprintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") + throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") } } @@ -669,7 +669,7 @@ class ResourceAssignmentUtils { ) } else -> { - throw BlueprintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") + throw BluePrintProcessorException("Output-key-mapping do not map the Data Type $entrySchemaType") } } } else { diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceDefinitionUtils.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceDefinitionUtils.kt index 4b4e04e16..1bf854cbd 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceDefinitionUtils.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceDefinitionUtils.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition @@ -48,7 +48,7 @@ object ResourceDefinitionUtils { MutableList { /** Check if resolve definition is defined in the resource definition Map */ val resourceDefinition = resourceDefinitions[resolveDefinition] - ?: throw BlueprintProcessorException("failed to get resolve definition($resolveDefinition)") + ?: throw BluePrintProcessorException("failed to get resolve definition($resolveDefinition)") val resourceAssignments: MutableList = arrayListOf() @@ -56,7 +56,7 @@ object ResourceDefinitionUtils { val definitionDependencies = definitionDependencies(resourceDefinition, sources) definitionDependencies.forEach { definitionDependencyName -> val definitionDependency = resourceDefinitions[definitionDependencyName] - ?: throw BlueprintProcessorException("failed to get dependency definition($definitionDependencyName)") + ?: throw BluePrintProcessorException("failed to get dependency definition($definitionDependencyName)") val resourceAssignment = ResourceAssignment().apply { name = definitionDependency.name diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSLTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSLTest.kt index bdb47e711..7dcaab733 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSLTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceDefinitionDSLTest.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -25,7 +25,7 @@ class ResourceDefinitionDSLTest { @Test fun testResourceDefinitionDSL() { - val testResourceDefinition = BlueprintTypes.resourceDefinition( + val testResourceDefinition = BluePrintTypes.resourceDefinition( "service-instance-id", "VFW Service Instance Name" ) { @@ -79,7 +79,7 @@ class ResourceDefinitionDSLTest { // println(resourceDefinition.asJsonString(true)) assertNotNull(testResourceDefinition, "failed to generate testResourceDefinition") - val testResourceDefinitions = BlueprintTypes.resourceDefinitions { + val testResourceDefinitions = BluePrintTypes.resourceDefinitions { resourceDefinition(testResourceDefinition) } assertNotNull(testResourceDefinitions, "failed to generate testResourceDefinitions") @@ -88,7 +88,7 @@ class ResourceDefinitionDSLTest { @Test fun testResourceAssignment() { - val testResourceAssignment = BlueprintTypes.resourceAssignment( + val testResourceAssignment = BluePrintTypes.resourceAssignment( "instance-name", "service-instance-name", "odl-mdsal" ) { @@ -99,7 +99,7 @@ class ResourceDefinitionDSLTest { // println(resourceAssignment.asJsonString(true)) assertNotNull(testResourceAssignment, "failed to generate resourceAssignment") - val testResourceAssignments = BlueprintTypes.resourceAssignments { + val testResourceAssignments = BluePrintTypes.resourceAssignments { resourceAssignment(testResourceAssignment) resourceAssignment( "instance-name1", diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSLTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSLTest.kt index 09eef46d4..f7c41bdac 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSLTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentDSLTest.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getAttribute import kotlin.test.Test import kotlin.test.assertNotNull @@ -25,14 +25,14 @@ class ResourceResolutionComponentDSLTest { @Test fun testNodeTypeComponentResourceResolution() { - val nodeType = BlueprintTypes.nodeTypeComponentResourceResolution() + val nodeType = BluePrintTypes.nodeTypeComponentResourceResolution() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeComponentResourceResolution") } @Test fun testNodeTemplateComponentResourceResolution() { - val nodeTemplate = BlueprintTypes.nodeTemplateComponentResourceResolution("resource-resolve", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateComponentResourceResolution("resource-resolve", "") { definedOperation("Resolve resources") { inputs { actionName("resolve") diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt index 74a88b4e3..84d132a55 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt @@ -26,10 +26,10 @@ import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import kotlin.test.assertEquals import kotlin.test.fail @@ -44,7 +44,7 @@ class ResourceResolutionComponentTest { private val resourceType = "ServiceInstance" private val occurrence = 1 private val props = mutableMapOf() - private val bluePrintRuntimeService = mockk>() + private val bluePrintRuntimeService = mockk>() private val artifactNames = listOf("template") private val nodeTemplateName = "nodeTemplateName" @@ -79,7 +79,7 @@ class ResourceResolutionComponentTest { runBlocking { try { resourceResolutionComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { assertEquals( "Can't proceed with the resolution: either provide resolution-key OR combination of resource-id and resource-type.", e.message @@ -98,7 +98,7 @@ class ResourceResolutionComponentTest { runBlocking { try { resourceResolutionComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { assertEquals( "Can't proceed with the resolution: both resource-id and resource-type should be provided, one of them is missing.", e.message @@ -118,7 +118,7 @@ class ResourceResolutionComponentTest { runBlocking { try { resourceResolutionComponent.processNB(executionRequest) - } catch (e: BlueprintProcessorException) { + } catch (e: BluePrintProcessorException) { assertEquals( "Can't proceed with the resolution: can't persist resolution without a correlation key. " + "Either provide a resolution-key OR combination of resource-id and resource-type OR set `storeResult` to false.", @@ -164,9 +164,9 @@ class ResourceResolutionComponentTest { @Test fun testRecover() { runBlocking { - val blueprintError = BlueprintError() + val blueprintError = BluePrintError() val exception = RuntimeException("message") - every { bluePrintRuntimeService.getBlueprintError() } returns blueprintError + every { bluePrintRuntimeService.getBluePrintError() } returns blueprintError resourceResolutionComponent.recoverNB(exception, executionRequest) assertEquals(1, blueprintError.allErrors().size) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt index a1de557d5..3d2a9755c 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt @@ -30,11 +30,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.MockCapabilityScriptRA import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResolutionSummary import org.slf4j.LoggerFactory @@ -106,7 +106,7 @@ class ResourceResolutionServiceTest { Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -160,7 +160,7 @@ class ResourceResolutionServiceTest { runBlocking { Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -200,7 +200,7 @@ class ResourceResolutionServiceTest { runBlocking { Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -245,7 +245,7 @@ class ResourceResolutionServiceTest { props[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_SUMMARY] = true Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -291,7 +291,7 @@ class ResourceResolutionServiceTest { runBlocking { Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -344,7 +344,7 @@ class ResourceResolutionServiceTest { runBlocking { Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -384,13 +384,13 @@ class ResourceResolutionServiceTest { @Test fun testResourceResolutionForDefinition() { - val resourceDefinitions = BlueprintTypes.resourceDefinitions { + val resourceDefinitions = BluePrintTypes.resourceDefinitions { resourceDefinition(name = "port-speed", description = "Port Speed") { property(type = "string", required = true) sources { sourceCapability(id = "sdno", description = "SDNO Source") { definedProperties { - type(BlueprintConstants.SCRIPT_KOTLIN) + type(BluePrintConstants.SCRIPT_KOTLIN) scriptClassReference(MockCapabilityScriptRA::class.qualifiedName!!) keyDependencies(arrayListOf("device-id")) } @@ -417,9 +417,9 @@ class ResourceResolutionServiceTest { } runBlocking { val raRuntimeService = mockk() - every { raRuntimeService.bluePrintContext() } returns mockk() - every { raRuntimeService.getBlueprintError() } returns BlueprintError() - every { raRuntimeService.setBlueprintError(any()) } returns Unit + every { raRuntimeService.bluePrintContext() } returns mockk() + every { raRuntimeService.getBluePrintError() } returns BluePrintError() + every { raRuntimeService.setBluePrintError(any()) } returns Unit every { raRuntimeService.getInputValue("device-id") } returns "123456".asJsonPrimitive() every { raRuntimeService.putResolutionStore(any(), any()) } returns Unit diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSLTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSLTest.kt index 1dff814ac..2e9dc9e2a 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSLTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceDSLTest.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import kotlin.test.Test import kotlin.test.assertNotNull @@ -24,42 +24,42 @@ class ResourceSourceDSLTest { @Test fun testNodeTypeSourceInput() { - val nodeType = BlueprintTypes.nodeTypeSourceInput() + val nodeType = BluePrintTypes.nodeTypeSourceInput() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeSourceInput") } @Test fun testNodeTypeSourceDefault() { - val nodeType = BlueprintTypes.nodeTypeSourceDefault() + val nodeType = BluePrintTypes.nodeTypeSourceDefault() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeSourceDefault") } @Test fun testNodeTypeSourceDb() { - val nodeType = BlueprintTypes.nodeTypeSourceDb() + val nodeType = BluePrintTypes.nodeTypeSourceDb() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeSourceDb") } @Test fun testNodeTypeSourceRest() { - val nodeType = BlueprintTypes.nodeTypeSourceRest() + val nodeType = BluePrintTypes.nodeTypeSourceRest() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeSourceRest") } @Test fun testNodeTypeSourceCapability() { - val nodeType = BlueprintTypes.nodeTypeSourceCapability() + val nodeType = BluePrintTypes.nodeTypeSourceCapability() // println(nodeType.asJsonString(true)) assertNotNull(nodeType, "failed to generate nodeTypeSourceCapability") } @Test fun testNodeTemplateSourceInput() { - val nodeTemplate = BlueprintTypes.nodeTemplateSourceInput("InputSystem", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateSourceInput("InputSystem", "") { } // println(nodeTemplate.asJsonString(true)) assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceInput") @@ -67,7 +67,7 @@ class ResourceSourceDSLTest { @Test fun testNodeTemplateSourceDefault() { - val nodeTemplate = BlueprintTypes.nodeTemplateSourceDefault("DefaultSystem", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateSourceDefault("DefaultSystem", "") { } // println(nodeTemplate.asJsonString(true)) assertNotNull(nodeTemplate, "failed to generate nodeTemplateSourceDefault") @@ -75,7 +75,7 @@ class ResourceSourceDSLTest { @Test fun testNodeTemplateSourceDb() { - val nodeTemplate = BlueprintTypes.nodeTemplateSourceDb("DbSystem", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateSourceDb("DbSystem", "") { definedProperties { type("SQL") query("SELECT * FROM DB WHERE name = \$name") @@ -95,7 +95,7 @@ class ResourceSourceDSLTest { @Test fun testNodeTemplateSourceRest() { - val nodeTemplate = BlueprintTypes.nodeTemplateSourceRest("restSystem", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateSourceRest("restSystem", "") { definedProperties { type("JSON") endpointSelector("rest-source-endpoint") @@ -119,7 +119,7 @@ class ResourceSourceDSLTest { @Test fun testNodeTemplateSourceCapability() { - val nodeTemplate = BlueprintTypes.nodeTemplateSourceCapability("capabiltySystem", "") { + val nodeTemplate = BluePrintTypes.nodeTemplateSourceCapability("capabiltySystem", "") { definedProperties { type("kotlin") scriptClassReference("Scripts/Sample.kt") diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/TestDatabaseConfiguration.kt index d720bd836..096d7ff27 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution", diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapabilityTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapabilityTest.kt index e48ac388d..4ce5df18f 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapabilityTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/IpAssignResolutionCapabilityTest.kt @@ -29,14 +29,14 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.proc import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceAssignments import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceDefinitions import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResolutionSummary import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -57,7 +57,7 @@ class IpAssignResolutionCapabilityTest { @Before fun setup() { - mockkObject(BlueprintDependencyService) + mockkObject(BluePrintDependencyService) val blueprintWebClientService = mockk() // Create mock Response @@ -72,9 +72,9 @@ class IpAssignResolutionCapabilityTest { ) every { blueprintWebClientService.exchangeResource(any(), any(), any()) } returns mockResponse - val restLibPropertyService = mockk() + val restLibPropertyService = mockk() every { restLibPropertyService.blueprintWebClientService("ipassign-ms") } returns blueprintWebClientService - every { BlueprintDependencyService.applicationContext.getBean(any()) } returns restLibPropertyService + every { BluePrintDependencyService.applicationContext.getBean(any()) } returns restLibPropertyService } @Test @@ -152,7 +152,7 @@ class IpAssignResolutionCapabilityTest { /** Test dictionaries */ private fun resourceDefinitions(): MutableMap { - return BlueprintTypes.resourceDefinitions { + return BluePrintTypes.resourceDefinitions { resourceDefinition("CloudRegionId", "Cloud Region Id Resource Definition") { tags("CloudRegionId") updatedBy("saurav.paira@att.com") @@ -230,7 +230,7 @@ class IpAssignResolutionCapabilityTest { } private fun resourceAssignments(): MutableMap { - return BlueprintTypes.resourceAssignments { + return BluePrintTypes.resourceAssignments { resourceAssignment( name = "CloudRegionId", dictionaryName = "CloudRegionId", dictionarySource = "input" diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapabilityTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapabilityTest.kt index 66f302f6f..8c0aca49e 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapabilityTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/capabilities/NamingResolutionCapabilityTest.kt @@ -29,16 +29,16 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.proc import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceAssignments import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceDefinitions import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResolutionSummary import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -60,7 +60,7 @@ class NamingResolutionCapabilityTest { @Before fun setup() { - mockkObject(BlueprintDependencyService) + mockkObject(BluePrintDependencyService) val blueprintWebClientService = mockk() // Create mock Response @@ -74,9 +74,9 @@ class NamingResolutionCapabilityTest { ) every { blueprintWebClientService.exchangeResource(any(), any(), any()) } returns mockResponse - val restLibPropertyService = mockk() + val restLibPropertyService = mockk() every { restLibPropertyService.blueprintWebClientService("naming-ms") } returns blueprintWebClientService - every { BlueprintDependencyService.applicationContext.getBean(any()) } returns restLibPropertyService + every { BluePrintDependencyService.applicationContext.getBean(any()) } returns restLibPropertyService } @Test @@ -89,8 +89,8 @@ class NamingResolutionCapabilityTest { } returns NamingResolutionCapability() val raRuntimeService = mockk() - every { raRuntimeService.getBlueprintError() } returns BlueprintError() - every { raRuntimeService.bluePrintContext() } returns mockk() + every { raRuntimeService.getBluePrintError() } returns BluePrintError() + every { raRuntimeService.bluePrintContext() } returns mockk() every { raRuntimeService.getInputValue("vf-module-name") } returns NullNode.getInstance() every { raRuntimeService.getInputValue("vnfc-name") } returns NullNode.getInstance() @@ -154,7 +154,7 @@ class NamingResolutionCapabilityTest { /** Test dictionaries */ private fun resourceDefinitions(): MutableMap { - return BlueprintTypes.resourceDefinitions { + return BluePrintTypes.resourceDefinitions { resourceDefinition("naming-code", "naming-code Resource Definition") { tags("naming-code") updatedBy("brindasanth@onap.com") @@ -274,7 +274,7 @@ class NamingResolutionCapabilityTest { } private fun resourceAssignments(): MutableMap { - return BlueprintTypes.resourceAssignments { + return BluePrintTypes.resourceAssignments { resourceAssignment( name = "naming-code", dictionaryName = "naming-code", dictionarySource = "input" diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBServiceTest.kt index 51825a5f9..fa59876a9 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBServiceTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionDBServiceTest.kt @@ -23,10 +23,10 @@ import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.springframework.dao.EmptyResultDataAccessException import kotlin.test.assertEquals @@ -46,13 +46,13 @@ open class ResourceResolutionDBServiceTest { private val blueprintVersion = "1.0.0" private val metadata = hashMapOf() private val props = hashMapOf() - private val bluePrintContext = mockk() - private val bluePrintRuntimeService = mockk() + private val bluePrintContext = mockk() + private val bluePrintRuntimeService = mockk() @Before fun setup() { - metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] = blueprintVersion - metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] = blueprintName + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = blueprintVersion + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = blueprintName props[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = resolutionKey props[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = resourceId @@ -206,7 +206,7 @@ open class ResourceResolutionDBServiceTest { fun writeTest() { val resourceResolution = ResourceResolution() val resourceAssignment = ResourceAssignment() - resourceAssignment.property?.status = BlueprintConstants.STATUS_SUCCESS + resourceAssignment.property?.status = BluePrintConstants.STATUS_SUCCESS resourceAssignment.property?.value = "result".asJsonPrimitive() resourceAssignment.dictionarySource = "ddSource" resourceAssignment.dictionaryName = "ddName" @@ -229,7 +229,7 @@ open class ResourceResolutionDBServiceTest { fun writeWithNullValue() { val slot = slot() val resourceAssignment = ResourceAssignment() - resourceAssignment.status = BlueprintConstants.STATUS_SUCCESS + resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS resourceAssignment.dictionarySource = "ddSource" resourceAssignment.dictionaryName = "ddName" resourceAssignment.version = 1 diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionServiceTest.kt index 0a7722f53..71d895574 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionServiceTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/TemplateResolutionServiceTest.kt @@ -7,9 +7,9 @@ import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.springframework.dao.EmptyResultDataAccessException import kotlin.test.assertEquals @@ -29,13 +29,13 @@ class TemplateResolutionServiceTest { private val result = "result" private val metadata = hashMapOf() private val props = hashMapOf() - private val bluePrintContext = mockk() - private val bluePrintRuntimeService = mockk() + private val bluePrintContext = mockk() + private val bluePrintRuntimeService = mockk() @Before fun setup() { - metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] = blueprintVersion - metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] = blueprintName + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = blueprintVersion + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = blueprintName props[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOLUTION_KEY] = resolutionKey props[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_RESOURCE_ID] = resourceId diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBluePrintRestLibPropertyService.kt new file mode 100644 index 000000000..a2ec75d02 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBluePrintRestLibPropertyService.kt @@ -0,0 +1,36 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock + +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService + +class MockBluePrintRestLibPropertyService(bluePrintProperties: BluePrintPropertiesService) : + BluePrintRestLibPropertyService(bluePrintProperties) { + + fun mockBlueprintWebClientService(selector: String): + MockBlueprintWebClientService { + val prefix = "blueprintsprocessor.restclient.$selector" + val restClientProperties = restClientProperties(prefix) + return mockBlueprintWebClientService(restClientProperties) + } + + private fun mockBlueprintWebClientService(restClientProperties: RestClientProperties): + MockBlueprintWebClientService { + return MockBlueprintWebClientService(restClientProperties) + } +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBlueprintRestLibPropertyService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBlueprintRestLibPropertyService.kt deleted file mode 100644 index b6c20cd5a..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockBlueprintRestLibPropertyService.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock - -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService - -class MockBlueprintRestLibPropertyService(bluePrintProperties: BlueprintPropertiesService) : - BlueprintRestLibPropertyService(bluePrintProperties) { - - fun mockBlueprintWebClientService(selector: String): - MockBlueprintWebClientService { - val prefix = "blueprintsprocessor.restclient.$selector" - val restClientProperties = restClientProperties(prefix) - return mockBlueprintWebClientService(restClientProperties) - } - - private fun mockBlueprintWebClientService(restClientProperties: RestClientProperties): - MockBlueprintWebClientService { - return MockBlueprintWebClientService(restClientProperties) - } -} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockDatabaseConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockDatabaseConfiguration.kt index 653a2c1f4..2219f2348 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockDatabaseConfiguration.kt @@ -17,9 +17,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.moc import io.mockk.coEvery import io.mockk.mockk -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @@ -27,8 +27,8 @@ import org.springframework.context.annotation.Configuration open class MockDBLibGenericService { @Bean(name = ["MariaDatabaseConfiguration", "MySqlDatabaseConfiguration"]) - open fun createDatabaseConfiguration(): BlueprintDBLibGenericService { - return mockk() + open fun createDatabaseConfiguration(): BluePrintDBLibGenericService { + return mockk() } } @@ -36,10 +36,10 @@ open class MockDBLibGenericService { open class MockBlueprintProcessorCatalogServiceImpl { @Bean(name = ["bluePrintRuntimeValidatorService"]) - open fun bluePrintRuntimeValidatorService(): BlueprintValidatorService { - val bluePrintValidatorService = mockk() - coEvery { bluePrintValidatorService.validateBlueprints(any()) } returns true - coEvery { bluePrintValidatorService.validateBlueprints(any>()) } returns true + open fun bluePrintRuntimeValidatorService(): BluePrintValidatorService { + val bluePrintValidatorService = mockk() + coEvery { bluePrintValidatorService.validateBluePrints(any()) } returns true + coEvery { bluePrintValidatorService.validateBluePrints(any>()) } returns true return bluePrintValidatorService } } diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt index 77c90ba51..69099152e 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt @@ -22,8 +22,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.Reso import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -33,7 +33,7 @@ import java.util.HashMap class MockRestResourceResolutionProcessor( private val blueprintRestLibPropertyService: - MockBlueprintRestLibPropertyService + MockBluePrintRestLibPropertyService ) : ResourceAssignmentProcessor() { private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java) @@ -97,12 +97,12 @@ class MockRestResourceResolutionProcessor( val errMsg = "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)" logger.warn(errMsg) - throw BlueprintProcessorException(errMsg) + throw BluePrintProcessorException(errMsg) } } } catch (e: Exception) { ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message) - throw BlueprintProcessorException( + throw BluePrintProcessorException( "Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}", e ) @@ -117,7 +117,7 @@ class MockRestResourceResolutionProcessor( return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) private fun populateResource( resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, @@ -132,15 +132,15 @@ class MockRestResourceResolutionProcessor( val responseNode = JacksonUtils.jsonNode(restResponse).at(path) when (type) { - in BlueprintTypes.validPrimitiveTypes() -> { + in BluePrintTypes.validPrimitiveTypes() -> { ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode) } - in BlueprintTypes.validCollectionTypes() -> { + in BluePrintTypes.validCollectionTypes() -> { // Array Types entrySchemaType = resourceAssignment.property!!.entrySchema!!.type val arrayNode = responseNode as ArrayNode - if (entrySchemaType !in BlueprintTypes.validPrimitiveTypes()) { + if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) { val responseArrayNode = responseNode.toList() for (responseSingleJsonNode in responseArrayNode) { diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt index b289cfe3e..1b0058b90 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt @@ -27,13 +27,13 @@ import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.resourceAssignment import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition @@ -53,14 +53,14 @@ class CapabilityResourceResolutionProcessorTest { } returns MockCapabilityScriptRA() val raRuntimeService = mockk() - every { raRuntimeService.bluePrintContext() } returns mockk() + every { raRuntimeService.bluePrintContext() } returns mockk() every { raRuntimeService.getInputValue("test-property") } returns NullNode.getInstance() val capabilityResourceResolutionProcessor = CapabilityResourceResolutionProcessor(componentFunctionScriptingService) capabilityResourceResolutionProcessor.raRuntimeService = raRuntimeService - val resourceAssignment = BlueprintTypes.resourceAssignment( + val resourceAssignment = BluePrintTypes.resourceAssignment( name = "test-property", dictionaryName = "ra-dict-name", dictionarySource = "capability" ) { @@ -86,14 +86,14 @@ class CapabilityResourceResolutionProcessorTest { fun `test jython capability`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/capability_python" ) val componentFunctionScriptingService = mockk() coEvery { componentFunctionScriptingService - .scriptInstance(any(), BlueprintConstants.SCRIPT_JYTHON, any()) + .scriptInstance(any(), BluePrintConstants.SCRIPT_JYTHON, any()) } returns MockCapabilityScriptRA() val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceResolutionProcessorTest.kt index 6689aff81..0c8ec7d95 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceResolutionProcessorTest.kt @@ -19,14 +19,14 @@ import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDBLibGenericService -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BlueprintDBLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.TestDatabaseConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBlueprintProcessorCatalogServiceImpl import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockDBLibGenericService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -38,7 +38,7 @@ import kotlin.test.assertNotNull @ContextConfiguration( classes = [ TestDatabaseConfiguration::class, - PrimaryDBLibGenericService::class, BlueprintDBLibPropertyService::class, + PrimaryDBLibGenericService::class, BluePrintDBLibPropertyService::class, DatabaseResourceAssignmentProcessor::class, MockDBLibGenericService::class, MockBlueprintProcessorCatalogServiceImpl::class ] @@ -52,7 +52,7 @@ class DatabaseResourceResolutionProcessorTest { @Test fun `test database resource resolution processor db`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessorTest.kt index 7cec75950..a109131fe 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessorTest.kt @@ -20,7 +20,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -39,7 +39,7 @@ class DefaultResourceResolutionProcessorTest { @Test fun `test default resource resolution`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt index aae35f4d3..cf8dc0c59 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessorTest.kt @@ -25,7 +25,7 @@ import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -45,7 +45,7 @@ class InputResourceResolutionProcessorTest { fun `InputResourceResolutionProcessor should be able to resolve a value for an input parameter`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessorTest.kt index 9fabf5dbd..cb7214123 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessorTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessorTest.kt @@ -18,15 +18,15 @@ package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.pro import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService -import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockBluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock.MockRestResourceResolutionProcessor import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -38,15 +38,15 @@ import kotlin.test.assertNotNull @RunWith(SpringRunner::class) @ContextConfiguration( classes = [ - MockRestResourceResolutionProcessor::class, MockBlueprintRestLibPropertyService::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class, RestClientProperties::class + MockRestResourceResolutionProcessor::class, MockBluePrintRestLibPropertyService::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, RestClientProperties::class ] ) @TestPropertySource(locations = ["classpath:application-test.properties"]) class RestResourceResolutionProcessorTest { @Autowired - lateinit var bluePrintRestLibPropertyService: MockBlueprintRestLibPropertyService + lateinit var bluePrintRestLibPropertyService: MockBluePrintRestLibPropertyService private lateinit var restResourceResolutionProcessor: MockRestResourceResolutionProcessor @@ -58,7 +58,7 @@ class RestResourceResolutionProcessorTest { @Test fun `test rest resource resolution`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -92,7 +92,7 @@ class RestResourceResolutionProcessorTest { @Test fun `test rest aai get resource resolution`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -126,7 +126,7 @@ class RestResourceResolutionProcessorTest { @Test fun `test rest aai put resource resolution`() { runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext( + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtilsTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtilsTest.kt index d9e93150c..2f07e3b9a 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtilsTest.kt +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtilsTest.kt @@ -36,7 +36,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition @@ -70,7 +70,7 @@ class ResourceAssignmentUtilsTest { fun setup() { val bluePrintContext = runBlocking { - BlueprintMetadataUtils.getBlueprintContext( + BluePrintMetadataUtils.getBluePrintContext( "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) } diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorExtensions.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorExtensions.kt index 61ab4c11c..2d3eb3bab 100644 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorExtensions.kt +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorExtensions.kt @@ -21,9 +21,9 @@ import org.hibernate.annotations.common.util.impl.LoggerFactory import org.onap.ccsdk.cds.blueprintsprocessor.rest.restClientService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintRetryException -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintRetryException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService /** * Register the Restconf module exposed dependency @@ -32,7 +32,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyS val log = LoggerFactory.logger(AbstractScriptComponentFunction::class.java)!! fun AbstractScriptComponentFunction.restconfClientService(selector: String): BlueprintWebClientService { - return BlueprintDependencyService.restClientService(selector) + return BluePrintDependencyService.restClientService(selector) } /** @@ -60,7 +60,7 @@ suspend fun AbstractScriptComponentFunction.restconfMountDevice( log.info("NF was mounted successfully on ODL") result.body } else { - throw BlueprintRetryException("Wait for device($deviceId) to mount") + throw BluePrintRetryException("Wait for device($deviceId) to mount") } } @@ -126,7 +126,7 @@ suspend fun AbstractScriptComponentFunction.genericPutPatchPostRequest( "PUT" -> log.info("sending PUT request, url: $requestUrl") "PATCH" -> log.info("sending PATCH request, url: $requestUrl") "POST" -> log.info("sending POST request, url: $requestUrl") - else -> throw BlueprintProcessorException("Illegal request type, only POST, PUT or PATCH allowed.") + else -> throw BluePrintProcessorException("Illegal request type, only POST, PUT or PATCH allowed.") } return webClientService.exchangeResource(requestType, requestUrl, payload as String, headers) } @@ -143,7 +143,7 @@ suspend fun AbstractScriptComponentFunction.genericGetOrDeleteRequest( when (requestType.toUpperCase()) { "GET" -> log.info("sending GET request, url: $requestUrl") "DELETE" -> log.info("sending DELETE request, url: $requestUrl") - else -> throw BlueprintProcessorException("Illegal request type, only GET and DELETE allowed.") + else -> throw BluePrintProcessorException("Illegal request type, only GET and DELETE allowed.") } return webClientService.exchangeResource(requestType, requestUrl, "") } @@ -173,7 +173,7 @@ suspend fun AbstractScriptComponentFunction.restconfMountDevice( log.info("NF was mounted successfully on ODL") result.body } else { - throw BlueprintRetryException("Wait for device with url($mountUrl) to mount") + throw BluePrintRetryException("Wait for device with url($mountUrl) to mount") } } diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt index 653b4c56a..47cf34fad 100644 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt @@ -28,11 +28,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.context.ApplicationContext import kotlin.test.assertNotNull @@ -59,25 +59,25 @@ class ComponentRestconfExecutorTest { payload = JacksonUtils.jsonNode("{}") as ObjectNode } - val blueprintContext = mockk() + val blueprintContext = mockk() every { blueprintContext.nodeTemplateOperationImplementation( any(), any(), any() ) } returns Implementation() - val bluePrintRuntime = mockk("1234") + val bluePrintRuntime = mockk("1234") every { bluePrintRuntime.bluePrintContext() } returns blueprintContext componentScriptExecutor.bluePrintRuntimeService = bluePrintRuntime componentScriptExecutor.stepName = "sample-step" val operationInputs = hashMapOf() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-restconf".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-restconf".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_TYPE] = - BlueprintConstants.SCRIPT_INTERNAL.asJsonPrimitive() + BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive() operationInputs[ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE] = "internal.scripts.TestRestconfConfigure".asJsonPrimitive() diff --git a/ms/blueprintsprocessor/functions/restful-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restful/executor/RestfulCMComponentFunction.kt b/ms/blueprintsprocessor/functions/restful-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restful/executor/RestfulCMComponentFunction.kt index 122fe5543..9cd6f57a4 100644 --- a/ms/blueprintsprocessor/functions/restful-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restful/executor/RestfulCMComponentFunction.kt +++ b/ms/blueprintsprocessor/functions/restful-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restful/executor/RestfulCMComponentFunction.kt @@ -22,10 +22,10 @@ import com.fasterxml.jackson.databind.node.ObjectNode import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.functions.restful.executor.nrmfunction.RestfulNRMServiceClient import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory @@ -33,14 +33,14 @@ abstract class RestfulCMComponentFunction : AbstractScriptComponentFunction() { private val log = LoggerFactory.getLogger(RestfulCMComponentFunction::class.java) override suspend fun processNB(executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } - open fun bluePrintRestLibPropertyService(): BlueprintRestLibPropertyService = + open fun bluePrintRestLibPropertyService(): BluePrintRestLibPropertyService = functionDependencyInstanceAsType(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) fun restClientService(clientInfo: JsonNode): BlueprintWebClientService { diff --git a/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/ComponentRestfulExecutorTest.kt b/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/ComponentRestfulExecutorTest.kt index 989170213..ad70ac021 100644 --- a/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/ComponentRestfulExecutorTest.kt +++ b/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/ComponentRestfulExecutorTest.kt @@ -27,11 +27,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.context.ApplicationContext @@ -58,24 +58,24 @@ class ComponentRestfulExecutorTest { payload = JacksonUtils.jsonNode("{}") as ObjectNode } - val blueprintContext = mockk() + val blueprintContext = mockk() every { blueprintContext.nodeTemplateOperationImplementation( any(), any(), any() ) } returns Implementation() - val bluePrintRuntime = mockk("1234") + val bluePrintRuntime = mockk("1234") every { bluePrintRuntime.bluePrintContext() } returns blueprintContext componentRestfulExecutor.bluePrintRuntimeService = bluePrintRuntime componentRestfulExecutor.stepName = "sample-step" val operationInputs = hashMapOf() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "config-deploy-process".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() - operationInputs["script-type"] = BlueprintConstants.SCRIPT_INTERNAL.asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "config-deploy-process".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() + operationInputs["script-type"] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive() operationInputs["script-class-reference"] = "internal.scripts.TestRestfulConfigure".asJsonPrimitive() val stepInputData = StepData().apply { diff --git a/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/nrmfunction/RestfulNRMServiceClientTest.kt b/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/nrmfunction/RestfulNRMServiceClientTest.kt index 6f57439c3..6f76c9b40 100644 --- a/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/nrmfunction/RestfulNRMServiceClientTest.kt +++ b/ms/blueprintsprocessor/functions/restful-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/restful/executor/nrmfunction/RestfulNRMServiceClientTest.kt @@ -20,8 +20,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BlueprintRestLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BluePrintRestLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration @@ -44,7 +44,7 @@ import kotlin.test.assertNotNull @RunWith(SpringRunner::class) @EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class]) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@ContextConfiguration(classes = [BlueprintRestLibConfiguration::class, NrmTestController::class]) +@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, NrmTestController::class]) @TestPropertySource( properties = [ "blueprintsprocessor.restclient.nrm.type=basic-auth", @@ -59,7 +59,7 @@ class RestfulNRMServiceClientTest { @Autowired lateinit var restfulNRMServiceClient: RestfulNRMServiceClient - lateinit var bluePrintRestLibPropertyService: BlueprintRestLibPropertyService + lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService @Test fun testCreateMOI() { diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt new file mode 100644 index 000000000..5c2ae7e16 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt @@ -0,0 +1,260 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2020 IBM, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +/** + * BluePrintConstants + * + * @author Brinda Santh + */ +object BluePrintConstants { + + val APP_NAME = System.getenv("APP_NAME") + ?: "cds-controller" + + const val DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" + + const val RESPONSE_HEADER_MINOR_VERSION: String = "X-MinorVersion" + const val RESPONSE_HEADER_PATCH_VERSION: String = "X-PatchVersion" + const val RESPONSE_HEADER_LATEST_VERSION: String = "X-LatestVersion" + + const val ONAP_REQUEST_ID = "X-ONAP-RequestID" + const val ONAP_SUBREQUEST_ID = "X-ONAP-SubRequestID" + const val ONAP_ORIGINATOR_ID = "X-ONAP-OriginatorID" + const val ONAP_INVOCATION_ID = "X-ONAP-InvocationID" + const val ONAP_PARTNER_NAME = "X-ONAP-PartnerName" + + const val STATUS_SUCCESS: String = "success" + const val STATUS_PROCESSING: String = "processing" + const val STATUS_FAILURE: String = "failure" + + const val FLAG_Y: String = "Y" + const val FLAG_N: String = "N" + + const val TYPE_DEFAULT: String = "default" + + const val DATA_TYPE_STRING: String = "string" + const val DATA_TYPE_INTEGER: String = "integer" + const val DATA_TYPE_FLOAT: String = "float" + const val DATA_TYPE_DOUBLE: String = "double" + const val DATA_TYPE_BOOLEAN: String = "boolean" + const val DATA_TYPE_TIMESTAMP: String = "timestamp" + const val DATA_TYPE_NULL: String = "null" + const val DATA_TYPE_LIST: String = "list" + const val DATA_TYPE_MAP: String = "map" + const val DATA_TYPE_JSON: String = "json" + + const val BLUEPRINT_TYPE_DEFAULT = "DEFAULT" + const val BLUEPRINT_TYPE_KOTLIN_DSL = "KOTLIN_DSL" + const val BLUEPRINT_TYPE_GENERIC_SCRIPT = "GENERIC_SCRIPT" + + const val SCRIPT_KOTLIN = "kotlin" + const val SCRIPT_JYTHON = "jython" + const val SCRIPT_INTERNAL = "internal" + + const val USER_SYSTEM: String = "System" + + const val PATH_DIVIDER: String = "/" + const val PATH_SERVICE_TEMPLATE: String = "service_template" + const val PATH_TOPOLOGY_TEMPLATE: String = "topology_template" + const val PATH_METADATA: String = "metadata" + const val PATH_NODE_TYPES: String = "node_types" + const val PATH_POLICY_TYPES: String = "policy_types" + const val PATH_RELATIONSHIP_TYPES: String = "relationship_types" + const val PATH_ARTIFACT_TYPES: String = "artifact_types" + const val PATH_DATA_TYPES: String = "data_types" + const val PATH_INPUTS: String = "inputs" + const val PATH_NODE_WORKFLOWS: String = "workflows" + const val PATH_NODE_TEMPLATES: String = "node_templates" + const val PATH_RELATIONSHIP_TEMPLATES: String = "relationship_templates" + const val PATH_CAPABILITIES: String = "capabilities" + const val PATH_REQUIREMENTS: String = "requirements" + const val PATH_INTERFACES: String = "interfaces" + const val PATH_OPERATIONS: String = "operations" + const val PATH_OUTPUTS: String = "outputs" + const val PATH_PROPERTIES: String = "properties" + const val PATH_ATTRIBUTES: String = "attributes" + const val PATH_ARTIFACTS: String = "artifacts" + + const val MODEL_DIR_MODEL_TYPE: String = "definition-type" + + const val MODEL_DEFINITION_TYPE_NODE_TYPE: String = "node_type" + const val MODEL_DEFINITION_TYPE_ARTIFACT_TYPE: String = "artifact_type" + const val MODEL_DEFINITION_TYPE_CAPABILITY_TYPE: String = "capability_type" + const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE: String = "relationship_type" + const val MODEL_DEFINITION_TYPE_DATA_TYPE: String = "data_type" + const val MODEL_DEFINITION_TYPE_NODE_TEMPLATE: String = "node_template" + const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE: String = "relationship_template" + const val MODEL_DEFINITION_TYPE_WORKFLOW: String = "workflow" + const val MODEL_DEFINITION_TYPE_DSL: String = "dsl" + + const val MODEL_TYPE_DATATYPES_ROOT: String = "tosca.datatypes.Root" + const val MODEL_TYPE_NODES_ROOT: String = "tosca.nodes.Root" + const val MODEL_TYPE_GROUPS_ROOT: String = "tosca.groups.Root" + const val MODEL_TYPE_RELATIONSHIPS_ROOT: String = "tosca.relationships.Root" + const val MODEL_TYPE_ARTIFACTS_ROOT: String = "tosca.artifacts.Root" + const val MODEL_TYPE_CAPABILITIES_ROOT: String = "tosca.capabilities.Root" + const val MODEL_TYPE_INTERFACES_ROOT: String = "tosca.interfaces.Root" + + const val MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON = "tosca.relationships.DependsOn" + const val MODEL_TYPE_RELATIONSHIPS_HOSTED_ON = "tosca.relationships.HostedOn" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO = "tosca.relationships.ConnectsTo" + const val MODEL_TYPE_RELATIONSHIPS_ATTACH_TO = "tosca.relationships.AttachesTo" + const val MODEL_TYPE_RELATIONSHIPS_ROUTES_TO = "tosca.relationships.RoutesTo" + + // CDS Defined Relationship Types + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB = "tosca.relationships.ConnectsTo.Db" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT = "tosca.relationships.ConnectsTo.RestClient" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT = "tosca.relationships.ConnectsTo.SshClient" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER = "tosca.relationships.ConnectsTo.MessageProducer" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER = "tosca.relationships.ConnectsTo.MessageConsumer" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER = "tosca.relationships.ConnectsTo.GrpcServer" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT = "tosca.relationships.ConnectsTo.GrpcClient" + const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS = "tosca.relationships.ConnectsTo.Nats" + + const val MODEL_TYPE_NODE_WORKFLOW = "tosca.nodes.Workflow" + const val MODEL_TYPE_NODE_COMPONENT = "tosca.nodes.Component" + const val MODEL_TYPE_NODE_VNF = "tosca.nodes.Vnf" + const val MODEL_TYPE_NODE_RESOURCE_SOURCE = "tosca.nodes.ResourceSource" + + const val MODEL_TYPE_NODES_COMPONENT_JAVA: String = "tosca.nodes.component.Java" + const val MODEL_TYPE_NODES_COMPONENT_BUNDLE: String = "tosca.nodes.component.Bundle" + const val MODEL_TYPE_NODES_COMPONENT_SCRIPT: String = "tosca.nodes.component.Script" + const val MODEL_TYPE_NODES_COMPONENT_PYTHON: String = "tosca.nodes.component.Python" + const val MODEL_TYPE_NODES_COMPONENT_JYTHON: String = "tosca.nodes.component.Jython" + const val MODEL_TYPE_NODES_COMPONENT_KOTLIN: String = "tosca.nodes.component.Kotlin" + const val MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT: String = "tosca.nodes.component.JavaScript" + + const val MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION = "tosca.artifacts.Implementation" + + const val MODEL_TYPE_DATA_TYPE_DYNAMIC = "tosca.datatypes.Dynamic" + + const val MODEL_TYPE_CAPABILITY_TYPE_NODE = "tosca.capabilities.Node" + const val MODEL_TYPE_CAPABILITY_TYPE_COMPUTE = "tosca.capabilities.Compute" + const val MODEL_TYPE_CAPABILITY_TYPE_NETWORK = "tosca.capabilities.Network" + const val MODEL_TYPE_CAPABILITY_TYPE_STORAGE = "tosca.capabilities.Storage" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT = "tosca.capabilities.Endpoint" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC = "tosca.capabilities.Endpoint.Public" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN = "tosca.capabilities.Endpoint.Admin" + const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE = "tosca.capabilities.Endpoint.Database" + const val MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT = "tosca.capabilities.Attachment" + const val MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM = "tosca.capabilities.OperatingSystem" + const val MODEL_TYPE_CAPABILITY_TYPE_BINDABLE = "tosca.capabilities.network.Bindable" + + // Custom capabilities + const val MODEL_TYPE_CAPABILITY_TYPE_CONTENT = "tosca.capabilities.Content" + const val MODEL_TYPE_CAPABILITY_TYPE_MAPPING = "tosca.capabilities.Mapping" + const val MODEL_TYPE_CAPABILITY_TYPE_NETCONF = "tosca.capabilities.Netconf" + const val MODEL_TYPE_CAPABILITY_TYPE_RESTCONF = "tosca.capabilities.Restconf" + const val MODEL_TYPE_CAPABILITY_TYPE_SSH = "tosca.capabilities.Ssh" + const val MODEL_TYPE_CAPABILITY_TYPE_SFTP = "tosca.capabilities.Sftp" + + const val EXPRESSION_DSL_REFERENCE: String = "*" + const val EXPRESSION_GET_INPUT: String = "get_input" + const val EXPRESSION_GET_ATTRIBUTE: String = "get_attribute" + const val EXPRESSION_GET_ARTIFACT: String = "get_artifact" + const val EXPRESSION_GET_PROPERTY: String = "get_property" + const val EXPRESSION_GET_OPERATION_OUTPUT: String = "get_operation_output" + const val EXPRESSION_GET_NODE_OF_TYPE: String = "get_nodes_of_type" + + const val PROPERTY_BLUEPRINT_PROCESS_ID: String = "blueprint-process-id" + const val PROPERTY_BLUEPRINT_VALID: String = "blueprint-valid" + const val PROPERTY_BLUEPRINT_BASE_PATH: String = "blueprint-basePath" + const val PROPERTY_BLUEPRINT_RUNTIME: String = "blueprint-runtime" + const val PROPERTY_BLUEPRINT_INPUTS_DATA: String = "blueprint-inputs-data" + const val PROPERTY_BLUEPRINT_CONTEXT: String = "blueprint-context" + const val PROPERTY_BLUEPRINT_NAME: String = "template_name" + const val PROPERTY_BLUEPRINT_VERSION: String = "template_version" + + const val TOSCA_METADATA_DIR: String = "TOSCA-Metadata" + const val TOSCA_METADATA_ENTRY_DEFINITION_FILE: String = "TOSCA-Metadata/TOSCA.meta" + const val TOSCA_DEFINITIONS_DIR: String = "Definitions" + const val TOSCA_PLANS_DIR: String = "Plans" + const val TOSCA_SCRIPTS_DIR: String = "Scripts" + const val TOSCA_MAPPINGS_DIR: String = "Mappings" + const val TOSCA_TEMPLATES_DIR: String = "Templates" + const val TOSCA_ENVIRONMENTS_DIR: String = "Environments" + const val TOSCA_SCRIPTS_KOTLIN_DIR: String = "$TOSCA_SCRIPTS_DIR/kotlin" + const val TOSCA_SCRIPTS_JYTHON_DIR: String = "$TOSCA_SCRIPTS_DIR/python" + + const val UAT_SPECIFICATION_FILE = "Tests/uat.yaml" + + const val GRAPH_START_NODE_NAME = "START" + const val GRAPH_END_NODE_NAME = "END" + + const val PROPERTY_ENV = "ENV" + const val PROPERTY_APP = "APP" + const val PROPERTY_BPP = "BPP" + const val PROPERTY_SELF = "SELF" + + const val METADATA_TEMPLATE_NAME = "template_name" + const val METADATA_TEMPLATE_VERSION = "template_version" + const val METADATA_TEMPLATE_TYPE = "template_type" + const val METADATA_TEMPLATE_AUTHOR = "template_author" + const val METADATA_TEMPLATE_TAGS = "template_tags" + const val METADATA_TEMPLATE_DESCRIPTION = "template_description" + const val METADATA_WORKFLOW_NAME = "workflow_name" + + const val PAYLOAD_DATA = "payload-data" + const val PROPERTY_CURRENT_STEP = "current-step" + const val PROPERTY_CURRENT_NODE_TEMPLATE = "current-node-template" + const val PROPERTY_CURRENT_INTERFACE = "current-interface" + const val PROPERTY_CURRENT_OPERATION = "current-operation" + const val PROPERTY_CURRENT_TIMEOUT = "current-timeout" + const val PROPERTY_CURRENT_IMPLEMENTATION = "current-implementation" + const val PROPERTY_EXECUTION_REQUEST = "execution-request" + const val PROPERTY_CONNECTION_CONFIG = "connection-config" + + const val DEFAULT_VERSION_NUMBER = "1.0.0" + const val DEFAULT_STEP_OPERATION = "process" + const val DEFAULT_STEP_INTERFACE = "ComponentInterface" + + const val MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY = "artifact-template-velocity" + const val MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA = "artifact-template-jinja" + const val MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE = "artifact-mapping-resource" + const val MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON = "artifact-script-jython" + const val MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN = "artifact-script-kotlin" + const val MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH = "artifact-directed-graph" + const val MODEL_TYPE_ARTIFACT_COMPONENT_JAR = "artifact-component-jar" + const val MODEL_TYPE_ARTIFACT_K8S_PROFILE = "artifact-k8sprofile-content" + const val MODEL_TYPE_ARTIFACT_K8S_CONFIG = "artifact-k8sconfig-content" + + const val TOSCA_SPEC = "TOSCA" + + const val LOG_PROTECT: String = "log-protect" + + /** Cluster Properties */ + val CLUSTER_ENABLED = (System.getenv("CLUSTER_ENABLED") ?: "false").toBoolean() + const val PROPERTY_CLUSTER_ID = "CLUSTER_ID" + const val PROPERTY_CLUSTER_NODE_ID = "CLUSTER_NODE_ID" + const val PROPERTY_CLUSTER_NODE_ADDRESS = "CLUSTER_NODE_ADDRESS" + const val PROPERTY_CLUSTER_JOIN_AS_CLIENT = "CLUSTER_JOIN_AS_CLIENT" + const val PROPERTY_CLUSTER_CONFIG_FILE = "CLUSTER_CONFIG_FILE" + + const val NODE_TEMPLATE_TYPE_COMPONENT_RESOURCE_RESOLUTION = "component-resource-resolution" + const val NODE_TEMPLATE_TYPE_DG = "dg-generic" + const val PROPERTY_DG_DEPENDENCY_NODE_TEMPLATE = "dependency-node-templates" + + // TAGS + const val METRIC_TAG_BP_NAME = "blueprint_name" + const val METRIC_TAG_BP_VERSION = "blueprint_version" + const val METRIC_TAG_BP_ACTION = "blueprint_action" + const val METRIC_TAG_BP_STATUS = "status" + const val METRIC_TAG_BP_OUTCOME = "outcome" + const val METRIC_TAG_TOPIC = "topic" +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt new file mode 100644 index 000000000..1ac49d6fe --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt @@ -0,0 +1,38 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +class BluePrintError { + + private val errors: MutableMap> = mutableMapOf() + + fun addError(type: String, name: String, error: String, stepName: String) { + addError("$type : $name : $error", stepName) + } + + fun addError(error: String, stepName: String) { + errors.getOrPut(stepName, { mutableListOf() }).add(error) + } + + fun addErrors(stepName: String, errorList: List) { + errors.getOrPut(stepName, { mutableListOf() }).addAll(errorList) + } + + fun allErrors(): List = errors.values.flatten() + + fun stepErrors(stepName: String): MutableList? = errors[stepName] +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt new file mode 100644 index 000000000..74e6bb6bd --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt @@ -0,0 +1,34 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2020 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +/** + * + * + * @author Brinda Santh + */ +class BluePrintException : BluePrintProcessorException { + + constructor(cause: Throwable) : super(cause) + constructor(message: String) : super(message) + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(cause, message, args) + constructor(code: Int, cause: Throwable) : super(code, cause) + constructor(code: Int, message: String) : super(code, message) + constructor(code: Int, message: String, cause: Throwable) : super(code, message, cause) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt new file mode 100644 index 000000000..daf833494 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt @@ -0,0 +1,148 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.ArtifactExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.AttributeExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsConstrain +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsDataType +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsProperty +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.DSLExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.InputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.OperationOutputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyDefaultValue +import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dslExpression +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateArtifact +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateAttribute +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateOperationOutput +import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateProperty +import kotlin.reflect.KClass +import kotlin.reflect.KProperty1 +import kotlin.reflect.KType +import kotlin.reflect.full.declaredMemberProperties + +fun > T.asBluePrintsDataTypes(): DataType { + val annotation = this.annotations.filter { it is BluePrintsDataType }.single() as BluePrintsDataType + checkNotNull(annotation) { "BluePrintsDataType annotation definition not found" } + val dataType = DataType().apply { + id = annotation.name + version = annotation.version + derivedFrom = annotation.derivedFrom + description = annotation.description + } + dataType.properties = this.asPropertyDefinitionMap() + return dataType +} + +fun > T.asPropertyDefinitionMap(): MutableMap { + val properties: MutableMap = hashMapOf() + this.declaredMemberProperties.forEach { member -> + properties[member.name] = member.asPropertyDefinition() + } + return properties +} + +fun KProperty1.asPropertyDefinition(): PropertyDefinition { + val property = PropertyDefinition() + property.id = this.name + val getter = this.getter + property.required = !this.returnType.isMarkedNullable + property.type = this.returnType.asBluePrintsDataType(this.name) + if (this.returnType.arguments.isNotEmpty()) { + property.entrySchema = this.returnType.entitySchema() + } + this.annotations.forEach { fieldAnnotation -> + // println("Field : ${this.name} : Annotation : $fieldAnnotation") + when (fieldAnnotation) { + is BluePrintsProperty -> + property.description = fieldAnnotation.description + is PropertyDefaultValue -> + property.value = fieldAnnotation.value.asJsonType(property.type) + is BluePrintsConstrain -> { + if (property.constraints == null) property.constraints = arrayListOf() + property.constraints!!.add(fieldAnnotation.asBluePrintConstraintClause()) + } + is InputExpression -> { + property.value = getInput(fieldAnnotation.propertyName) + } + is PropertyExpression -> { + property.value = getNodeTemplateProperty( + fieldAnnotation.modelableEntityName, + fieldAnnotation.propertyName, fieldAnnotation.subPropertyName + ) + } + is AttributeExpression -> { + property.value = getNodeTemplateAttribute( + fieldAnnotation.modelableEntityName, + fieldAnnotation.attributeName, fieldAnnotation.subAttributeName + ) + } + is ArtifactExpression -> { + property.value = getNodeTemplateArtifact( + fieldAnnotation.modelableEntityName, + fieldAnnotation.artifactName + ) + } + is OperationOutputExpression -> { + property.value = getNodeTemplateOperationOutput( + fieldAnnotation.modelableEntityName, + fieldAnnotation.interfaceName, fieldAnnotation.propertyName, fieldAnnotation.subPropertyName + ) + } + is DSLExpression -> { + property.value = dslExpression(fieldAnnotation.propertyName) + } + } + } + return property +} + +internal fun BluePrintsConstrain.asBluePrintConstraintClause(): ConstraintClause { + TODO() +} + +internal fun T.entitySchema(): EntrySchema { + val entrySchema = EntrySchema() + if (this.arguments.size == 1) { + entrySchema.type = this.arguments[0].type!!.asBluePrintsDataType("") + } else if (this.arguments.size == 2) { + entrySchema.type = this.arguments[1].type!!.asBluePrintsDataType("") + } + return entrySchema +} + +internal fun T.asBluePrintsDataType(propertyName: String): String { + val simpleName = (this.classifier as? KClass<*>)?.java?.simpleName + ?: throw BluePrintException("filed to get simple name.") + return when (simpleName) { + "String", "Date" -> BluePrintConstants.DATA_TYPE_STRING + "int" -> BluePrintConstants.DATA_TYPE_INTEGER + "Boolean" -> BluePrintConstants.DATA_TYPE_BOOLEAN + "Float" -> BluePrintConstants.DATA_TYPE_FLOAT + "Double" -> BluePrintConstants.DATA_TYPE_DOUBLE + "List" -> BluePrintConstants.DATA_TYPE_LIST + "Map" -> BluePrintConstants.DATA_TYPE_MAP + "Object", "JsonNode", "ObjectNode", "ArrayNode" -> BluePrintConstants.DATA_TYPE_JSON + else -> simpleName + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt new file mode 100644 index 000000000..c818b0a44 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt @@ -0,0 +1,175 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2020 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +import org.apache.commons.lang.exception.ExceptionUtils +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogException +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogExceptionFluent +import org.onap.ccsdk.cds.error.catalog.core.ErrorMessage + +/** + * + * + * @author Brinda Santh + */ +open class BluePrintProcessorException : ErrorCatalogException, ErrorCatalogExceptionFluent { + + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(message: String) : super(message) + constructor(cause: Throwable) : super(cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(cause, message, args) + constructor(code: Int, cause: Throwable) : super(code, cause) + constructor(code: Int, message: String) : super(code, message) + constructor(code: Int, message: String, cause: Throwable) : super(code, message, cause) + + override fun code(code: Int): BluePrintProcessorException { + return this.updateCode(code) + } + + override fun domain(domain: String): BluePrintProcessorException { + return this.updateDomain(domain) + } + + override fun action(action: String): BluePrintProcessorException { + return this.updateAction(action) + } + + override fun http(type: String): BluePrintProcessorException { + return this.updateHttp(type) + } + + override fun grpc(type: String): BluePrintProcessorException { + return this.updateGrpc(type) + } + + override fun convertToHttp(): BluePrintProcessorException { + return this.inverseToHttp() + } + + override fun convertToGrpc(): BluePrintProcessorException { + return this.inverseToHttp() + } + + override fun payloadMessage(message: String): BluePrintProcessorException { + return this.updatePayloadMessage(message) + } + + override fun addErrorPayloadMessage(message: String): BluePrintProcessorException { + return this.updateErrorPayloadMessage(message) + } + + override fun addSubError(errorMessage: ErrorMessage): BluePrintProcessorException { + return this.updateSubError(errorMessage) + } +} + +class BluePrintRetryException : RuntimeException { + constructor(message: String, cause: Throwable) : super(message, cause) + constructor(message: String) : super(message) + constructor(cause: Throwable) : super(cause) + constructor(cause: Throwable, message: String, vararg args: Any?) : super(format(message, *args), cause) +} + +/** Extension Functions */ + +fun processorException(message: String): BluePrintProcessorException { + return BluePrintProcessorException(message) +} + +fun processorException(message: String, cause: Throwable): BluePrintProcessorException { + return BluePrintProcessorException(message, cause) +} + +fun processorException(cause: Throwable, message: String, vararg args: Any?): BluePrintProcessorException { + return BluePrintProcessorException(cause, message, args) +} + +fun processorException(code: Int, message: String): BluePrintProcessorException { + return processorException(message).code(code) +} + +fun processorException(code: Int, message: String, cause: Throwable): BluePrintProcessorException { + return processorException(message, cause).code(code) +} + +fun processorException(code: Int, cause: Throwable, message: String, vararg args: Any?): BluePrintProcessorException { + return processorException(cause, message, args).code(code) +} + +fun httpProcessorException(type: String, message: String): BluePrintProcessorException { + return processorException(message).http(type) +} + +fun grpcProcessorException(type: String, message: String): BluePrintProcessorException { + return processorException(message).grpc(type) +} + +fun httpProcessorException(type: String, domain: String, message: String): BluePrintProcessorException { + val bluePrintProcessorException = processorException(message).http(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message) +} + +fun grpcProcessorException(type: String, domain: String, message: String): BluePrintProcessorException { + val bluePrintProcessorException = processorException(message).grpc(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message) +} + +fun httpProcessorException(type: String, domain: String, message: String, cause: Throwable): + BluePrintProcessorException { + val bluePrintProcessorException = processorException(message, cause).http(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) + } + +fun grpcProcessorException(type: String, domain: String, message: String, cause: Throwable): + BluePrintProcessorException { + val bluePrintProcessorException = processorException(message, cause).grpc(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) + } + +fun httpProcessorException(type: String, domain: String, message: String, cause: Throwable, vararg args: Any?): + BluePrintProcessorException { + val bluePrintProcessorException = processorException(cause, message, args).http(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) + } + +fun grpcProcessorException(type: String, domain: String, message: String, cause: Throwable, vararg args: Any?): + BluePrintProcessorException { + val bluePrintProcessorException = processorException(cause, message, args).grpc(type) + return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) + } + +fun BluePrintProcessorException.updateErrorMessage(domain: String, message: String, cause: String): + BluePrintProcessorException { + return this.addDomainAndErrorMessage(domain, message, cause).domain(domain) + .addErrorPayloadMessage(message) + .payloadMessage(message) + } + +fun BluePrintProcessorException.updateErrorMessage(domain: String, message: String): BluePrintProcessorException { + return this.addDomainAndErrorMessage(domain, message).domain(domain) + .addErrorPayloadMessage(message) + .payloadMessage(message) +} + +private fun BluePrintProcessorException.addDomainAndErrorMessage( + domain: String, + message: String, + cause: String = "" +): BluePrintProcessorException { + return this.addSubError(ErrorMessage(domain, message, cause)).domain(domain) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt new file mode 100644 index 000000000..1c769932f --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt @@ -0,0 +1,170 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core + +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition + +/** + * + * + * @author Brinda Santh + */ +object BluePrintTypes { + + @JvmStatic + val validNodeTypeDerivedFroms: MutableList = arrayListOf( + BluePrintConstants.MODEL_TYPE_NODES_ROOT, + BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, + BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, + BluePrintConstants.MODEL_TYPE_NODE_VNF, + BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_BUNDLE, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_SCRIPT, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_PYTHON, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JYTHON, + BluePrintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT + ) + + @JvmStatic + val validArtifactTypeDerivedFroms: MutableList = arrayListOf( + BluePrintConstants.MODEL_TYPE_ARTIFACTS_ROOT, + BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION + ) + + @JvmStatic + val validDataTypeDerivedFroms: MutableList = arrayListOf( + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, + BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC + ) + + @JvmStatic + val validRelationShipDerivedFroms: MutableList = arrayListOf( + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ATTACH_TO, + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROUTES_TO + ) + + @JvmStatic + val validCapabilityTypes: MutableList = arrayListOf( + BluePrintConstants.MODEL_TYPE_CAPABILITIES_ROOT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NODE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_COMPUTE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETWORK, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_STORAGE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_BINDABLE, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_CONTENT, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_MAPPING, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETCONF, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_RESTCONF, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SSH, + BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP + ) + + @JvmStatic + fun validModelTypes(): List { + val validTypes: MutableList = arrayListOf() + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) + validTypes.add(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) + return validTypes + } + + @JvmStatic + fun validPropertyTypes(): List { + val validTypes: MutableList = arrayListOf() + validTypes.addAll(validPrimitiveTypes()) + validTypes.addAll(validComplexTypes()) + validTypes.addAll(validCollectionTypes()) + return validTypes + } + + @JvmStatic + fun validPrimitiveTypes(): List { + val validTypes: MutableList = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_STRING) + validTypes.add(BluePrintConstants.DATA_TYPE_INTEGER) + validTypes.add(BluePrintConstants.DATA_TYPE_FLOAT) + validTypes.add(BluePrintConstants.DATA_TYPE_DOUBLE) + validTypes.add(BluePrintConstants.DATA_TYPE_BOOLEAN) + validTypes.add(BluePrintConstants.DATA_TYPE_TIMESTAMP) + validTypes.add(BluePrintConstants.DATA_TYPE_NULL) + return validTypes + } + + @JvmStatic + fun validComplexTypes(): List { + val validTypes: MutableList = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_JSON) + validTypes.add(BluePrintConstants.DATA_TYPE_MAP) + return validTypes + } + + @JvmStatic + fun validCollectionTypes(): List { + val validTypes: MutableList = arrayListOf() + validTypes.add(BluePrintConstants.DATA_TYPE_LIST) + return validTypes + } + + @JvmStatic + fun validPrimitiveOrCollectionPrimitive(propertyDefinition: PropertyDefinition): Boolean { + val entrySchema = propertyDefinition.entrySchema?.type ?: BluePrintConstants.DATA_TYPE_NULL + return BluePrintTypes.validPropertyTypes().contains(propertyDefinition.type) && + BluePrintTypes.validPrimitiveTypes().contains(entrySchema) + } + + @JvmStatic + fun validCommands(): List { + return listOf( + BluePrintConstants.EXPRESSION_DSL_REFERENCE, + BluePrintConstants.EXPRESSION_GET_INPUT, + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE, + BluePrintConstants.EXPRESSION_GET_PROPERTY, + BluePrintConstants.EXPRESSION_GET_ARTIFACT, + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT, + BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE + ) + } + + @JvmStatic + fun rootNodeTypes(): List { + return listOf(BluePrintConstants.MODEL_TYPE_NODES_ROOT) + } + + @JvmStatic + fun rootRelationshipTypes(): List { + return listOf(BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT) + } + + @JvmStatic + fun rootDataTypes(): List { + return listOf(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintConstants.kt deleted file mode 100644 index 256339c62..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintConstants.kt +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 - 2020 IBM, Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -/** - * BlueprintConstants - * - * @author Brinda Santh - */ -object BlueprintConstants { - - val APP_NAME = System.getenv("APP_NAME") - ?: "cds-controller" - - const val DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" - - const val RESPONSE_HEADER_MINOR_VERSION: String = "X-MinorVersion" - const val RESPONSE_HEADER_PATCH_VERSION: String = "X-PatchVersion" - const val RESPONSE_HEADER_LATEST_VERSION: String = "X-LatestVersion" - - const val ONAP_REQUEST_ID = "X-ONAP-RequestID" - const val ONAP_SUBREQUEST_ID = "X-ONAP-SubRequestID" - const val ONAP_ORIGINATOR_ID = "X-ONAP-OriginatorID" - const val ONAP_INVOCATION_ID = "X-ONAP-InvocationID" - const val ONAP_PARTNER_NAME = "X-ONAP-PartnerName" - - const val STATUS_SUCCESS: String = "success" - const val STATUS_PROCESSING: String = "processing" - const val STATUS_FAILURE: String = "failure" - - const val FLAG_Y: String = "Y" - const val FLAG_N: String = "N" - - const val TYPE_DEFAULT: String = "default" - - const val DATA_TYPE_STRING: String = "string" - const val DATA_TYPE_INTEGER: String = "integer" - const val DATA_TYPE_FLOAT: String = "float" - const val DATA_TYPE_DOUBLE: String = "double" - const val DATA_TYPE_BOOLEAN: String = "boolean" - const val DATA_TYPE_TIMESTAMP: String = "timestamp" - const val DATA_TYPE_NULL: String = "null" - const val DATA_TYPE_LIST: String = "list" - const val DATA_TYPE_MAP: String = "map" - const val DATA_TYPE_JSON: String = "json" - - const val BLUEPRINT_TYPE_DEFAULT = "DEFAULT" - const val BLUEPRINT_TYPE_KOTLIN_DSL = "KOTLIN_DSL" - const val BLUEPRINT_TYPE_GENERIC_SCRIPT = "GENERIC_SCRIPT" - - const val SCRIPT_KOTLIN = "kotlin" - const val SCRIPT_JYTHON = "jython" - const val SCRIPT_INTERNAL = "internal" - - const val USER_SYSTEM: String = "System" - - const val PATH_DIVIDER: String = "/" - const val PATH_SERVICE_TEMPLATE: String = "service_template" - const val PATH_TOPOLOGY_TEMPLATE: String = "topology_template" - const val PATH_METADATA: String = "metadata" - const val PATH_NODE_TYPES: String = "node_types" - const val PATH_POLICY_TYPES: String = "policy_types" - const val PATH_RELATIONSHIP_TYPES: String = "relationship_types" - const val PATH_ARTIFACT_TYPES: String = "artifact_types" - const val PATH_DATA_TYPES: String = "data_types" - const val PATH_INPUTS: String = "inputs" - const val PATH_NODE_WORKFLOWS: String = "workflows" - const val PATH_NODE_TEMPLATES: String = "node_templates" - const val PATH_RELATIONSHIP_TEMPLATES: String = "relationship_templates" - const val PATH_CAPABILITIES: String = "capabilities" - const val PATH_REQUIREMENTS: String = "requirements" - const val PATH_INTERFACES: String = "interfaces" - const val PATH_OPERATIONS: String = "operations" - const val PATH_OUTPUTS: String = "outputs" - const val PATH_PROPERTIES: String = "properties" - const val PATH_ATTRIBUTES: String = "attributes" - const val PATH_ARTIFACTS: String = "artifacts" - - const val MODEL_DIR_MODEL_TYPE: String = "definition-type" - - const val MODEL_DEFINITION_TYPE_NODE_TYPE: String = "node_type" - const val MODEL_DEFINITION_TYPE_ARTIFACT_TYPE: String = "artifact_type" - const val MODEL_DEFINITION_TYPE_CAPABILITY_TYPE: String = "capability_type" - const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE: String = "relationship_type" - const val MODEL_DEFINITION_TYPE_DATA_TYPE: String = "data_type" - const val MODEL_DEFINITION_TYPE_NODE_TEMPLATE: String = "node_template" - const val MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE: String = "relationship_template" - const val MODEL_DEFINITION_TYPE_WORKFLOW: String = "workflow" - const val MODEL_DEFINITION_TYPE_DSL: String = "dsl" - - const val MODEL_TYPE_DATATYPES_ROOT: String = "tosca.datatypes.Root" - const val MODEL_TYPE_NODES_ROOT: String = "tosca.nodes.Root" - const val MODEL_TYPE_GROUPS_ROOT: String = "tosca.groups.Root" - const val MODEL_TYPE_RELATIONSHIPS_ROOT: String = "tosca.relationships.Root" - const val MODEL_TYPE_ARTIFACTS_ROOT: String = "tosca.artifacts.Root" - const val MODEL_TYPE_CAPABILITIES_ROOT: String = "tosca.capabilities.Root" - const val MODEL_TYPE_INTERFACES_ROOT: String = "tosca.interfaces.Root" - - const val MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON = "tosca.relationships.DependsOn" - const val MODEL_TYPE_RELATIONSHIPS_HOSTED_ON = "tosca.relationships.HostedOn" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO = "tosca.relationships.ConnectsTo" - const val MODEL_TYPE_RELATIONSHIPS_ATTACH_TO = "tosca.relationships.AttachesTo" - const val MODEL_TYPE_RELATIONSHIPS_ROUTES_TO = "tosca.relationships.RoutesTo" - - // CDS Defined Relationship Types - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB = "tosca.relationships.ConnectsTo.Db" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT = "tosca.relationships.ConnectsTo.RestClient" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT = "tosca.relationships.ConnectsTo.SshClient" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER = "tosca.relationships.ConnectsTo.MessageProducer" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER = "tosca.relationships.ConnectsTo.MessageConsumer" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER = "tosca.relationships.ConnectsTo.GrpcServer" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT = "tosca.relationships.ConnectsTo.GrpcClient" - const val MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS = "tosca.relationships.ConnectsTo.Nats" - - const val MODEL_TYPE_NODE_WORKFLOW = "tosca.nodes.Workflow" - const val MODEL_TYPE_NODE_COMPONENT = "tosca.nodes.Component" - const val MODEL_TYPE_NODE_VNF = "tosca.nodes.Vnf" - const val MODEL_TYPE_NODE_RESOURCE_SOURCE = "tosca.nodes.ResourceSource" - - const val MODEL_TYPE_NODES_COMPONENT_JAVA: String = "tosca.nodes.component.Java" - const val MODEL_TYPE_NODES_COMPONENT_BUNDLE: String = "tosca.nodes.component.Bundle" - const val MODEL_TYPE_NODES_COMPONENT_SCRIPT: String = "tosca.nodes.component.Script" - const val MODEL_TYPE_NODES_COMPONENT_PYTHON: String = "tosca.nodes.component.Python" - const val MODEL_TYPE_NODES_COMPONENT_JYTHON: String = "tosca.nodes.component.Jython" - const val MODEL_TYPE_NODES_COMPONENT_KOTLIN: String = "tosca.nodes.component.Kotlin" - const val MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT: String = "tosca.nodes.component.JavaScript" - - const val MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION = "tosca.artifacts.Implementation" - - const val MODEL_TYPE_DATA_TYPE_DYNAMIC = "tosca.datatypes.Dynamic" - - const val MODEL_TYPE_CAPABILITY_TYPE_NODE = "tosca.capabilities.Node" - const val MODEL_TYPE_CAPABILITY_TYPE_COMPUTE = "tosca.capabilities.Compute" - const val MODEL_TYPE_CAPABILITY_TYPE_NETWORK = "tosca.capabilities.Network" - const val MODEL_TYPE_CAPABILITY_TYPE_STORAGE = "tosca.capabilities.Storage" - const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT = "tosca.capabilities.Endpoint" - const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC = "tosca.capabilities.Endpoint.Public" - const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN = "tosca.capabilities.Endpoint.Admin" - const val MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE = "tosca.capabilities.Endpoint.Database" - const val MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT = "tosca.capabilities.Attachment" - const val MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM = "tosca.capabilities.OperatingSystem" - const val MODEL_TYPE_CAPABILITY_TYPE_BINDABLE = "tosca.capabilities.network.Bindable" - - // Custom capabilities - const val MODEL_TYPE_CAPABILITY_TYPE_CONTENT = "tosca.capabilities.Content" - const val MODEL_TYPE_CAPABILITY_TYPE_MAPPING = "tosca.capabilities.Mapping" - const val MODEL_TYPE_CAPABILITY_TYPE_NETCONF = "tosca.capabilities.Netconf" - const val MODEL_TYPE_CAPABILITY_TYPE_RESTCONF = "tosca.capabilities.Restconf" - const val MODEL_TYPE_CAPABILITY_TYPE_SSH = "tosca.capabilities.Ssh" - const val MODEL_TYPE_CAPABILITY_TYPE_SFTP = "tosca.capabilities.Sftp" - - const val EXPRESSION_DSL_REFERENCE: String = "*" - const val EXPRESSION_GET_INPUT: String = "get_input" - const val EXPRESSION_GET_ATTRIBUTE: String = "get_attribute" - const val EXPRESSION_GET_ARTIFACT: String = "get_artifact" - const val EXPRESSION_GET_PROPERTY: String = "get_property" - const val EXPRESSION_GET_OPERATION_OUTPUT: String = "get_operation_output" - const val EXPRESSION_GET_NODE_OF_TYPE: String = "get_nodes_of_type" - - const val PROPERTY_BLUEPRINT_PROCESS_ID: String = "blueprint-process-id" - const val PROPERTY_BLUEPRINT_VALID: String = "blueprint-valid" - const val PROPERTY_BLUEPRINT_BASE_PATH: String = "blueprint-basePath" - const val PROPERTY_BLUEPRINT_RUNTIME: String = "blueprint-runtime" - const val PROPERTY_BLUEPRINT_INPUTS_DATA: String = "blueprint-inputs-data" - const val PROPERTY_BLUEPRINT_CONTEXT: String = "blueprint-context" - const val PROPERTY_BLUEPRINT_NAME: String = "template_name" - const val PROPERTY_BLUEPRINT_VERSION: String = "template_version" - - const val TOSCA_METADATA_DIR: String = "TOSCA-Metadata" - const val TOSCA_METADATA_ENTRY_DEFINITION_FILE: String = "TOSCA-Metadata/TOSCA.meta" - const val TOSCA_DEFINITIONS_DIR: String = "Definitions" - const val TOSCA_PLANS_DIR: String = "Plans" - const val TOSCA_SCRIPTS_DIR: String = "Scripts" - const val TOSCA_MAPPINGS_DIR: String = "Mappings" - const val TOSCA_TEMPLATES_DIR: String = "Templates" - const val TOSCA_ENVIRONMENTS_DIR: String = "Environments" - const val TOSCA_SCRIPTS_KOTLIN_DIR: String = "$TOSCA_SCRIPTS_DIR/kotlin" - const val TOSCA_SCRIPTS_JYTHON_DIR: String = "$TOSCA_SCRIPTS_DIR/python" - - const val UAT_SPECIFICATION_FILE = "Tests/uat.yaml" - - const val GRAPH_START_NODE_NAME = "START" - const val GRAPH_END_NODE_NAME = "END" - - const val PROPERTY_ENV = "ENV" - const val PROPERTY_APP = "APP" - const val PROPERTY_BPP = "BPP" - const val PROPERTY_SELF = "SELF" - - const val METADATA_TEMPLATE_NAME = "template_name" - const val METADATA_TEMPLATE_VERSION = "template_version" - const val METADATA_TEMPLATE_TYPE = "template_type" - const val METADATA_TEMPLATE_AUTHOR = "template_author" - const val METADATA_TEMPLATE_TAGS = "template_tags" - const val METADATA_TEMPLATE_DESCRIPTION = "template_description" - const val METADATA_WORKFLOW_NAME = "workflow_name" - - const val PAYLOAD_DATA = "payload-data" - const val PROPERTY_CURRENT_STEP = "current-step" - const val PROPERTY_CURRENT_NODE_TEMPLATE = "current-node-template" - const val PROPERTY_CURRENT_INTERFACE = "current-interface" - const val PROPERTY_CURRENT_OPERATION = "current-operation" - const val PROPERTY_CURRENT_TIMEOUT = "current-timeout" - const val PROPERTY_CURRENT_IMPLEMENTATION = "current-implementation" - const val PROPERTY_EXECUTION_REQUEST = "execution-request" - const val PROPERTY_CONNECTION_CONFIG = "connection-config" - - const val DEFAULT_VERSION_NUMBER = "1.0.0" - const val DEFAULT_STEP_OPERATION = "process" - const val DEFAULT_STEP_INTERFACE = "ComponentInterface" - - const val MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY = "artifact-template-velocity" - const val MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA = "artifact-template-jinja" - const val MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE = "artifact-mapping-resource" - const val MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON = "artifact-script-jython" - const val MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN = "artifact-script-kotlin" - const val MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH = "artifact-directed-graph" - const val MODEL_TYPE_ARTIFACT_COMPONENT_JAR = "artifact-component-jar" - const val MODEL_TYPE_ARTIFACT_K8S_PROFILE = "artifact-k8sprofile-content" - const val MODEL_TYPE_ARTIFACT_K8S_CONFIG = "artifact-k8sconfig-content" - - const val TOSCA_SPEC = "TOSCA" - - const val LOG_PROTECT: String = "log-protect" - - /** Cluster Properties */ - val CLUSTER_ENABLED = (System.getenv("CLUSTER_ENABLED") ?: "false").toBoolean() - const val PROPERTY_CLUSTER_ID = "CLUSTER_ID" - const val PROPERTY_CLUSTER_NODE_ID = "CLUSTER_NODE_ID" - const val PROPERTY_CLUSTER_NODE_ADDRESS = "CLUSTER_NODE_ADDRESS" - const val PROPERTY_CLUSTER_JOIN_AS_CLIENT = "CLUSTER_JOIN_AS_CLIENT" - const val PROPERTY_CLUSTER_CONFIG_FILE = "CLUSTER_CONFIG_FILE" - - const val NODE_TEMPLATE_TYPE_COMPONENT_RESOURCE_RESOLUTION = "component-resource-resolution" - const val NODE_TEMPLATE_TYPE_DG = "dg-generic" - const val PROPERTY_DG_DEPENDENCY_NODE_TEMPLATE = "dependency-node-templates" - - // TAGS - const val METRIC_TAG_BP_NAME = "blueprint_name" - const val METRIC_TAG_BP_VERSION = "blueprint_version" - const val METRIC_TAG_BP_ACTION = "blueprint_action" - const val METRIC_TAG_BP_STATUS = "status" - const val METRIC_TAG_BP_OUTCOME = "outcome" - const val METRIC_TAG_TOPIC = "topic" -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintError.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintError.kt deleted file mode 100644 index 2ecdce770..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintError.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -class BlueprintError { - - private val errors: MutableMap> = mutableMapOf() - - fun addError(type: String, name: String, error: String, stepName: String) { - addError("$type : $name : $error", stepName) - } - - fun addError(error: String, stepName: String) { - errors.getOrPut(stepName, { mutableListOf() }).add(error) - } - - fun addErrors(stepName: String, errorList: List) { - errors.getOrPut(stepName, { mutableListOf() }).addAll(errorList) - } - - fun allErrors(): List = errors.values.flatten() - - fun stepErrors(stepName: String): MutableList? = errors[stepName] -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintException.kt deleted file mode 100644 index 10e6f5959..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintException.kt +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 - 2020 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -/** - * - * - * @author Brinda Santh - */ -class BlueprintException : BlueprintProcessorException { - - constructor(cause: Throwable) : super(cause) - constructor(message: String) : super(message) - constructor(message: String, cause: Throwable) : super(message, cause) - constructor(cause: Throwable, message: String, vararg args: Any?) : super(cause, message, args) - constructor(code: Int, cause: Throwable) : super(code, cause) - constructor(code: Int, message: String) : super(code, message) - constructor(code: Int, message: String, cause: Throwable) : super(code, message, cause) -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintExtensionFunctions.kt deleted file mode 100644 index 0a1b0954a..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintExtensionFunctions.kt +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.ArtifactExpression -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.AttributeExpression -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BlueprintsConstrain -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BlueprintsDataType -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BlueprintsProperty -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.DSLExpression -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.InputExpression -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.OperationOutputExpression -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyDefaultValue -import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dslExpression -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateArtifact -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateAttribute -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateOperationOutput -import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateProperty -import kotlin.reflect.KClass -import kotlin.reflect.KProperty1 -import kotlin.reflect.KType -import kotlin.reflect.full.declaredMemberProperties - -fun > T.asBlueprintsDataTypes(): DataType { - val annotation = this.annotations.filter { it is BlueprintsDataType }.single() as BlueprintsDataType - checkNotNull(annotation) { "BlueprintsDataType annotation definition not found" } - val dataType = DataType().apply { - id = annotation.name - version = annotation.version - derivedFrom = annotation.derivedFrom - description = annotation.description - } - dataType.properties = this.asPropertyDefinitionMap() - return dataType -} - -fun > T.asPropertyDefinitionMap(): MutableMap { - val properties: MutableMap = hashMapOf() - this.declaredMemberProperties.forEach { member -> - properties[member.name] = member.asPropertyDefinition() - } - return properties -} - -fun KProperty1.asPropertyDefinition(): PropertyDefinition { - val property = PropertyDefinition() - property.id = this.name - val getter = this.getter - property.required = !this.returnType.isMarkedNullable - property.type = this.returnType.asBlueprintsDataType(this.name) - if (this.returnType.arguments.isNotEmpty()) { - property.entrySchema = this.returnType.entitySchema() - } - this.annotations.forEach { fieldAnnotation -> - // println("Field : ${this.name} : Annotation : $fieldAnnotation") - when (fieldAnnotation) { - is BlueprintsProperty -> - property.description = fieldAnnotation.description - is PropertyDefaultValue -> - property.value = fieldAnnotation.value.asJsonType(property.type) - is BlueprintsConstrain -> { - if (property.constraints == null) property.constraints = arrayListOf() - property.constraints!!.add(fieldAnnotation.asBlueprintConstraintClause()) - } - is InputExpression -> { - property.value = getInput(fieldAnnotation.propertyName) - } - is PropertyExpression -> { - property.value = getNodeTemplateProperty( - fieldAnnotation.modelableEntityName, - fieldAnnotation.propertyName, fieldAnnotation.subPropertyName - ) - } - is AttributeExpression -> { - property.value = getNodeTemplateAttribute( - fieldAnnotation.modelableEntityName, - fieldAnnotation.attributeName, fieldAnnotation.subAttributeName - ) - } - is ArtifactExpression -> { - property.value = getNodeTemplateArtifact( - fieldAnnotation.modelableEntityName, - fieldAnnotation.artifactName - ) - } - is OperationOutputExpression -> { - property.value = getNodeTemplateOperationOutput( - fieldAnnotation.modelableEntityName, - fieldAnnotation.interfaceName, fieldAnnotation.propertyName, fieldAnnotation.subPropertyName - ) - } - is DSLExpression -> { - property.value = dslExpression(fieldAnnotation.propertyName) - } - } - } - return property -} - -internal fun BlueprintsConstrain.asBlueprintConstraintClause(): ConstraintClause { - TODO() -} - -internal fun T.entitySchema(): EntrySchema { - val entrySchema = EntrySchema() - if (this.arguments.size == 1) { - entrySchema.type = this.arguments[0].type!!.asBlueprintsDataType("") - } else if (this.arguments.size == 2) { - entrySchema.type = this.arguments[1].type!!.asBlueprintsDataType("") - } - return entrySchema -} - -internal fun T.asBlueprintsDataType(propertyName: String): String { - val simpleName = (this.classifier as? KClass<*>)?.java?.simpleName - ?: throw BlueprintException("filed to get simple name.") - return when (simpleName) { - "String", "Date" -> BlueprintConstants.DATA_TYPE_STRING - "int" -> BlueprintConstants.DATA_TYPE_INTEGER - "Boolean" -> BlueprintConstants.DATA_TYPE_BOOLEAN - "Float" -> BlueprintConstants.DATA_TYPE_FLOAT - "Double" -> BlueprintConstants.DATA_TYPE_DOUBLE - "List" -> BlueprintConstants.DATA_TYPE_LIST - "Map" -> BlueprintConstants.DATA_TYPE_MAP - "Object", "JsonNode", "ObjectNode", "ArrayNode" -> BlueprintConstants.DATA_TYPE_JSON - else -> simpleName - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintProcessorException.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintProcessorException.kt deleted file mode 100644 index 10a299bd0..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintProcessorException.kt +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 - 2020 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -import org.apache.commons.lang.exception.ExceptionUtils -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogException -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogExceptionFluent -import org.onap.ccsdk.cds.error.catalog.core.ErrorMessage - -/** - * - * - * @author Brinda Santh - */ -open class BlueprintProcessorException : ErrorCatalogException, ErrorCatalogExceptionFluent { - - constructor(message: String, cause: Throwable) : super(message, cause) - constructor(message: String) : super(message) - constructor(cause: Throwable) : super(cause) - constructor(cause: Throwable, message: String, vararg args: Any?) : super(cause, message, args) - constructor(code: Int, cause: Throwable) : super(code, cause) - constructor(code: Int, message: String) : super(code, message) - constructor(code: Int, message: String, cause: Throwable) : super(code, message, cause) - - override fun code(code: Int): BlueprintProcessorException { - return this.updateCode(code) - } - - override fun domain(domain: String): BlueprintProcessorException { - return this.updateDomain(domain) - } - - override fun action(action: String): BlueprintProcessorException { - return this.updateAction(action) - } - - override fun http(type: String): BlueprintProcessorException { - return this.updateHttp(type) - } - - override fun grpc(type: String): BlueprintProcessorException { - return this.updateGrpc(type) - } - - override fun convertToHttp(): BlueprintProcessorException { - return this.inverseToHttp() - } - - override fun convertToGrpc(): BlueprintProcessorException { - return this.inverseToHttp() - } - - override fun payloadMessage(message: String): BlueprintProcessorException { - return this.updatePayloadMessage(message) - } - - override fun addErrorPayloadMessage(message: String): BlueprintProcessorException { - return this.updateErrorPayloadMessage(message) - } - - override fun addSubError(errorMessage: ErrorMessage): BlueprintProcessorException { - return this.updateSubError(errorMessage) - } -} - -class BlueprintRetryException : RuntimeException { - constructor(message: String, cause: Throwable) : super(message, cause) - constructor(message: String) : super(message) - constructor(cause: Throwable) : super(cause) - constructor(cause: Throwable, message: String, vararg args: Any?) : super(format(message, *args), cause) -} - -/** Extension Functions */ - -fun processorException(message: String): BlueprintProcessorException { - return BlueprintProcessorException(message) -} - -fun processorException(message: String, cause: Throwable): BlueprintProcessorException { - return BlueprintProcessorException(message, cause) -} - -fun processorException(cause: Throwable, message: String, vararg args: Any?): BlueprintProcessorException { - return BlueprintProcessorException(cause, message, args) -} - -fun processorException(code: Int, message: String): BlueprintProcessorException { - return processorException(message).code(code) -} - -fun processorException(code: Int, message: String, cause: Throwable): BlueprintProcessorException { - return processorException(message, cause).code(code) -} - -fun processorException(code: Int, cause: Throwable, message: String, vararg args: Any?): BlueprintProcessorException { - return processorException(cause, message, args).code(code) -} - -fun httpProcessorException(type: String, message: String): BlueprintProcessorException { - return processorException(message).http(type) -} - -fun grpcProcessorException(type: String, message: String): BlueprintProcessorException { - return processorException(message).grpc(type) -} - -fun httpProcessorException(type: String, domain: String, message: String): BlueprintProcessorException { - val bluePrintProcessorException = processorException(message).http(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message) -} - -fun grpcProcessorException(type: String, domain: String, message: String): BlueprintProcessorException { - val bluePrintProcessorException = processorException(message).grpc(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message) -} - -fun httpProcessorException(type: String, domain: String, message: String, cause: Throwable): - BlueprintProcessorException { - val bluePrintProcessorException = processorException(message, cause).http(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) - } - -fun grpcProcessorException(type: String, domain: String, message: String, cause: Throwable): - BlueprintProcessorException { - val bluePrintProcessorException = processorException(message, cause).grpc(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) - } - -fun httpProcessorException(type: String, domain: String, message: String, cause: Throwable, vararg args: Any?): - BlueprintProcessorException { - val bluePrintProcessorException = processorException(cause, message, args).http(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) - } - -fun grpcProcessorException(type: String, domain: String, message: String, cause: Throwable, vararg args: Any?): - BlueprintProcessorException { - val bluePrintProcessorException = processorException(cause, message, args).grpc(type) - return bluePrintProcessorException.addDomainAndErrorMessage(domain, message, ExceptionUtils.getRootCauseMessage(cause)) - } - -fun BlueprintProcessorException.updateErrorMessage(domain: String, message: String, cause: String): - BlueprintProcessorException { - return this.addDomainAndErrorMessage(domain, message, cause).domain(domain) - .addErrorPayloadMessage(message) - .payloadMessage(message) - } - -fun BlueprintProcessorException.updateErrorMessage(domain: String, message: String): BlueprintProcessorException { - return this.addDomainAndErrorMessage(domain, message).domain(domain) - .addErrorPayloadMessage(message) - .payloadMessage(message) -} - -private fun BlueprintProcessorException.addDomainAndErrorMessage( - domain: String, - message: String, - cause: String = "" -): BlueprintProcessorException { - return this.addSubError(ErrorMessage(domain, message, cause)).domain(domain) -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintTypes.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintTypes.kt deleted file mode 100644 index cb78ea19f..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintTypes.kt +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core - -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition - -/** - * - * - * @author Brinda Santh - */ -object BlueprintTypes { - - @JvmStatic - val validNodeTypeDerivedFroms: MutableList = arrayListOf( - BlueprintConstants.MODEL_TYPE_NODES_ROOT, - BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW, - BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, - BlueprintConstants.MODEL_TYPE_NODE_VNF, - BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_BUNDLE, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_SCRIPT, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_PYTHON, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_JYTHON, - BlueprintConstants.MODEL_TYPE_NODES_COMPONENT_JAVA_SCRIPT - ) - - @JvmStatic - val validArtifactTypeDerivedFroms: MutableList = arrayListOf( - BlueprintConstants.MODEL_TYPE_ARTIFACTS_ROOT, - BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION - ) - - @JvmStatic - val validDataTypeDerivedFroms: MutableList = arrayListOf( - BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT, - BlueprintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC - ) - - @JvmStatic - val validRelationShipDerivedFroms: MutableList = arrayListOf( - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ATTACH_TO, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROUTES_TO - ) - - @JvmStatic - val validCapabilityTypes: MutableList = arrayListOf( - BlueprintConstants.MODEL_TYPE_CAPABILITIES_ROOT, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_NODE, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_COMPUTE, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETWORK, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_STORAGE, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_PUBLIC, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_ADMIN, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT_DATABASE, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ATTACHMENT, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_OPERATION_SYSTEM, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_BINDABLE, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_CONTENT, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_MAPPING, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_NETCONF, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_RESTCONF, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_SSH, - BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP - ) - - @JvmStatic - fun validModelTypes(): List { - val validTypes: MutableList = arrayListOf() - validTypes.add(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) - validTypes.add(BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) - validTypes.add(BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) - validTypes.add(BlueprintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) - validTypes.add(BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) - return validTypes - } - - @JvmStatic - fun validPropertyTypes(): List { - val validTypes: MutableList = arrayListOf() - validTypes.addAll(validPrimitiveTypes()) - validTypes.addAll(validComplexTypes()) - validTypes.addAll(validCollectionTypes()) - return validTypes - } - - @JvmStatic - fun validPrimitiveTypes(): List { - val validTypes: MutableList = arrayListOf() - validTypes.add(BlueprintConstants.DATA_TYPE_STRING) - validTypes.add(BlueprintConstants.DATA_TYPE_INTEGER) - validTypes.add(BlueprintConstants.DATA_TYPE_FLOAT) - validTypes.add(BlueprintConstants.DATA_TYPE_DOUBLE) - validTypes.add(BlueprintConstants.DATA_TYPE_BOOLEAN) - validTypes.add(BlueprintConstants.DATA_TYPE_TIMESTAMP) - validTypes.add(BlueprintConstants.DATA_TYPE_NULL) - return validTypes - } - - @JvmStatic - fun validComplexTypes(): List { - val validTypes: MutableList = arrayListOf() - validTypes.add(BlueprintConstants.DATA_TYPE_JSON) - validTypes.add(BlueprintConstants.DATA_TYPE_MAP) - return validTypes - } - - @JvmStatic - fun validCollectionTypes(): List { - val validTypes: MutableList = arrayListOf() - validTypes.add(BlueprintConstants.DATA_TYPE_LIST) - return validTypes - } - - @JvmStatic - fun validPrimitiveOrCollectionPrimitive(propertyDefinition: PropertyDefinition): Boolean { - val entrySchema = propertyDefinition.entrySchema?.type ?: BlueprintConstants.DATA_TYPE_NULL - return BlueprintTypes.validPropertyTypes().contains(propertyDefinition.type) && - BlueprintTypes.validPrimitiveTypes().contains(entrySchema) - } - - @JvmStatic - fun validCommands(): List { - return listOf( - BlueprintConstants.EXPRESSION_DSL_REFERENCE, - BlueprintConstants.EXPRESSION_GET_INPUT, - BlueprintConstants.EXPRESSION_GET_ATTRIBUTE, - BlueprintConstants.EXPRESSION_GET_PROPERTY, - BlueprintConstants.EXPRESSION_GET_ARTIFACT, - BlueprintConstants.EXPRESSION_GET_OPERATION_OUTPUT, - BlueprintConstants.EXPRESSION_GET_NODE_OF_TYPE - ) - } - - @JvmStatic - fun rootNodeTypes(): List { - return listOf(BlueprintConstants.MODEL_TYPE_NODES_ROOT) - } - - @JvmStatic - fun rootRelationshipTypes(): List { - return listOf(BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT) - } - - @JvmStatic - fun rootDataTypes(): List { - return listOf(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt index 25abcd30b..ebe682611 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt @@ -113,7 +113,7 @@ fun T.asJsonPrimitive(): JsonNode { is Double -> this.asJsonPrimitive() else -> - throw BlueprintException("$this type is not supported") + throw BluePrintException("$this type is not supported") } } } @@ -121,11 +121,11 @@ fun T.asJsonPrimitive(): JsonNode { /** Based on Blueprint DataType Convert string value to JsonNode Type **/ fun String.asJsonType(bpDataType: String): JsonNode { return when (bpDataType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_STRING -> this.asJsonPrimitive() - BlueprintConstants.DATA_TYPE_BOOLEAN -> this.toBoolean().asJsonPrimitive() - BlueprintConstants.DATA_TYPE_INTEGER -> this.toInt().asJsonPrimitive() - BlueprintConstants.DATA_TYPE_FLOAT -> this.toFloat().asJsonPrimitive() - BlueprintConstants.DATA_TYPE_DOUBLE -> this.toDouble().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_STRING -> this.asJsonPrimitive() + BluePrintConstants.DATA_TYPE_BOOLEAN -> this.toBoolean().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_INTEGER -> this.toInt().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_FLOAT -> this.toFloat().asJsonPrimitive() + BluePrintConstants.DATA_TYPE_DOUBLE -> this.toDouble().asJsonPrimitive() // For List, Map and Complex Types. else -> this.jsonAsJsonType() } @@ -182,7 +182,7 @@ fun Map.castValue(key: String, valueType: KClass): T { if (containsKey(key)) { return get(key) as T } else { - throw BlueprintException("couldn't find the key $key") + throw BluePrintException("couldn't find the key $key") } } @@ -197,7 +197,7 @@ fun JsonNode.asByteArray(): ByteArray { fun JsonNode.asType(clazzType: Class): T { return JacksonUtils.readValue(this, clazzType) - ?: throw BlueprintException("couldn't convert JsonNode of type $clazzType") + ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType") } fun JsonNode.asListOfString(): List { @@ -226,7 +226,7 @@ fun JsonNode.rootFieldsToMap(): MutableMap { } return propertyMap } else { - throw BlueprintException("json node should be Object Node Type") + throw BluePrintException("json node should be Object Node Type") } } @@ -248,19 +248,19 @@ fun MutableMap.putJsonElement(key: String, value: Any) { } fun Map.getAsString(key: String): String { - return this[key]?.asText() ?: throw BlueprintException("couldn't find value for key($key)") + return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)") } fun Map.getAsBoolean(key: String): Boolean { - return this[key]?.asBoolean() ?: throw BlueprintException("couldn't find value for key($key)") + return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)") } fun Map.getAsInt(key: String): Int { - return this[key]?.asInt() ?: throw BlueprintException("couldn't find value for key($key)") + return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)") } fun Map.getAsDouble(key: String): Double { - return this[key]?.asDouble() ?: throw BlueprintException("couldn't find value for key($key)") + return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)") } fun Map.getOptionalAsString(key: String): String? { @@ -285,7 +285,7 @@ inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any) if (value1.equals(value2, ignoreCase = true)) { return true } else { - throw BlueprintException(lazyMessage().toString()) + throw BluePrintException(lazyMessage().toString()) } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt index ca3d815f3..518e9b236 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt @@ -19,7 +19,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.apache.commons.io.FileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils import java.io.File import java.io.InputStream import java.nio.charset.Charset @@ -39,7 +39,7 @@ fun File.reCreateDirs(): File { // this.mkdirs() FileUtils.forceMkdir(this) check(this.exists()) { - throw BlueprintException("failed to re create dir(${this.absolutePath})") + throw BluePrintException("failed to re create dir(${this.absolutePath})") } return this } @@ -52,7 +52,7 @@ fun File.compress(targetZipFileName: String): File { * Compress the current Dir to the target zip file and return the target zip file */ fun File.compress(targetZipFile: File): File { - BlueprintArchiveUtils.compress(this, targetZipFile) + BluePrintArchiveUtils.compress(this, targetZipFile) return targetZipFile } @@ -64,7 +64,7 @@ fun File.deCompress(targetFileName: String): File { * De-Compress the current zip file to the target file and return the target file */ fun File.deCompress(targetFile: File): File { - BlueprintArchiveUtils.deCompress(this, targetFile.path) + BluePrintArchiveUtils.deCompress(this, targetFile.path) return targetFile } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt new file mode 100644 index 000000000..c39442976 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt @@ -0,0 +1,100 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.annotations + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import kotlin.reflect.KClass + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsDataType( + val name: String, + val version: String = BluePrintConstants.DEFAULT_VERSION_NUMBER, + val description: String, + val derivedFrom: String = "tosca.datatypes.root" +) + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsWorkflowInput + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsWorkflowOutput + +@Target(AnnotationTarget.CLASS) +annotation class BluePrintsNodeType( + val propertiesType: KClass<*>, + val attributesType: KClass<*>, + val inputsType: KClass<*>, + val outputsType: KClass<*> +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class BluePrintsProperty( + val name: String = "", + val description: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +@Repeatable +annotation class BluePrintsConstrain() + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class PropertyDefaultValue(val value: String) + +annotation class PropertyValidValue(val value: String) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class InputExpression( + val propertyName: String +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class PropertyExpression( + val modelableEntityName: String = "SELF", + val reqOrCapEntityName: String = "", + val propertyName: String, + val subPropertyName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class AttributeExpression( + val modelableEntityName: String = "SELF", + val reqOrCapEntityName: String = "", + val attributeName: String, + val subAttributeName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class ArtifactExpression( + val modelableEntityName: String = "SELF", + val artifactName: String, + val location: String = "LOCAL_FILE", + val remove: Boolean = false +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class OperationOutputExpression( + val modelableEntityName: String = "SELF", + val interfaceName: String, + val operationName: String, + val propertyName: String, + val subPropertyName: String = "" +) + +@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) +annotation class DSLExpression( + val propertyName: String +) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotations.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotations.kt deleted file mode 100644 index a72860ae2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotations.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.annotations - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import kotlin.reflect.KClass - -@Target(AnnotationTarget.CLASS) -annotation class BlueprintsDataType( - val name: String, - val version: String = BlueprintConstants.DEFAULT_VERSION_NUMBER, - val description: String, - val derivedFrom: String = "tosca.datatypes.root" -) - -@Target(AnnotationTarget.CLASS) -annotation class BlueprintsWorkflowInput - -@Target(AnnotationTarget.CLASS) -annotation class BlueprintsWorkflowOutput - -@Target(AnnotationTarget.CLASS) -annotation class BlueprintsNodeType( - val propertiesType: KClass<*>, - val attributesType: KClass<*>, - val inputsType: KClass<*>, - val outputsType: KClass<*> -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class BlueprintsProperty( - val name: String = "", - val description: String = "" -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -@Repeatable -annotation class BlueprintsConstrain() - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class PropertyDefaultValue(val value: String) - -annotation class PropertyValidValue(val value: String) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class InputExpression( - val propertyName: String -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class PropertyExpression( - val modelableEntityName: String = "SELF", - val reqOrCapEntityName: String = "", - val propertyName: String, - val subPropertyName: String = "" -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class AttributeExpression( - val modelableEntityName: String = "SELF", - val reqOrCapEntityName: String = "", - val attributeName: String, - val subAttributeName: String = "" -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class ArtifactExpression( - val modelableEntityName: String = "SELF", - val artifactName: String, - val location: String = "LOCAL_FILE", - val remove: Boolean = false -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class OperationOutputExpression( - val modelableEntityName: String = "SELF", - val interfaceName: String, - val operationName: String, - val propertyName: String, - val subPropertyName: String = "" -) - -@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY) -annotation class DSLExpression( - val propertyName: String -) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt new file mode 100644 index 000000000..adfbf2905 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt @@ -0,0 +1,29 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.config + +open class BluePrintLoadConfiguration { + + lateinit var blueprintDeployPath: String + lateinit var blueprintArchivePath: String + lateinit var blueprintWorkingPath: String + + var loadBluePrintPaths: String? = null + var loadModeTypePaths: String? = null + var loadResourceDictionaryPaths: String? = null +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BlueprintLoadConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BlueprintLoadConfiguration.kt deleted file mode 100644 index 5176ffefd..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BlueprintLoadConfiguration.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.config - -open class BlueprintLoadConfiguration { - - lateinit var blueprintDeployPath: String - lateinit var blueprintArchivePath: String - lateinit var blueprintWorkingPath: String - - var loadBlueprintPaths: String? = null - var loadModeTypePaths: String? = null - var loadResourceDictionaryPaths: String? = null -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt new file mode 100644 index 000000000..37c128714 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt @@ -0,0 +1,77 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.data + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ObjectNode + +/** + * + * + * @author Brinda Santh + */ +data class ExpressionData( + var isExpression: Boolean = false, + var valueNode: JsonNode, + var expressionNode: ObjectNode? = null, + var dslExpression: DSLExpression? = null, + var inputExpression: InputExpression? = null, + var propertyExpression: PropertyExpression? = null, + var attributeExpression: AttributeExpression? = null, + var artifactExpression: ArtifactExpression? = null, + var operationOutputExpression: OperationOutputExpression? = null, + var command: String? = null +) + +data class InputExpression( + var propertyName: String +) + +data class PropertyExpression( + var modelableEntityName: String = "SELF", + var reqOrCapEntityName: String? = null, + var propertyName: String, + var subPropertyName: String? = null +) + +data class AttributeExpression( + var modelableEntityName: String = "SELF", + var reqOrCapEntityName: String? = null, + var attributeName: String, + var subAttributeName: String? = null +) + +data class ArtifactExpression( + val modelableEntityName: String = "SELF", + val artifactName: String, + val location: String? = "LOCAL_FILE", + val remove: Boolean? = false +) + +data class OperationOutputExpression( + val modelableEntityName: String = "SELF", + val interfaceName: String, + val operationName: String, + val propertyName: String, + var subPropertyName: String? = null +) + +data class DSLExpression( + val propertyName: String +) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt new file mode 100644 index 000000000..bc6cbe426 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt @@ -0,0 +1,182 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.data + +enum class EdgeLabel(val id: String) { + SUCCESS("success"), + FAILURE("failure"), + DEFAULT("*") +} + +enum class EdgeStatus(val id: String) { + NOT_STARTED("not_started"), + EXECUTED("executed"), + SKIPPED("skipped") +} + +enum class NodeStatus(val id: String) { + NOT_STARTED("not_started"), + READY("ready"), + EXECUTING("executing"), + EXECUTED("executed"), + SKIPPED("skipped"), + TERMINATED("terminated") +} + +class Graph { + + val nodes: MutableMap = hashMapOf() + val edges: MutableSet = mutableSetOf() + + fun addNode(value: String): Node { + val node = Node(value) + nodes[value] = node + return node + } + + fun addEdge(source: String, destination: String, label: EdgeLabel) { + if (!nodes.containsKey(source)) { + addNode(source) + } + if (!nodes.containsKey(destination)) { + addNode(destination) + } + val edge = Edge(nodes[source]!!, nodes[destination]!!, label) + if (!edges.contains(edge)) { + edges.add(edge) + nodes[source]!!.edges.add(edge) + } + } + + override fun toString(): String { + val standaloneNodes = nodes.values.filter { node -> edges.all { it.source != node && it.target != node } } + val s = (edges.map { it.toString() } + standaloneNodes.map { it.toString() }).joinToString() + return "[$s]" + } + + fun print(): String { + val buffer = StringBuffer("Nodes :") + nodes.values.forEach { + buffer.append("\n\t$it") + } + buffer.append("\nEdges :") + edges.forEach { + buffer.append("\n\t$it") + } + return buffer.toString() + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other?.javaClass != javaClass) return false + other as Graph + return nodes == other.nodes && edges == other.edges + } + + override fun hashCode() = 31 * nodes.hashCode() + edges.hashCode() + + fun equivalentTo(other: Graph): Boolean { + return nodes == other.nodes && edges.all { edge -> other.edges.any { it.equivalentTo(edge) } } + } + + data class Node(val id: String, var status: NodeStatus = NodeStatus.NOT_STARTED) { + + val edges: MutableList = ArrayList() + + fun neighbors(): List = edges.map { it.target } + + fun neighbors(label: EdgeLabel): List = edges.filter { it.label == label } + .map { it.target } + + fun labelEdges(label: EdgeLabel): List = edges.filter { it.label == label } + + override fun toString() = "$id, Status($status)" + } + + data class Edge( + val source: Node, + val target: Node, + val label: EdgeLabel, + var status: EdgeStatus = EdgeStatus.NOT_STARTED + ) { + + fun equivalentTo(other: Edge) = + (source == other.source && target == other.target) || + (source == other.target && target == other.source) + + override fun toString() = + "${source.id}>${target.id}/$label($status)" + } + + data class TermForm(val nodes: Collection, val edges: List) { + + data class Term(val source: String, val target: String, val label: EdgeLabel) { + + override fun toString() = "Term($source, $target, $label)" + } + } + + data class AdjacencyList(val entries: List>) { + constructor(vararg entries: Entry) : this(entries.asList()) + + override fun toString() = "AdjacencyList(${entries.joinToString()})" + + data class Entry(val node: String, val links: List> = emptyList()) { + constructor(node: String, vararg links: Link) : this(node, links.asList()) + + override fun toString() = "Entry($node, links[${links.joinToString()}])" + } + + data class Link(val node: String, val label: EdgeLabel) { + + override fun toString() = if (label == null) "$node" else "$node/$label" + } + } + + companion object { + + fun labeledDirectedTerms(termForm: TermForm): Graph = + createFromTerms(termForm) { graph, n1, n2, value -> graph.addEdge(n1, n2, value) } + + fun labeledDirectedAdjacent(adjacencyList: AdjacencyList): Graph = + fromAdjacencyList(adjacencyList) { graph, n1, n2, value -> + graph.addEdge(n1, n2, value) + } + + private fun createFromTerms( + termForm: TermForm, + addFunction: (Graph, String, String, EdgeLabel) -> Unit + ): Graph { + val graph = Graph() + termForm.nodes.forEach { graph.addNode(it) } + termForm.edges.forEach { addFunction(graph, it.source, it.target, it.label) } + return graph + } + + private fun fromAdjacencyList( + adjacencyList: AdjacencyList, + addFunction: (Graph, String, String, EdgeLabel) -> Unit + ): Graph { + val graph = Graph() + adjacencyList.entries.forEach { graph.addNode(it.node) } + adjacencyList.entries.forEach { (node, links) -> + links.forEach { addFunction(graph, node, it.node, it.label) } + } + return graph + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt new file mode 100644 index 000000000..9f32d8830 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt @@ -0,0 +1,736 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.data + +import com.fasterxml.jackson.annotation.JsonIgnore +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonPropertyOrder +import com.fasterxml.jackson.databind.JsonNode +import io.swagger.annotations.ApiModelProperty +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType + +/** + * + * + * @author Brinda Santh + */ +open class EntityType { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var version: String = "1.0.0" + var metadata: MutableMap? = null + + @get:JsonProperty("derived_from") + lateinit var derivedFrom: String + var attributes: MutableMap? = null + var properties: MutableMap? = null +} + +/* + 5.3.2 tosca.datatypes.Credential + The Credential type is a complex TOSCA data Type used when describing + authorization credentials used to access network accessible resources. + */ +class Credential { + + @get:JsonIgnore + var id: String? = null + var protocol: String? = null + + @get:JsonProperty("token_type") + lateinit var tokenType: String + lateinit var token: String + var keys: MutableMap? = null + lateinit var user: String +} + +/* +3.5.2 Constraint clause +A constraint clause defines an operation along with one or more compatible values that can be used to define a constraint on a property or parameter’s allowed values when it is defined in a TOSCA Service Template or one of its entities. + */ +class ConstraintClause { + + var equal: JsonNode? = null + + @get:JsonProperty("greater_than") + var greaterThan: JsonNode? = null + + @get:JsonProperty("greater_or_equal") + var greaterOrEqual: JsonNode? = null + + @get:JsonProperty("less_than") + var lessThan: JsonNode? = null + + @get:JsonProperty("less_or_equal") + var lessOrEqual: JsonNode? = null + + @get:JsonProperty("in_range") + var inRange: MutableList? = null + + @get:JsonProperty("valid_values") + var validValues: MutableList? = null + var length: JsonNode? = null + + @get:JsonProperty("min_length") + var minLength: JsonNode? = null + + @get:JsonProperty("max_length") + var maxLength: JsonNode? = null + var pattern: String? = null + var schema: String? = null +} + +/* +3.5.4 Node Filter definition +A node filter definition defines criteria for selection of a TOSCA Node Template based upon the template’s property values, capabilities and capability properties. + */ + +class NodeFilterDefinition { + + var properties: MutableMap? = null + var capabilities: MutableList? = null +} + +/* +3.5.5 Repository definition + A repository definition defines a named external repository which contains deployment + and implementation artifacts that are referenced within the TOSCA Service Template. +*/ +class RepositoryDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + lateinit var url: String + var credential: Credential? = null +} + +/* +3.5.6 Artifact definition +An artifact definition defines a named, typed file that can be associated with Node Type +or Node Template and used by orchestration engine to facilitate deployment and implementation of interface operations. + */ +class ArtifactDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + lateinit var file: String + var repository: String? = null + var description: String? = null + + @get:JsonProperty("deploy_Path") + var deployPath: String? = null + var properties: MutableMap? = null +} + +/* +3.5.7 Import definition +An import definition is used within a TOSCA Service Template to locate and uniquely name +another TOSCA Service Template file which has type and template definitions to be imported (included) +and referenced within another Service Template. + */ +class ImportDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var file: String + var repository: String? = null + + @get:JsonProperty("namespace_uri") + var namespaceUri: String? = null + + @get:JsonProperty("namespace_prefix") + var namespacePrefix: String? = null +} + +/* +3.5.8 Property definition A property definition defines a named, typed value and related data that can be associated with an +entity defined in this specification (e.g., Node Types, Relationship Types, Capability Types, etc.). +Properties are used by template authors to provide input values to TOSCA entities which indicate their “desired state” when they are +instantiated. The value of a property can be retrieved using the get_property function within TOSCA Service Templates. + */ +class PropertyDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var required: Boolean? = null + lateinit var type: String + + @get:JsonProperty("input-param") + var inputparam: Boolean? = null + + @get:JsonProperty("default") + var defaultValue: JsonNode? = null + var status: String? = null + var constraints: MutableList? = null + + @get:JsonProperty("entry_schema") + var entrySchema: EntrySchema? = null + + @get:JsonProperty("external-schema") + var externalSchema: String? = null + var metadata: MutableMap? = null + + // Mainly used in Workflow Outputs + @get:ApiModelProperty(notes = "Property Value, It may be Expression or Json type values") + var value: JsonNode? = null +} + +/* +3.5.10 Attribute definition + +An attribute definition defines a named, typed value that can be associated with an entity defined in this +specification (e.g., a Node, Relationship or Capability Type). Specifically, it is used to expose the +“actual state” of some property of a TOSCA entity after it has been deployed and instantiated +(as set by the TOSCA orchestrator). Attribute values can be retrieved via the get_attribute function +from the instance model and used as values to other entities within TOSCA Service Templates. + */ + +class AttributeDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var required: Boolean? = null + lateinit var type: String + + @JsonProperty("default") + var defaultValue: JsonNode? = null + var status: String? = null + var constraints: MutableList? = null + + @JsonProperty("entry_schema") + var entrySchema: EntrySchema? = null + + // Mainly used in DSL definitions + @get:ApiModelProperty(notes = "Attribute Value, It may be Expression or Json type values") + var value: JsonNode? = null +} + +/* +3.5.13 Operation definition +An operation definition defines a named function or procedure that can be bound to an implementation artifact (e.g., a script). + */ +class OperationDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var implementation: Implementation? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} + +class Implementation { + + var primary: String? = null + var dependencies: MutableList? = null + + @get:JsonProperty("operation_host") + var operationHost: String = BluePrintConstants.PROPERTY_SELF + + // Timeout value in seconds + var timeout: Int = 180 + var lock: LockAssignment? = null +} + +class LockAssignment { + + lateinit var key: JsonNode + var acquireTimeout: JsonNode = Integer(180).asJsonType() +} + +/* +3.5.14 Interface definition +An interface definition defines a named interface that can be associated with a Node or Relationship Type + */ +class InterfaceDefinition { + + @get:JsonIgnore + var id: String? = null + var type: String? = null + var operations: MutableMap? = null + var inputs: MutableMap? = null +} + +/* +3.5.15 Event Filter definition +An event filter definition defines criteria for selection of an attribute, for the purpose of monitoring it, within a TOSCA entity, or one its capabilities. + */ +class EventFilterDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var node: String + var requirement: String? = null + var capability: String? = null +} + +/* +3.5.16 Trigger definition TODO +A trigger definition defines the event, condition and action that is used to “trigger” a policy it is associated with. + */ +class TriggerDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + + @get:JsonProperty("event_type") + lateinit var eventType: String + + @get:JsonProperty("target_filter") + var targetFilter: EventFilterDefinition? = null + var condition: ConditionClause? = null + var constraint: ConditionClause? = null + var method: String? = null + lateinit var action: String +} + +/* + 3.5.17 Workflow activity definition + A workflow activity defines an operation to be performed in a TOSCA workflow. Activities allows to: + · Delegate the workflow for a node expected to be provided by the orchestrator + · Set the state of a node + · Call an operation defined on a TOSCA interface of a node, relationship or group + · Inline another workflow defined in the topology (to allow reusability) + */ +class Activity { + + var delegate: String? = null + + @get:JsonProperty("set_state") + var setState: String? = null + + @get:JsonProperty("call_operation") + var callOperation: String? = null + var inlines: ArrayList? = null +} + +/* +3.5.20 Workflow precondition definition +A workflow condition can be used as a filter or precondition to check if a workflow can be processed or not based on the state of the instances of a TOSCA topology deployment. When not met, the workflow will not be triggered. + */ +class PreConditionDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var target: String + + @get:JsonProperty("target_relationship") + lateinit var targetRelationship: String + lateinit var condition: ArrayList +} + +/* +3.5.21 Workflow step definition +A workflow step allows to define one or multiple sequenced activities in a workflow and how they are connected to other steps in the workflow. They are the building blocks of a declarative workflow. + */ +class Step { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var target: String? = null + + @JsonProperty("target_relationship") + var targetRelationship: String? = null + + @JsonProperty("operation_host") + var operationHost: String? = null + var activities: ArrayList? = null + + @get:JsonProperty("on_success") + var onSuccess: ArrayList? = null + + @get:JsonProperty("on_failure") + var onFailure: ArrayList? = null +} + +/* +3.6.2 Capability definition +A capability definition defines a named, typed set of data that can be associated with Node Type or Node Template to describe a transparent capability or feature of the software component the node describes. + */ + +class CapabilityDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var properties: MutableMap? = null + + @get:JsonProperty("valid_source_types") + var validSourceTypes: MutableList? = null + var occurrences: MutableList? = null +} + +/* +3.6.3 Requirement definition +The Requirement definition describes a named requirement (dependencies) of a TOSCA Node Type or Node template which needs to be fulfilled by a matching Capability definition declared by another TOSCA modelable entity. The requirement definition may itself include the specific name of the fulfilling entity (explicitly) or provide an abstract type, along with additional filtering characteristics, that a TOSCA orchestrator can use to fulfill the capability at runtime (implicitly). + */ +class RequirementDefinition { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var capability: String? = null + var node: String? = null + var relationship: String? = null + var occurrences: MutableList? = null +} + +/* +3.6.4 Artifact Type +An Artifact Type is a reusable entity that defines the type of one or more files that are used to define implementation or deployment artifacts that are referenced by nodes or relationships on their operations. + */ +class ArtifactType : EntityType() { + + @get:JsonProperty("mime_type") + var mimeType: String? = null + + @get:JsonProperty("file_ext") + var fileExt: MutableList? = null +} + +/* +3.6.6 Data Type +A Data Type definition defines the schema for new named datatypes in TOSCA. + */ + +class DataType : EntityType() { + + var constraints: MutableList? = null +} + +/* +3.6.9 Node Type +A Node Type is a reusable entity that defines the type of one or more Node Templates. As such, a Node Type defines the structure of observable properties via a Properties Definition, the Requirements and Capabilities of the node as well as its supported interfaces. + + */ + +class NodeType : EntityType() { + + var capabilities: MutableMap? = null + var requirements: MutableMap? = null + var interfaces: MutableMap? = null + var artifacts: MutableMap? = null +} + +/* +3.6.8 Requirement Type +A Requirement Type is a reusable entity that describes a kind of requirement that a Node Type can declare to expose. +The TOSCA Simple Profile seeks to simplify the need for declaring specific Requirement Types +from nodes and instead rely upon nodes declaring their features sets using TOSCA Capability Types +along with a named Feature notation. + */ + +class RequirementType : EntityType() { + + var requirements: MutableMap? = null + var capabilities: MutableMap? = null + var interfaces: MutableMap? = null + var artifacts: MutableMap? = null +} + +/* +3.6.10 Relationship Type +A Relationship Type is a reusable entity that defines the type of one or more relationships between Node Types or Node Templates. +*/ + +class RelationshipType : EntityType() { + + var interfaces: MutableMap? = null + + @get:JsonProperty("valid_target_types") + var validTargetTypes: MutableList? = null +} + +/* +3.6.11 Group Type +A Group Type defines logical grouping types for nodes, typically for different management purposes. +Groups can effectively be viewed as logical nodes that are not part of the physical deployment topology + of an application, yet can have capabilities and the ability to attach policies and interfaces + that can be applied (depending on the group type) to its member nodes. + */ + +class GroupType : EntityType() { + + var members: MutableList? = null + var requirements: ArrayList? = null + var capabilities: MutableMap? = null + var interfaces: MutableMap? = null +} + +/* + 3.6.12 Policy Type + A Policy Type defines a type of requirement that affects or governs an application or service’s + topology at some stage of its lifecycle, but is not explicitly part of the topology itself + (i.e., it does not prevent the application or service from being deployed or run if it did not exist). + */ +class PolicyType : EntityType() { + + lateinit var targets: MutableList +} + +/* +3.7.1 Capability assignment +A capability assignment allows node template authors to assign values to properties and attributes for a named capability definition that is part of a Node Template’s type definition. + */ +class CapabilityAssignment { + + @get:JsonIgnore + var id: String? = null + var attributes: MutableMap? = null + var properties: MutableMap? = null +} + +/* +3.7.4 Relationship Template +A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. + */ +class GroupDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var metadata: MutableMap? = null + var properties: MutableMap? = null + var members = ArrayList() + var interfaces: MutableMap? = null +} + +/* +3.7.6 Policy definition +A policy definition defines a policy that can be associated with a TOSCA topology or top-level entity definition (e.g., group definition, node template, etc.). + */ +class PolicyDefinition { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var metadata: MutableMap? = null + var properties: MutableMap? = null + var targets: MutableList? = null +} + +/* +3.8 Topology Template definition +This section defines the topology template of a cloud application. The main ingredients of the topology template are node templates representing components of the application and relationship templates representing links between the components. These elements are defined in the nested node_templates section and the nested relationship_templates sections, respectively. Furthermore, a topology template allows for defining input parameters, output parameters as well as grouping of node templates. + */ +class TopologyTemplate { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var inputs: MutableMap? = null + + @get:JsonProperty("node_templates") + var nodeTemplates: MutableMap? = null + + @get:JsonProperty("relationship_templates") + var relationshipTemplates: MutableMap? = null + var policies: MutableMap? = null + var outputs: MutableMap? = null + + @get:JsonProperty("substitution_mappings") + var substitutionMappings: Any? = null + var workflows: MutableMap? = null +} + +class SubstitutionMapping { + + @get:JsonProperty("node_type") + lateinit var nodeType: String + lateinit var capabilities: ArrayList + lateinit var requirements: ArrayList +} + +class EntrySchema { + + lateinit var type: String + var constraints: MutableList? = null +} + +class InterfaceAssignment { + + @get:JsonIgnore + var id: String? = null + var operations: MutableMap? = null + var inputs: MutableMap? = null +} + +/* +3.7.3 Node Template +A Node Template specifies the occurrence of a manageable software component as part of an application’s topology model which is defined in a TOSCA Service Template. A Node template is an instance of a specified Node Type and can provide customized properties, constraints or operations which override the defaults provided by its Node Type and its implementations. + */ + +open class NodeTemplate { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + lateinit var type: String + var metadata: MutableMap? = null + var directives: MutableList? = null + + // @get:JsonSerialize(using = PropertyDefinitionValueSerializer::class) + var properties: MutableMap? = null + var attributes: MutableMap? = null + var capabilities: MutableMap? = null + var requirements: MutableMap? = null + var interfaces: MutableMap? = null + var artifacts: MutableMap? = null + + @get:JsonProperty("node_filter") + var nodeFilter: NodeFilterDefinition? = null + var copy: String? = null +} + +class OperationAssignment { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var implementation: Implementation? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} + +/* +3.7.4 Relationship Template +A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. + */ + +class RelationshipTemplate { + + @get:JsonIgnore + var id: String? = null + lateinit var type: String + var description: String? = null + var metadata: MutableMap? = null + var properties: MutableMap? = null + var attributes: MutableMap? = null + var interfaces: MutableMap? = null + var copy: String? = null +} + +/* +3.7.2 Requirement assignment +A Requirement assignment allows template authors to provide either concrete names of TOSCA templates or provide abstract selection criteria for providers to use to find matching TOSCA templates that are used to fulfill a named requirement’s declared TOSCA Node Type. + */ + +class RequirementAssignment { + + @get:JsonIgnore + var id: String? = null + var capability: String? = null + var node: String? = null + + // Relationship Type or Relationship Template + var relationship: String? = null +} + +class Workflow { + + @get:JsonIgnore + var id: String? = null + var description: String? = null + var steps: MutableMap? = null + var preconditions: ArrayList? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} + +class ConditionClause { + + var and: ArrayList>? = null + var or: ArrayList>? = null + + @get:JsonProperty("assert") + var assertConditions: ArrayList>? = null +} + +/* +3.9 Service Template definition +A TOSCA Service Template (YAML) document contains element definitions of building blocks for cloud application, or complete models of cloud applications. This section describes the top-level structural elements (TOSCA keynames) along with their grammars, which are allowed to appear in a TOSCA Service Template document. + */ + +@JsonPropertyOrder( + value = [ + "toscaDefinitionsVersion", "description", "metadata", "imports", "dsl_definitions", + "topologyTemplate" + ] +) +class ServiceTemplate : Cloneable { + + @get:JsonIgnore + var id: String? = null + + @get:JsonProperty("tosca_definitions_version") + var toscaDefinitionsVersion: String = "controller_blueprint_1_0_0" + var metadata: MutableMap? = null + var description: String? = null + + @get:JsonProperty("dsl_definitions") + var dslDefinitions: MutableMap? = null + var repositories: MutableMap? = null + var imports: MutableList? = null + + @get:JsonProperty("artifact_types") + var artifactTypes: MutableMap? = null + + @get:JsonProperty("data_types") + var dataTypes: MutableMap? = null + + @get:JsonProperty("relationship_types") + var relationshipTypes: MutableMap? = null + + @get:JsonProperty("node_types") + var nodeTypes: MutableMap? = null + + @get:JsonProperty("policy_types") + var policyTypes: MutableMap? = null + + @get:JsonProperty("topology_template") + var topologyTemplate: TopologyTemplate? = null + + public override fun clone(): ServiceTemplate { + return super.clone() as ServiceTemplate + } +} + +class ToscaMetaData { + + lateinit var toscaMetaFileVersion: String + lateinit var csarVersion: String + lateinit var createdBy: String + lateinit var entityDefinitions: String + lateinit var templateName: String + lateinit var templateVersion: String + lateinit var templateTags: String + var templateType: String = BluePrintConstants.BLUEPRINT_TYPE_DEFAULT +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintExpressionData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintExpressionData.kt deleted file mode 100644 index 37c128714..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintExpressionData.kt +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@file:Suppress("unused") - -package org.onap.ccsdk.cds.controllerblueprints.core.data - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ObjectNode - -/** - * - * - * @author Brinda Santh - */ -data class ExpressionData( - var isExpression: Boolean = false, - var valueNode: JsonNode, - var expressionNode: ObjectNode? = null, - var dslExpression: DSLExpression? = null, - var inputExpression: InputExpression? = null, - var propertyExpression: PropertyExpression? = null, - var attributeExpression: AttributeExpression? = null, - var artifactExpression: ArtifactExpression? = null, - var operationOutputExpression: OperationOutputExpression? = null, - var command: String? = null -) - -data class InputExpression( - var propertyName: String -) - -data class PropertyExpression( - var modelableEntityName: String = "SELF", - var reqOrCapEntityName: String? = null, - var propertyName: String, - var subPropertyName: String? = null -) - -data class AttributeExpression( - var modelableEntityName: String = "SELF", - var reqOrCapEntityName: String? = null, - var attributeName: String, - var subAttributeName: String? = null -) - -data class ArtifactExpression( - val modelableEntityName: String = "SELF", - val artifactName: String, - val location: String? = "LOCAL_FILE", - val remove: Boolean? = false -) - -data class OperationOutputExpression( - val modelableEntityName: String = "SELF", - val interfaceName: String, - val operationName: String, - val propertyName: String, - var subPropertyName: String? = null -) - -data class DSLExpression( - val propertyName: String -) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintGraph.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintGraph.kt deleted file mode 100644 index bc6cbe426..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintGraph.kt +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.data - -enum class EdgeLabel(val id: String) { - SUCCESS("success"), - FAILURE("failure"), - DEFAULT("*") -} - -enum class EdgeStatus(val id: String) { - NOT_STARTED("not_started"), - EXECUTED("executed"), - SKIPPED("skipped") -} - -enum class NodeStatus(val id: String) { - NOT_STARTED("not_started"), - READY("ready"), - EXECUTING("executing"), - EXECUTED("executed"), - SKIPPED("skipped"), - TERMINATED("terminated") -} - -class Graph { - - val nodes: MutableMap = hashMapOf() - val edges: MutableSet = mutableSetOf() - - fun addNode(value: String): Node { - val node = Node(value) - nodes[value] = node - return node - } - - fun addEdge(source: String, destination: String, label: EdgeLabel) { - if (!nodes.containsKey(source)) { - addNode(source) - } - if (!nodes.containsKey(destination)) { - addNode(destination) - } - val edge = Edge(nodes[source]!!, nodes[destination]!!, label) - if (!edges.contains(edge)) { - edges.add(edge) - nodes[source]!!.edges.add(edge) - } - } - - override fun toString(): String { - val standaloneNodes = nodes.values.filter { node -> edges.all { it.source != node && it.target != node } } - val s = (edges.map { it.toString() } + standaloneNodes.map { it.toString() }).joinToString() - return "[$s]" - } - - fun print(): String { - val buffer = StringBuffer("Nodes :") - nodes.values.forEach { - buffer.append("\n\t$it") - } - buffer.append("\nEdges :") - edges.forEach { - buffer.append("\n\t$it") - } - return buffer.toString() - } - - override fun equals(other: Any?): Boolean { - if (this === other) return true - if (other?.javaClass != javaClass) return false - other as Graph - return nodes == other.nodes && edges == other.edges - } - - override fun hashCode() = 31 * nodes.hashCode() + edges.hashCode() - - fun equivalentTo(other: Graph): Boolean { - return nodes == other.nodes && edges.all { edge -> other.edges.any { it.equivalentTo(edge) } } - } - - data class Node(val id: String, var status: NodeStatus = NodeStatus.NOT_STARTED) { - - val edges: MutableList = ArrayList() - - fun neighbors(): List = edges.map { it.target } - - fun neighbors(label: EdgeLabel): List = edges.filter { it.label == label } - .map { it.target } - - fun labelEdges(label: EdgeLabel): List = edges.filter { it.label == label } - - override fun toString() = "$id, Status($status)" - } - - data class Edge( - val source: Node, - val target: Node, - val label: EdgeLabel, - var status: EdgeStatus = EdgeStatus.NOT_STARTED - ) { - - fun equivalentTo(other: Edge) = - (source == other.source && target == other.target) || - (source == other.target && target == other.source) - - override fun toString() = - "${source.id}>${target.id}/$label($status)" - } - - data class TermForm(val nodes: Collection, val edges: List) { - - data class Term(val source: String, val target: String, val label: EdgeLabel) { - - override fun toString() = "Term($source, $target, $label)" - } - } - - data class AdjacencyList(val entries: List>) { - constructor(vararg entries: Entry) : this(entries.asList()) - - override fun toString() = "AdjacencyList(${entries.joinToString()})" - - data class Entry(val node: String, val links: List> = emptyList()) { - constructor(node: String, vararg links: Link) : this(node, links.asList()) - - override fun toString() = "Entry($node, links[${links.joinToString()}])" - } - - data class Link(val node: String, val label: EdgeLabel) { - - override fun toString() = if (label == null) "$node" else "$node/$label" - } - } - - companion object { - - fun labeledDirectedTerms(termForm: TermForm): Graph = - createFromTerms(termForm) { graph, n1, n2, value -> graph.addEdge(n1, n2, value) } - - fun labeledDirectedAdjacent(adjacencyList: AdjacencyList): Graph = - fromAdjacencyList(adjacencyList) { graph, n1, n2, value -> - graph.addEdge(n1, n2, value) - } - - private fun createFromTerms( - termForm: TermForm, - addFunction: (Graph, String, String, EdgeLabel) -> Unit - ): Graph { - val graph = Graph() - termForm.nodes.forEach { graph.addNode(it) } - termForm.edges.forEach { addFunction(graph, it.source, it.target, it.label) } - return graph - } - - private fun fromAdjacencyList( - adjacencyList: AdjacencyList, - addFunction: (Graph, String, String, EdgeLabel) -> Unit - ): Graph { - val graph = Graph() - adjacencyList.entries.forEach { graph.addNode(it.node) } - adjacencyList.entries.forEach { (node, links) -> - links.forEach { addFunction(graph, node, it.node, it.label) } - } - return graph - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintModel.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintModel.kt deleted file mode 100644 index 49736c18b..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintModel.kt +++ /dev/null @@ -1,736 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018-2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@file:Suppress("unused") - -package org.onap.ccsdk.cds.controllerblueprints.core.data - -import com.fasterxml.jackson.annotation.JsonIgnore -import com.fasterxml.jackson.annotation.JsonProperty -import com.fasterxml.jackson.annotation.JsonPropertyOrder -import com.fasterxml.jackson.databind.JsonNode -import io.swagger.annotations.ApiModelProperty -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType - -/** - * - * - * @author Brinda Santh - */ -open class EntityType { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var version: String = "1.0.0" - var metadata: MutableMap? = null - - @get:JsonProperty("derived_from") - lateinit var derivedFrom: String - var attributes: MutableMap? = null - var properties: MutableMap? = null -} - -/* - 5.3.2 tosca.datatypes.Credential - The Credential type is a complex TOSCA data Type used when describing - authorization credentials used to access network accessible resources. - */ -class Credential { - - @get:JsonIgnore - var id: String? = null - var protocol: String? = null - - @get:JsonProperty("token_type") - lateinit var tokenType: String - lateinit var token: String - var keys: MutableMap? = null - lateinit var user: String -} - -/* -3.5.2 Constraint clause -A constraint clause defines an operation along with one or more compatible values that can be used to define a constraint on a property or parameter’s allowed values when it is defined in a TOSCA Service Template or one of its entities. - */ -class ConstraintClause { - - var equal: JsonNode? = null - - @get:JsonProperty("greater_than") - var greaterThan: JsonNode? = null - - @get:JsonProperty("greater_or_equal") - var greaterOrEqual: JsonNode? = null - - @get:JsonProperty("less_than") - var lessThan: JsonNode? = null - - @get:JsonProperty("less_or_equal") - var lessOrEqual: JsonNode? = null - - @get:JsonProperty("in_range") - var inRange: MutableList? = null - - @get:JsonProperty("valid_values") - var validValues: MutableList? = null - var length: JsonNode? = null - - @get:JsonProperty("min_length") - var minLength: JsonNode? = null - - @get:JsonProperty("max_length") - var maxLength: JsonNode? = null - var pattern: String? = null - var schema: String? = null -} - -/* -3.5.4 Node Filter definition -A node filter definition defines criteria for selection of a TOSCA Node Template based upon the template’s property values, capabilities and capability properties. - */ - -class NodeFilterDefinition { - - var properties: MutableMap? = null - var capabilities: MutableList? = null -} - -/* -3.5.5 Repository definition - A repository definition defines a named external repository which contains deployment - and implementation artifacts that are referenced within the TOSCA Service Template. -*/ -class RepositoryDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - lateinit var url: String - var credential: Credential? = null -} - -/* -3.5.6 Artifact definition -An artifact definition defines a named, typed file that can be associated with Node Type -or Node Template and used by orchestration engine to facilitate deployment and implementation of interface operations. - */ -class ArtifactDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var type: String - lateinit var file: String - var repository: String? = null - var description: String? = null - - @get:JsonProperty("deploy_Path") - var deployPath: String? = null - var properties: MutableMap? = null -} - -/* -3.5.7 Import definition -An import definition is used within a TOSCA Service Template to locate and uniquely name -another TOSCA Service Template file which has type and template definitions to be imported (included) -and referenced within another Service Template. - */ -class ImportDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var file: String - var repository: String? = null - - @get:JsonProperty("namespace_uri") - var namespaceUri: String? = null - - @get:JsonProperty("namespace_prefix") - var namespacePrefix: String? = null -} - -/* -3.5.8 Property definition A property definition defines a named, typed value and related data that can be associated with an -entity defined in this specification (e.g., Node Types, Relationship Types, Capability Types, etc.). -Properties are used by template authors to provide input values to TOSCA entities which indicate their “desired state” when they are -instantiated. The value of a property can be retrieved using the get_property function within TOSCA Service Templates. - */ -class PropertyDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var required: Boolean? = null - lateinit var type: String - - @get:JsonProperty("input-param") - var inputparam: Boolean? = null - - @get:JsonProperty("default") - var defaultValue: JsonNode? = null - var status: String? = null - var constraints: MutableList? = null - - @get:JsonProperty("entry_schema") - var entrySchema: EntrySchema? = null - - @get:JsonProperty("external-schema") - var externalSchema: String? = null - var metadata: MutableMap? = null - - // Mainly used in Workflow Outputs - @get:ApiModelProperty(notes = "Property Value, It may be Expression or Json type values") - var value: JsonNode? = null -} - -/* -3.5.10 Attribute definition - -An attribute definition defines a named, typed value that can be associated with an entity defined in this -specification (e.g., a Node, Relationship or Capability Type). Specifically, it is used to expose the -“actual state” of some property of a TOSCA entity after it has been deployed and instantiated -(as set by the TOSCA orchestrator). Attribute values can be retrieved via the get_attribute function -from the instance model and used as values to other entities within TOSCA Service Templates. - */ - -class AttributeDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var required: Boolean? = null - lateinit var type: String - - @JsonProperty("default") - var defaultValue: JsonNode? = null - var status: String? = null - var constraints: MutableList? = null - - @JsonProperty("entry_schema") - var entrySchema: EntrySchema? = null - - // Mainly used in DSL definitions - @get:ApiModelProperty(notes = "Attribute Value, It may be Expression or Json type values") - var value: JsonNode? = null -} - -/* -3.5.13 Operation definition -An operation definition defines a named function or procedure that can be bound to an implementation artifact (e.g., a script). - */ -class OperationDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var implementation: Implementation? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} - -class Implementation { - - var primary: String? = null - var dependencies: MutableList? = null - - @get:JsonProperty("operation_host") - var operationHost: String = BlueprintConstants.PROPERTY_SELF - - // Timeout value in seconds - var timeout: Int = 180 - var lock: LockAssignment? = null -} - -class LockAssignment { - - lateinit var key: JsonNode - var acquireTimeout: JsonNode = Integer(180).asJsonType() -} - -/* -3.5.14 Interface definition -An interface definition defines a named interface that can be associated with a Node or Relationship Type - */ -class InterfaceDefinition { - - @get:JsonIgnore - var id: String? = null - var type: String? = null - var operations: MutableMap? = null - var inputs: MutableMap? = null -} - -/* -3.5.15 Event Filter definition -An event filter definition defines criteria for selection of an attribute, for the purpose of monitoring it, within a TOSCA entity, or one its capabilities. - */ -class EventFilterDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var node: String - var requirement: String? = null - var capability: String? = null -} - -/* -3.5.16 Trigger definition TODO -A trigger definition defines the event, condition and action that is used to “trigger” a policy it is associated with. - */ -class TriggerDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - - @get:JsonProperty("event_type") - lateinit var eventType: String - - @get:JsonProperty("target_filter") - var targetFilter: EventFilterDefinition? = null - var condition: ConditionClause? = null - var constraint: ConditionClause? = null - var method: String? = null - lateinit var action: String -} - -/* - 3.5.17 Workflow activity definition - A workflow activity defines an operation to be performed in a TOSCA workflow. Activities allows to: - · Delegate the workflow for a node expected to be provided by the orchestrator - · Set the state of a node - · Call an operation defined on a TOSCA interface of a node, relationship or group - · Inline another workflow defined in the topology (to allow reusability) - */ -class Activity { - - var delegate: String? = null - - @get:JsonProperty("set_state") - var setState: String? = null - - @get:JsonProperty("call_operation") - var callOperation: String? = null - var inlines: ArrayList? = null -} - -/* -3.5.20 Workflow precondition definition -A workflow condition can be used as a filter or precondition to check if a workflow can be processed or not based on the state of the instances of a TOSCA topology deployment. When not met, the workflow will not be triggered. - */ -class PreConditionDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var target: String - - @get:JsonProperty("target_relationship") - lateinit var targetRelationship: String - lateinit var condition: ArrayList -} - -/* -3.5.21 Workflow step definition -A workflow step allows to define one or multiple sequenced activities in a workflow and how they are connected to other steps in the workflow. They are the building blocks of a declarative workflow. - */ -class Step { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var target: String? = null - - @JsonProperty("target_relationship") - var targetRelationship: String? = null - - @JsonProperty("operation_host") - var operationHost: String? = null - var activities: ArrayList? = null - - @get:JsonProperty("on_success") - var onSuccess: ArrayList? = null - - @get:JsonProperty("on_failure") - var onFailure: ArrayList? = null -} - -/* -3.6.2 Capability definition -A capability definition defines a named, typed set of data that can be associated with Node Type or Node Template to describe a transparent capability or feature of the software component the node describes. - */ - -class CapabilityDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var type: String - var description: String? = null - var properties: MutableMap? = null - - @get:JsonProperty("valid_source_types") - var validSourceTypes: MutableList? = null - var occurrences: MutableList? = null -} - -/* -3.6.3 Requirement definition -The Requirement definition describes a named requirement (dependencies) of a TOSCA Node Type or Node template which needs to be fulfilled by a matching Capability definition declared by another TOSCA modelable entity. The requirement definition may itself include the specific name of the fulfilling entity (explicitly) or provide an abstract type, along with additional filtering characteristics, that a TOSCA orchestrator can use to fulfill the capability at runtime (implicitly). - */ -class RequirementDefinition { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var capability: String? = null - var node: String? = null - var relationship: String? = null - var occurrences: MutableList? = null -} - -/* -3.6.4 Artifact Type -An Artifact Type is a reusable entity that defines the type of one or more files that are used to define implementation or deployment artifacts that are referenced by nodes or relationships on their operations. - */ -class ArtifactType : EntityType() { - - @get:JsonProperty("mime_type") - var mimeType: String? = null - - @get:JsonProperty("file_ext") - var fileExt: MutableList? = null -} - -/* -3.6.6 Data Type -A Data Type definition defines the schema for new named datatypes in TOSCA. - */ - -class DataType : EntityType() { - - var constraints: MutableList? = null -} - -/* -3.6.9 Node Type -A Node Type is a reusable entity that defines the type of one or more Node Templates. As such, a Node Type defines the structure of observable properties via a Properties Definition, the Requirements and Capabilities of the node as well as its supported interfaces. - - */ - -class NodeType : EntityType() { - - var capabilities: MutableMap? = null - var requirements: MutableMap? = null - var interfaces: MutableMap? = null - var artifacts: MutableMap? = null -} - -/* -3.6.8 Requirement Type -A Requirement Type is a reusable entity that describes a kind of requirement that a Node Type can declare to expose. -The TOSCA Simple Profile seeks to simplify the need for declaring specific Requirement Types -from nodes and instead rely upon nodes declaring their features sets using TOSCA Capability Types -along with a named Feature notation. - */ - -class RequirementType : EntityType() { - - var requirements: MutableMap? = null - var capabilities: MutableMap? = null - var interfaces: MutableMap? = null - var artifacts: MutableMap? = null -} - -/* -3.6.10 Relationship Type -A Relationship Type is a reusable entity that defines the type of one or more relationships between Node Types or Node Templates. -*/ - -class RelationshipType : EntityType() { - - var interfaces: MutableMap? = null - - @get:JsonProperty("valid_target_types") - var validTargetTypes: MutableList? = null -} - -/* -3.6.11 Group Type -A Group Type defines logical grouping types for nodes, typically for different management purposes. -Groups can effectively be viewed as logical nodes that are not part of the physical deployment topology - of an application, yet can have capabilities and the ability to attach policies and interfaces - that can be applied (depending on the group type) to its member nodes. - */ - -class GroupType : EntityType() { - - var members: MutableList? = null - var requirements: ArrayList? = null - var capabilities: MutableMap? = null - var interfaces: MutableMap? = null -} - -/* - 3.6.12 Policy Type - A Policy Type defines a type of requirement that affects or governs an application or service’s - topology at some stage of its lifecycle, but is not explicitly part of the topology itself - (i.e., it does not prevent the application or service from being deployed or run if it did not exist). - */ -class PolicyType : EntityType() { - - lateinit var targets: MutableList -} - -/* -3.7.1 Capability assignment -A capability assignment allows node template authors to assign values to properties and attributes for a named capability definition that is part of a Node Template’s type definition. - */ -class CapabilityAssignment { - - @get:JsonIgnore - var id: String? = null - var attributes: MutableMap? = null - var properties: MutableMap? = null -} - -/* -3.7.4 Relationship Template -A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. - */ -class GroupDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var type: String - var description: String? = null - var metadata: MutableMap? = null - var properties: MutableMap? = null - var members = ArrayList() - var interfaces: MutableMap? = null -} - -/* -3.7.6 Policy definition -A policy definition defines a policy that can be associated with a TOSCA topology or top-level entity definition (e.g., group definition, node template, etc.). - */ -class PolicyDefinition { - - @get:JsonIgnore - var id: String? = null - lateinit var type: String - var description: String? = null - var metadata: MutableMap? = null - var properties: MutableMap? = null - var targets: MutableList? = null -} - -/* -3.8 Topology Template definition -This section defines the topology template of a cloud application. The main ingredients of the topology template are node templates representing components of the application and relationship templates representing links between the components. These elements are defined in the nested node_templates section and the nested relationship_templates sections, respectively. Furthermore, a topology template allows for defining input parameters, output parameters as well as grouping of node templates. - */ -class TopologyTemplate { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var inputs: MutableMap? = null - - @get:JsonProperty("node_templates") - var nodeTemplates: MutableMap? = null - - @get:JsonProperty("relationship_templates") - var relationshipTemplates: MutableMap? = null - var policies: MutableMap? = null - var outputs: MutableMap? = null - - @get:JsonProperty("substitution_mappings") - var substitutionMappings: Any? = null - var workflows: MutableMap? = null -} - -class SubstitutionMapping { - - @get:JsonProperty("node_type") - lateinit var nodeType: String - lateinit var capabilities: ArrayList - lateinit var requirements: ArrayList -} - -class EntrySchema { - - lateinit var type: String - var constraints: MutableList? = null -} - -class InterfaceAssignment { - - @get:JsonIgnore - var id: String? = null - var operations: MutableMap? = null - var inputs: MutableMap? = null -} - -/* -3.7.3 Node Template -A Node Template specifies the occurrence of a manageable software component as part of an application’s topology model which is defined in a TOSCA Service Template. A Node template is an instance of a specified Node Type and can provide customized properties, constraints or operations which override the defaults provided by its Node Type and its implementations. - */ - -open class NodeTemplate { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - lateinit var type: String - var metadata: MutableMap? = null - var directives: MutableList? = null - - // @get:JsonSerialize(using = PropertyDefinitionValueSerializer::class) - var properties: MutableMap? = null - var attributes: MutableMap? = null - var capabilities: MutableMap? = null - var requirements: MutableMap? = null - var interfaces: MutableMap? = null - var artifacts: MutableMap? = null - - @get:JsonProperty("node_filter") - var nodeFilter: NodeFilterDefinition? = null - var copy: String? = null -} - -class OperationAssignment { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var implementation: Implementation? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} - -/* -3.7.4 Relationship Template -A Relationship Template specifies the occurrence of a manageable relationship between node templates as part of an application’s topology model that is defined in a TOSCA Service Template. A Relationship template is an instance of a specified Relationship Type and can provide customized properties, constraints or operations which override the defaults provided by its Relationship Type and its implementations. - */ - -class RelationshipTemplate { - - @get:JsonIgnore - var id: String? = null - lateinit var type: String - var description: String? = null - var metadata: MutableMap? = null - var properties: MutableMap? = null - var attributes: MutableMap? = null - var interfaces: MutableMap? = null - var copy: String? = null -} - -/* -3.7.2 Requirement assignment -A Requirement assignment allows template authors to provide either concrete names of TOSCA templates or provide abstract selection criteria for providers to use to find matching TOSCA templates that are used to fulfill a named requirement’s declared TOSCA Node Type. - */ - -class RequirementAssignment { - - @get:JsonIgnore - var id: String? = null - var capability: String? = null - var node: String? = null - - // Relationship Type or Relationship Template - var relationship: String? = null -} - -class Workflow { - - @get:JsonIgnore - var id: String? = null - var description: String? = null - var steps: MutableMap? = null - var preconditions: ArrayList? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} - -class ConditionClause { - - var and: ArrayList>? = null - var or: ArrayList>? = null - - @get:JsonProperty("assert") - var assertConditions: ArrayList>? = null -} - -/* -3.9 Service Template definition -A TOSCA Service Template (YAML) document contains element definitions of building blocks for cloud application, or complete models of cloud applications. This section describes the top-level structural elements (TOSCA keynames) along with their grammars, which are allowed to appear in a TOSCA Service Template document. - */ - -@JsonPropertyOrder( - value = [ - "toscaDefinitionsVersion", "description", "metadata", "imports", "dsl_definitions", - "topologyTemplate" - ] -) -class ServiceTemplate : Cloneable { - - @get:JsonIgnore - var id: String? = null - - @get:JsonProperty("tosca_definitions_version") - var toscaDefinitionsVersion: String = "controller_blueprint_1_0_0" - var metadata: MutableMap? = null - var description: String? = null - - @get:JsonProperty("dsl_definitions") - var dslDefinitions: MutableMap? = null - var repositories: MutableMap? = null - var imports: MutableList? = null - - @get:JsonProperty("artifact_types") - var artifactTypes: MutableMap? = null - - @get:JsonProperty("data_types") - var dataTypes: MutableMap? = null - - @get:JsonProperty("relationship_types") - var relationshipTypes: MutableMap? = null - - @get:JsonProperty("node_types") - var nodeTypes: MutableMap? = null - - @get:JsonProperty("policy_types") - var policyTypes: MutableMap? = null - - @get:JsonProperty("topology_template") - var topologyTemplate: TopologyTemplate? = null - - public override fun clone(): ServiceTemplate { - return super.clone() as ServiceTemplate - } -} - -class ToscaMetaData { - - lateinit var toscaMetaFileVersion: String - lateinit var csarVersion: String - lateinit var createdBy: String - lateinit var entityDefinitions: String - lateinit var templateName: String - lateinit var templateVersion: String - lateinit var templateTags: String - var templateType: String = BlueprintConstants.BLUEPRINT_TYPE_DEFAULT -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt new file mode 100644 index 000000000..7f300041a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt @@ -0,0 +1,424 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType + +// CDS DSLs +fun blueprint( + name: String, + version: String, + author: String, + tags: String, + block: DSLBluePrintBuilder.() -> Unit +): DSLBluePrint { + return DSLBluePrintBuilder(name, version, author, tags).apply(block).build() +} + +// TOSCA DSLs +fun serviceTemplate( + name: String, + version: String, + author: String, + tags: String, + block: ServiceTemplateBuilder.() -> Unit +): ServiceTemplate { + return ServiceTemplateBuilder(name, version, author, tags).apply(block).build() +} + +fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit): Workflow { + return WorkflowBuilder(id, description).apply(block).build() +} + +fun nodeTemplate( + id: String, + type: String, + description: String, + block: NodeTemplateBuilder.() -> Unit +): NodeTemplate { + return NodeTemplateBuilder(id, type, description).apply(block).build() +} + +fun nodeType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: NodeTypeBuilder.() -> Unit +): NodeType { + return NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun dataType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: DataTypeBuilder.() -> Unit +): DataType { + return DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun artifactType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: ArtifactTypeBuilder.() -> Unit +): ArtifactType { + return ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +fun relationshipType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: RelationshipTypeBuilder.() -> Unit +): RelationshipType { + return RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build() +} + +// DSL Function +fun dslExpression(key: String): JsonNode { + return ("*$key").asJsonPrimitive() +} +// Input Function + +fun getInput(inputKey: String, jsonPath: String? = null): JsonNode { + return """{"get_input": "$inputKey"}""".jsonAsJsonType() +} + +fun getAttribute(attributeId: String, jsonPath: String? = null): JsonNode { + return getNodeTemplateAttribute("SELF", attributeId, jsonPath) +} + +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String): JsonNode { + return getNodeTemplateAttribute(nodeTemplateId, attributeId, null) +} + +fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String, jsonPath: String?): JsonNode { + return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { + """{"get_attribute": ["$nodeTemplateId", "$attributeId"]}""".jsonAsJsonType() + } else { + """{"get_attribute": ["$nodeTemplateId", "$attributeId", "$jsonPath"]}""".jsonAsJsonType() + } +} + +// Property Function + +fun getProperty(propertyId: String, jsonPath: String? = null): JsonNode { + return getNodeTemplateProperty("SELF", propertyId, jsonPath) +} + +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String): JsonNode { + return getNodeTemplateProperty(nodeTemplateName, propertyId, null) +} + +fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String, jsonPath: String?): JsonNode { + return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { + """{"get_property": ["$nodeTemplateName", "$propertyId"]}""".jsonAsJsonType() + } else { + """{"get_property": ["$nodeTemplateName", "$propertyId", "$jsonPath"]}""".jsonAsJsonType() + } +} + +// Artifact Function + +fun getArtifact(artifactId: String): JsonNode { + return getNodeTemplateArtifact("SELF", artifactId) +} + +fun getNodeTemplateArtifact(nodeTemplateName: String, artifactId: String): JsonNode { + return """{"get_artifact": ["$nodeTemplateName", "$artifactId"]}""".jsonAsJsonType() +} + +// Operation Function + +fun getNodeTemplateOperationOutput( + nodeTemplateName: String, + interfaceName: String, + propertyId: String, + jsonPath: String? = null +): JsonNode { + return """{"get_operation_output": ["$nodeTemplateName", "$interfaceName", "process","$propertyId","$jsonPath" ]}""".trimMargin() + .jsonAsJsonType() +} + +/** Blueprint Type Extensions */ +fun ServiceTemplateBuilder.nodeTypeComponent() { + val nodeType = BluePrintTypes.nodeTypeComponent() + if (this.nodeTypes == null) this.nodeTypes = hashMapOf() + this.nodeTypes!![nodeType.id!!] = nodeType +} + +fun BluePrintTypes.nodeTypeComponent(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Component Node" + ) { + } +} + +@Deprecated("CDS won't support, use implerative workflow definitions.") +fun BluePrintTypes.nodeTypeWorkflow(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Workflow Node" + ) { + } +} + +fun ServiceTemplateBuilder.nodeTypeVnf() { + val nodeType = BluePrintTypes.nodeTypeVnf() + if (this.nodeTypes == null) this.nodeTypes = hashMapOf() + this.nodeTypes!![nodeType.id!!] = nodeType +} + +fun BluePrintTypes.nodeTypeVnf(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_VNF, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default VNF Node" + ) { + } +} + +fun ServiceTemplateBuilder.nodeTypeResourceSource() { + val nodeType = BluePrintTypes.nodeTypeResourceSource() + if (this.nodeTypes == null) this.nodeTypes = hashMapOf() + this.nodeTypes!![nodeType.id!!] = nodeType +} + +fun BluePrintTypes.nodeTypeResourceSource(): NodeType { + return nodeType( + id = BluePrintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT, + description = "This is default Resource Source Node" + ) { + } +} + +/** Artifacts */ +fun ServiceTemplateBuilder.artifactTypeTemplateVelocity() { + val artifactType = BluePrintTypes.artifactTypeTemplateVelocity() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeTemplateVelocity(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Velocity Artifact" + ) { + fileExt("vtl") + } +} + +fun ServiceTemplateBuilder.artifactTypeTempleJinja() { + val artifactType = BluePrintTypes.artifactTypeTempleJinja() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeTempleJinja(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Jinja Artifact" + ) { + fileExt("jinja") + } +} + +fun ServiceTemplateBuilder.artifactTypeMappingResource() { + val artifactType = BluePrintTypes.artifactTypeMappingResource() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeMappingResource(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Mapping Resource Artifact" + ) { + fileExt("json") + } +} + +@Deprecated("CDS won't support", replaceWith = ReplaceWith("artifactTypeScriptKotlin")) +fun BluePrintTypes.artifactTypeScriptJython(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Jython Script Artifact" + ) { + fileExt("py") + } +} + +fun ServiceTemplateBuilder.artifactTypeScriptKotlin() { + val artifactType = BluePrintTypes.artifactTypeScriptKotlin() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeScriptKotlin(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Kotlin Script Artifact" + ) { + fileExt("kts") + } +} + +fun ServiceTemplateBuilder.artifactTypeK8sProfileFolder() { + val artifactType = BluePrintTypes.artifactTypeK8sProfileFolder() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeK8sProfileFolder(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "K8s Profile Folder Artifact" + ) { + } +} + +fun ServiceTemplateBuilder.artifactTypeK8sConfigFolder() { + val artifactType = BluePrintTypes.artifactTypeK8sConfigFolder() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeK8sConfigFolder(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "K8s Config Folder Artifact" + ) { + } +} + +@Deprecated("CDS won't support, use implerative workflow definitions.") +fun BluePrintTypes.artifactTypeDirectedGraph(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Directed Graph Artifact" + ) { + fileExt("xml", "json") + } +} + +fun ServiceTemplateBuilder.artifactTypeComponentJar() { + val artifactType = BluePrintTypes.artifactTypeComponentJar() + if (this.artifactTypes == null) this.artifactTypes = hashMapOf() + this.artifactTypes!![artifactType.id!!] = artifactType +} + +fun BluePrintTypes.artifactTypeComponentJar(): ArtifactType { + return artifactType( + id = BluePrintConstants.MODEL_TYPE_ARTIFACT_COMPONENT_JAR, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, + description = "Component Artifact" + ) { + fileExt("jar") + } +} + +/** Relationship Types */ + +fun ServiceTemplateBuilder.relationshipTypeConnectsTo() { + val relationshipType = BluePrintTypes.relationshipTypeConnectsTo() + if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() + this.relationshipTypes!![relationshipType.id!!] = relationshipType +} + +fun BluePrintTypes.relationshipTypeConnectsTo(): RelationshipType { + return relationshipType( + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + description = "Relationship connects to" + ) { + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + } +} + +fun ServiceTemplateBuilder.relationshipTypeDependsOn() { + val relationshipType = BluePrintTypes.relationshipTypeDependsOn() + if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() + this.relationshipTypes!![relationshipType.id!!] = relationshipType +} + +fun BluePrintTypes.relationshipTypeDependsOn(): RelationshipType { + return relationshipType( + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + description = "Relationship depends on" + ) { + } +} + +fun ServiceTemplateBuilder.relationshipTypeHostedOn() { + val relationshipType = BluePrintTypes.relationshipTypeHostedOn() + if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() + this.relationshipTypes!![relationshipType.id!!] = relationshipType +} + +fun BluePrintTypes.relationshipTypeHostedOn(): RelationshipType { + return relationshipType( + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, + description = "Relationship hosted on" + ) { + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt new file mode 100644 index 000000000..b469ded74 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt @@ -0,0 +1,478 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step + +/** + * @author Brinda Santh + */ +class DSLBluePrintBuilder( + private val name: String, + private val version: String, + private val author: String, + private val tags: String +) { + + private var dslBluePrint = DSLBluePrint() + private var metadata: MutableMap = hashMapOf() + var properties: MutableMap? = null + var dataTypes: MutableMap = hashMapOf() + var artifactTypes: MutableMap = hashMapOf() + var components: MutableMap = hashMapOf() + private var registryComponents: MutableMap = hashMapOf() + var workflows: MutableMap = hashMapOf() + + private fun initMetaData() { + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = name + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = version + metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] = author + metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] = tags + } + + fun metadata(id: String, value: String) { + metadata[id] = value + } + + fun property(id: String, expression: Any) { + if (properties == null) + properties = hashMapOf() + properties!![id] = expression.asJsonType() + } + + fun dataType(dataType: DataType) { + dataTypes[dataType.id!!] = dataType + } + + fun dataType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: DataTypeBuilder.() -> Unit + ) { + dataTypes[id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun artifactType(artifactType: ArtifactType) { + artifactTypes[artifactType.id!!] = artifactType + } + + fun artifactType( + id: String, + version: String, + derivedFrom: String, + description: String, + block: ArtifactTypeBuilder.() -> Unit + ) { + artifactTypes[id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() + } + + fun component( + id: String, + type: String, + version: String, + description: String, + block: DSLComponentBuilder.() -> Unit + ) { + components[id] = DSLComponentBuilder(id, type, version, description).apply(block).build() + } + + fun registryComponent( + id: String, + type: String, + version: String, + interfaceName: String, + description: String, + block: DSLRegistryComponentBuilder.() -> Unit + ) { + registryComponents[id] = DSLRegistryComponentBuilder(id, type, version, interfaceName, description) + .apply(block).build() + } + + fun workflow(id: String, description: String, block: DSLWorkflowBuilder.() -> Unit) { + workflows[id] = DSLWorkflowBuilder(id, description).apply(block).build() + } + + fun build(): DSLBluePrint { + initMetaData() + dslBluePrint.metadata = metadata + dslBluePrint.properties = properties + dslBluePrint.dataTypes = dataTypes + dslBluePrint.artifactTypes = artifactTypes + dslBluePrint.components = components + dslBluePrint.registryComponents = registryComponents + dslBluePrint.workflows = workflows + return dslBluePrint + } +} + +class DSLComponentBuilder( + private val id: String, + private val type: String, + private val version: String, + private val description: String +) { + + private val dslComponent = DSLComponent() + var properties: MutableMap? = null + var attributes: MutableMap? = null + + var artifacts: MutableMap? = null + var implementation: Implementation? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null + + fun attribute(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (attributes == null) + attributes = hashMapOf() + val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() + attributes!![id] = attribute + } + + fun attribute( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLAttributeDefinitionBuilder.() -> Unit + ) { + if (attributes == null) + attributes = hashMapOf() + val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + attributes!![id] = attribute + } + + fun property(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (properties == null) + properties = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() + properties!![id] = property + } + + fun property( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (properties == null) + properties = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + properties!![id] = property + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun input(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (inputs == null) + inputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + inputs!![id] = property.build() + } + + fun input( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (inputs == null) + inputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + inputs!![id] = property + } + + fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + outputs!![id] = property.build() + } + + fun output( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + outputs!![id] = property + } + + fun build(): DSLComponent { + dslComponent.id = id + dslComponent.type = type + dslComponent.version = version + dslComponent.description = description + dslComponent.attributes = attributes + dslComponent.properties = properties + dslComponent.implementation = implementation + dslComponent.artifacts = artifacts + dslComponent.inputs = inputs + dslComponent.outputs = outputs + + return dslComponent + } +} + +class DSLRegistryComponentBuilder( + private val id: String, + private val type: String, + private val version: String, + private val interfaceName: String, + private val description: String +) { + + private val dslComponent = DSLRegistryComponent() + var properties: MutableMap? = null + + var artifacts: MutableMap? = null + var implementation: Implementation? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null + + fun property(id: String, expression: Any) { + if (properties == null) + properties = hashMapOf() + properties!![id] = expression.asJsonType() + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun input(id: String, expression: Any) { + if (inputs == null) + inputs = hashMapOf() + inputs!![id] = expression.asJsonType() + } + + fun output(id: String, expression: Any) { + if (outputs == null) + outputs = hashMapOf() + outputs!![id] = expression.asJsonType() + } + + fun build(): DSLRegistryComponent { + dslComponent.id = id + dslComponent.type = type + dslComponent.version = version + dslComponent.interfaceName = interfaceName + dslComponent.description = description + dslComponent.properties = properties + dslComponent.implementation = implementation + dslComponent.artifacts = artifacts + dslComponent.inputs = inputs + dslComponent.outputs = outputs + return dslComponent + } +} + +class DSLWorkflowBuilder(private val actionName: String, private val description: String) { + + private val dslWorkflow = DSLWorkflow() + private var steps: MutableMap? = null + private var inputs: MutableMap? = null + private var outputs: MutableMap? = null + + fun input(id: String, type: String, required: Boolean, description: String? = "") { + if (inputs == null) + inputs = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description) + inputs!![id] = property.build() + } + + fun input( + id: String, + type: String, + required: Boolean, + description: String, + defaultValue: Any?, + block: PropertyDefinitionBuilder.() -> Unit + ) { + if (inputs == null) + inputs = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + if (defaultValue != null) + property.defaultValue = defaultValue.asJsonType() + inputs!![id] = property + } + + fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + outputs!![id] = property.build() + } + + fun output( + id: String, + type: String, + required: Boolean, + expression: Any, + description: String? = "", + block: DSLPropertyDefinitionBuilder.() -> Unit + ) { + if (outputs == null) + outputs = hashMapOf() + val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) + .apply(block).build() + outputs!![id] = property + } + + fun step(id: String, target: String, description: String) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).build() + } + + fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).apply(block).build() + } + + fun build(): DSLWorkflow { + dslWorkflow.actionName = actionName + dslWorkflow.description = description + dslWorkflow.inputs = inputs + dslWorkflow.outputs = outputs + dslWorkflow.steps = steps!! + return dslWorkflow + } +} + +class DSLAttributeDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val expression: JsonNode, + private val description: String? = "" +) { + + private var attributeDefinition = AttributeDefinition() + + fun entrySchema(entrySchemaType: String) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + // TODO("Constrains") + + fun defaultValue(defaultValue: JsonNode) { + attributeDefinition.defaultValue = defaultValue + } + + fun build(): AttributeDefinition { + attributeDefinition.id = id + attributeDefinition.type = type!! + attributeDefinition.required = required + attributeDefinition.value = expression + attributeDefinition.description = description + return attributeDefinition + } +} + +class DSLPropertyDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val expression: JsonNode, + private val description: String? = "" +) { + + private var propertyDefinition: PropertyDefinition = PropertyDefinition() + + fun entrySchema(entrySchemaType: String) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + // TODO("Constrains") + + fun defaultValue(defaultValue: JsonNode) { + propertyDefinition.defaultValue = defaultValue + } + + fun build(): PropertyDefinition { + propertyDefinition.id = id + propertyDefinition.type = type!! + propertyDefinition.required = required + propertyDefinition.value = expression + propertyDefinition.description = description + return propertyDefinition + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt new file mode 100644 index 000000000..370531d2a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt @@ -0,0 +1,83 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.annotation.JsonIgnore +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step + +/** + * This is simplified version of DSL, which is used for generating the Service template + * @author Brinda Santh + */ + +class DSLBluePrint { + + var metadata: MutableMap = hashMapOf() + var properties: MutableMap? = null + var dataTypes: MutableMap = hashMapOf() + var artifactTypes: MutableMap = hashMapOf() + var components: MutableMap = hashMapOf() + var registryComponents: MutableMap = hashMapOf() + var workflows: MutableMap = hashMapOf() +} + +class DSLWorkflow { + + @get:JsonIgnore + var id: String? = null + lateinit var description: String + lateinit var actionName: String + lateinit var steps: MutableMap + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} + +class DSLComponent { + + @get:JsonIgnore + lateinit var id: String + lateinit var type: String + lateinit var version: String + lateinit var description: String + var implementation: Implementation? = null + var attributes: MutableMap? = null + var properties: MutableMap? = null + var artifacts: MutableMap? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} + +class DSLRegistryComponent { + + lateinit var id: String + lateinit var type: String + lateinit var version: String + lateinit var interfaceName: String + lateinit var description: String + var implementation: Implementation? = null + var properties: MutableMap? = null + var artifacts: MutableMap? = null + var inputs: MutableMap? = null + var outputs: MutableMap? = null +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt new file mode 100644 index 000000000..d07fc9c71 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt @@ -0,0 +1,211 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.bpClone +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow + +/** + * Generate Service Template for the simplified DSL. + * @author Brinda Santh + */ +class BluePrintServiceTemplateGenerator(private val dslBluePrint: DSLBluePrint) { + + private var serviceTemplate = ServiceTemplate() + + private val nodeTypes: MutableMap = hashMapOf() + private val artifactTypes: MutableMap = hashMapOf() + private val dataTypes: MutableMap = hashMapOf() + + fun serviceTemplate(): ServiceTemplate { + serviceTemplate.metadata = dslBluePrint.metadata + serviceTemplate.dslDefinitions = dslBluePrint.properties + + dataTypes.putAll(dslBluePrint.dataTypes) + artifactTypes.putAll(dslBluePrint.artifactTypes) + + serviceTemplate.dataTypes = dataTypes + serviceTemplate.artifactTypes = artifactTypes + serviceTemplate.nodeTypes = nodeTypes + + serviceTemplate.topologyTemplate = populateTopologyTemplate() + + return serviceTemplate + } + + private fun populateTopologyTemplate(): TopologyTemplate { + val topologyTemplate = TopologyTemplate() + topologyTemplate.nodeTemplates = populateNodeTemplates() + topologyTemplate.workflows = populateWorkflow() + return topologyTemplate + } + + private fun populateNodeTemplates(): MutableMap { + + val nodeTemplates: MutableMap = hashMapOf() + + // For New or Dynamic Components + val components = dslBluePrint.components + components.forEach { (dslCompName, dslComp) -> + val nodeTemplate = NodeTemplate() + nodeTemplate.type = dslComp.type + nodeTemplate.properties = propertyAssignments(dslComp.properties) + nodeTemplate.artifacts = dslComp.artifacts + nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) + nodeTemplates[dslCompName] = nodeTemplate + + /** Populate Type **/ + nodeTypes[dslComp.type] = populateNodeType(dslComp) + } + + // For Registry Components + val registryComponents = dslBluePrint.registryComponents + registryComponents.forEach { (dslCompName, dslComp) -> + val nodeTemplate = NodeTemplate() + nodeTemplate.type = dslComp.type + nodeTemplate.properties = dslComp.properties + nodeTemplate.artifacts = dslComp.artifacts + nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) + nodeTemplates[dslCompName] = nodeTemplate + } + return nodeTemplates + } + + private fun populateWorkflow(): MutableMap? { + var workflows: MutableMap? = null + if (dslBluePrint.workflows.isNotEmpty()) { + workflows = hashMapOf() + + dslBluePrint.workflows.forEach { (dslWorkflowName, dslWorkflow) -> + val workflow = Workflow() + workflow.description = dslWorkflow.description + workflow.steps = dslWorkflow.steps + workflow.inputs = dslWorkflow.inputs + workflow.outputs = dslWorkflow.outputs + workflows[dslWorkflowName] = workflow + } + } + return workflows + } + + private fun populateNodeType(dslComponent: DSLComponent): NodeType { + val nodeType = NodeType() + nodeType.derivedFrom = BluePrintConstants.MODEL_TYPE_NODES_ROOT + nodeType.version = dslComponent.version + nodeType.description = dslComponent.description + nodeType.interfaces = populateInterfaceDefinitions(dslComponent, nodeType) + return nodeType + } + + private fun populateInterfaceDefinitions(dslComponent: DSLComponent, nodeType: NodeType): MutableMap { + + // Populate Node Type Attribute + nodeType.attributes = attributeDefinitions(dslComponent.attributes) + + val operationDefinition = OperationDefinition() + operationDefinition.inputs = propertyDefinitions(dslComponent.inputs) + operationDefinition.outputs = propertyDefinitions(dslComponent.outputs) + + val operations: MutableMap = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationDefinition + + val interfaceDefinition = InterfaceDefinition() + interfaceDefinition.operations = operations + + val interfaces: MutableMap = hashMapOf() + interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceDefinition + return interfaces + } + + private fun populateInterfaceAssignments(dslComponent: DSLRegistryComponent): MutableMap { + val operationAssignment = OperationAssignment() + operationAssignment.implementation = dslComponent.implementation + operationAssignment.inputs = dslComponent.inputs + operationAssignment.outputs = dslComponent.outputs + + val operations: MutableMap = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment + + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = operations + + val interfaces: MutableMap = hashMapOf() + interfaces[dslComponent.interfaceName] = interfaceAssignment + return interfaces + } + + private fun populateInterfaceAssignments(dslComponent: DSLComponent): MutableMap { + val operationAssignment = OperationAssignment() + operationAssignment.implementation = dslComponent.implementation + operationAssignment.inputs = propertyAssignments(dslComponent.inputs) + operationAssignment.outputs = propertyAssignments(dslComponent.outputs) + + val operations: MutableMap = hashMapOf() + operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment + + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = operations + + val interfaces: MutableMap = hashMapOf() + interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceAssignment + return interfaces + } + + private fun propertyDefinitions(propertyDefinitions: Map?): MutableMap? { + val definitions: MutableMap? = propertyDefinitions?.bpClone()?.toMutableMap() + + definitions?.forEach { (_, prop) -> + prop.value = null + } + return definitions + } + + private fun attributeDefinitions(attributeDefinitions: Map?): MutableMap? { + val definitions: MutableMap? = attributeDefinitions?.bpClone()?.toMutableMap() + + definitions?.forEach { (_, prop) -> + prop.value = null + } + return definitions + } + + private fun propertyAssignments(propertyDefinitions: Map?): MutableMap? { + var assignments: MutableMap? = null + if (propertyDefinitions != null) { + assignments = hashMapOf() + propertyDefinitions.forEach { (propertyName, property) -> + assignments[propertyName] = property.value ?: NullNode.instance + } + } + return assignments + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt new file mode 100644 index 000000000..3a3503403 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt @@ -0,0 +1,482 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import kotlin.reflect.KClass +import kotlin.reflect.KMutableProperty1 +import kotlin.reflect.full.createInstance +import kotlin.reflect.jvm.reflect + +open class TopologyTemplateBuilder { + + private var topologyTemplate = TopologyTemplate() + var nodeTemplates: MutableMap? = null + var relationshipTemplates: MutableMap? = null + private var workflows: MutableMap? = null + + fun nodeTemplate(id: String, type: String, description: String, block: NodeTemplateBuilder.() -> Unit) { + if (nodeTemplates == null) nodeTemplates = hashMapOf() + nodeTemplates!![id] = NodeTemplateBuilder(id, type, description).apply(block).build() + } + + fun nodeTemplate(nodeTemplate: NodeTemplate) { + if (nodeTemplates == null) nodeTemplates = hashMapOf() + nodeTemplates!![nodeTemplate.id!!] = nodeTemplate + } + + fun relationshipTemplate( + id: String, + type: String, + description: String, + block: RelationshipTemplateBuilder.() -> Unit + ) { + if (relationshipTemplates == null) relationshipTemplates = hashMapOf() + relationshipTemplates!![id] = RelationshipTemplateBuilder(id, type, description).apply(block).build() + } + + fun relationshipTemplate(relationshipTemplate: RelationshipTemplate) { + if (relationshipTemplates == null) relationshipTemplates = hashMapOf() + relationshipTemplates!![relationshipTemplate.id!!] = relationshipTemplate + } + + fun nodeTemplateOperation( + nodeTemplateName: String, + type: String, + interfaceName: String, + description: String, + operationBlock: OperationAssignmentBuilder.() -> Unit + ) { + if (nodeTemplates == null) nodeTemplates = hashMapOf() + + val nodeTemplateBuilder = NodeTemplateBuilder(nodeTemplateName, type, description) + nodeTemplateBuilder.operation(interfaceName, "$description operation", operationBlock) + nodeTemplates!![nodeTemplateName] = nodeTemplateBuilder.build() + } + + fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit) { + if (workflows == null) workflows = hashMapOf() + workflows!![id] = WorkflowBuilder(id, description).apply(block).build() + } + + fun workflow(workflow: Workflow) { + if (workflows == null) workflows = hashMapOf() + workflows!![workflow.id!!] = workflow + } + + // TODO("populate inputs, outputs") + fun workflowNodeTemplate( + actionName: String, + nodeTemplateType: String, + description: String, + block: NodeTemplateBuilder.() -> Unit + ) { + if (nodeTemplates == null) nodeTemplates = hashMapOf() + + if (workflows == null) workflows = hashMapOf() + + val workflowBuilder = WorkflowBuilder(actionName, description) + workflowBuilder.nodeTemplateStep(actionName, description) + // Workflow name is NodeTemplate name + workflows!![actionName] = workflowBuilder.build() + + nodeTemplates!![actionName] = + NodeTemplateBuilder(actionName, nodeTemplateType, description).apply(block).build() + } + + fun build(): TopologyTemplate { + topologyTemplate.nodeTemplates = nodeTemplates + topologyTemplate.relationshipTemplates = relationshipTemplates + topologyTemplate.workflows = workflows + return topologyTemplate + } +} + +open class NodeTemplateBuilder( + private val id: String, + private val type: String, + private val description: String? = "" +) { + + var nodeTemplate: NodeTemplate = NodeTemplate() + var properties: MutableMap? = null + var interfaces: MutableMap? = null + var artifacts: MutableMap? = null + var capabilities: MutableMap? = null + var requirements: MutableMap? = null + + fun properties(properties: Map) { + if (this.properties == null) this.properties = hashMapOf() + this.properties!!.putAll(properties) + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + open fun typedProperties(block: Prop.() -> Unit) { + if (properties == null) properties = hashMapOf() + val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() + properties = instance.apply(block).build() + } + + open fun typedOperation( + interfaceName: String, + description: String = "", + block: OperationAssignmentBuilder.() -> Unit + ) { + if (interfaces == null) interfaces = hashMapOf() + + val interfaceAssignment = InterfaceAssignment() + val defaultOperationName = BluePrintConstants.DEFAULT_STEP_OPERATION + interfaceAssignment.operations = hashMapOf() + interfaceAssignment.operations!![defaultOperationName] = + OperationAssignmentBuilder(defaultOperationName, description).apply(block).build() + interfaces!![interfaceName] = interfaceAssignment + } + + fun operation( + interfaceName: String, + description: String, + block: OperationAssignmentBuilder.() -> Unit + ) { + typedOperation(interfaceName, description, block) + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { + if (artifacts == null) artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() + } + + fun artifacts(artifacts: MutableMap?) { + this.artifacts = artifacts + } + + fun capability(id: String, block: CapabilityAssignmentBuilder.() -> Unit) { + if (capabilities == null) capabilities = hashMapOf() + capabilities!![id] = CapabilityAssignmentBuilder(id).apply(block).build() + } + + fun capabilities(capabilities: MutableMap) { + if (this.capabilities == null) this.capabilities = hashMapOf() + this.capabilities!!.putAll(capabilities) + } + + fun requirement(id: String, capability: String, node: String, relationship: String) { + if (requirements == null) requirements = hashMapOf() + requirements!![id] = RequirementAssignmentBuilder(id, capability, node, relationship).build() + } + + fun requirements(requirements: MutableMap) { + if (this.requirements == null) this.requirements = hashMapOf() + this.requirements!!.putAll(requirements) + } + + open fun build(): NodeTemplate { + nodeTemplate.id = id + nodeTemplate.type = type + nodeTemplate.description = description + nodeTemplate.properties = properties + nodeTemplate.interfaces = interfaces + nodeTemplate.artifacts = artifacts + nodeTemplate.capabilities = capabilities + nodeTemplate.requirements = requirements + return nodeTemplate + } +} + +open class RelationshipTemplateBuilder( + private val id: String, + private val type: String, + private val description: String? = "" +) { + + var relationshipTemplate: RelationshipTemplate = RelationshipTemplate() + var properties: MutableMap? = null + + fun properties(properties: Map) { + if (this.properties == null) this.properties = hashMapOf() + this.properties!!.putAll(properties) + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + fun property(id: String, value: Any) { + if (properties == null) properties = hashMapOf() + properties!![id] = value.asJsonType() + } + + fun property(id: String, value: JsonNode) { + if (properties == null) properties = hashMapOf() + properties!![id] = value + } + + fun copy(copy: String) { + relationshipTemplate.copy = copy + } + + open fun typedProperties(block: Prop.() -> Unit) { + if (properties == null) properties = hashMapOf() + val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() + properties = instance.apply(block).build() + } + + open fun build(): RelationshipTemplate { + relationshipTemplate.id = id + relationshipTemplate.type = type + relationshipTemplate.description = description + relationshipTemplate.properties = properties + return relationshipTemplate + } +} + +class ArtifactDefinitionBuilder(private val id: String, private val type: String, private val file: String) { + + private var artifactDefinition: ArtifactDefinition = ArtifactDefinition() + private var properties: MutableMap? = null + + fun repository(repository: String) { + artifactDefinition.repository = repository + } + + fun deployPath(deployPath: String) { + artifactDefinition.deployPath = deployPath + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) + properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + fun build(): ArtifactDefinition { + artifactDefinition.id = id + artifactDefinition.type = type + artifactDefinition.file = file + artifactDefinition.properties = properties + return artifactDefinition + } +} + +open class CapabilityAssignmentBuilder(private val id: String) { + + var capabilityAssignment: CapabilityAssignment = CapabilityAssignment() + var attributes: MutableMap? = null + var properties: MutableMap? = null + + fun attributes(block: AttributesAssignmentBuilder.() -> Unit) { + if (attributes == null) attributes = hashMapOf() + attributes = AttributesAssignmentBuilder().apply(block).build() + } + + fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { + if (properties == null) properties = hashMapOf() + properties = PropertiesAssignmentBuilder().apply(block).build() + } + + fun property(id: String, value: Any) { + if (properties == null) properties = hashMapOf() + properties!![id] = value.asJsonType() + } + + fun property(id: String, value: JsonNode) { + if (properties == null) properties = hashMapOf() + properties!![id] = value + } + + open fun build(): CapabilityAssignment { + capabilityAssignment.properties = properties + capabilityAssignment.attributes = attributes + return capabilityAssignment + } +} + +open class RequirementAssignmentBuilder( + private val id: String, + private val capability: String, + private val node: String, + private val relationship: String +) { + + private var requirementAssignment: RequirementAssignment = RequirementAssignment() + + fun build(): RequirementAssignment { + requirementAssignment.id = id + requirementAssignment.capability = capability + requirementAssignment.node = node + requirementAssignment.relationship = relationship + return requirementAssignment + } +} + +class InterfaceAssignmentBuilder(private val id: String) { + + private var interfaceAssignment: InterfaceAssignment = InterfaceAssignment() + private var operations: MutableMap? = null + + fun operation( + id: String, + description: String? = "", + block: OperationAssignmentBuilder.() -> Unit + ) { + if (operations == null) + operations = hashMapOf() + operations!![id] = OperationAssignmentBuilder( + id, description + ).apply(block).build() + } + + fun build(): InterfaceAssignment { + interfaceAssignment.id = id + interfaceAssignment.operations = operations + return interfaceAssignment + } +} + +class OperationAssignmentBuilder( + private val id: String, + private val description: String? = "" +) { + + private var operationAssignment: OperationAssignment = OperationAssignment() + + fun implementation(implementation: Implementation?) { + operationAssignment.implementation = implementation + } + + fun implementation(timeout: Int, operationHost: String? = BluePrintConstants.PROPERTY_SELF) { + operationAssignment.implementation = Implementation().apply { + this.operationHost = operationHost!! + this.timeout = timeout + } + } + + fun implementation( + timeout: Int, + operationHost: String? = BluePrintConstants.PROPERTY_SELF, + block: ImplementationBuilder.() -> Unit + ) { + operationAssignment.implementation = ImplementationBuilder(timeout, operationHost!!).apply(block).build() + } + + fun inputs(inputs: MutableMap?) { + operationAssignment.inputs = inputs + } + + fun inputs(block: In.() -> Unit) { + val instance: In = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() + operationAssignment.inputs = instance.apply(block).build() + } + + fun outputs(outputs: MutableMap?) { + operationAssignment.outputs = outputs + } + + fun outputs(block: Out.() -> Unit) { + val instance: Out = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() + operationAssignment.outputs = instance.apply(block).build() + } + + fun build(): OperationAssignment { + operationAssignment.id = id + operationAssignment.description = description + return operationAssignment + } +} + +class ImplementationBuilder(private val timeout: Int, private val operationHost: String) { + + private val implementation = Implementation() + + fun primary(primary: String) { + implementation.primary = primary + } + + fun dependencies(vararg dependencies: String) { + if (implementation.dependencies == null) + implementation.dependencies = arrayListOf() + dependencies.forEach { + implementation.dependencies!!.add(it) + } + } + + fun build(): Implementation { + implementation.timeout = timeout + implementation.operationHost = operationHost + return implementation + } +} + +open class PropertiesAssignmentBuilder { + + var properties: MutableMap = hashMapOf() + + fun property(id: String, value: Any) { + property(id, value.asJsonType()) + } + + fun property(id: String, value: JsonNode) { + properties[id] = value + } + + fun property(kProperty: KMutableProperty1<*, *>, value: JsonNode) { + properties[kProperty.name] = value + } + + open fun build(): MutableMap { + return properties + } +} + +open class AttributesAssignmentBuilder { + + var attributes: MutableMap = hashMapOf() + + fun attribute(id: String, value: String) { + attribute(id, value.asJsonType()) + } + + fun attribute(id: String, value: JsonNode) { + attributes[id] = value + } + + fun build(): MutableMap { + return attributes + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt new file mode 100644 index 000000000..3dfdbac57 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt @@ -0,0 +1,585 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType +import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType + +open class EntityTypeBuilder( + private val id: String, + private val version: String, + private val derivedFrom: String, + private val description: String? = "" +) { + + var metadata: MutableMap? = null + var properties: MutableMap? = null + var attributes: MutableMap? = null + + fun metadata(key: String, value: String) { + if (metadata == null) + metadata = hashMapOf() + metadata!![key] = value + } + + fun attribute(id: String, type: String, required: Boolean, description: String? = "") { + if (attributes == null) + attributes = hashMapOf() + val attribute = AttributeDefinitionBuilder(id, type, required, description).build() + attributes!![id] = attribute + } + + fun attribute( + id: String, + type: String, + required: Boolean, + description: String? = "", + block: AttributeDefinitionBuilder.() -> Unit + ) { + if (attributes == null) + attributes = hashMapOf() + val attribute = AttributeDefinitionBuilder(id, type, required, description).apply(block).build() + attributes!![id] = attribute + } + + fun property(id: String, type: String, required: Boolean, description: String? = "") { + if (properties == null) + properties = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties!![id] = property + } + + fun property( + id: String, + type: String, + required: Boolean, + description: String? = "", + block: PropertyDefinitionBuilder.() -> Unit + ) { + if (properties == null) + properties = hashMapOf() + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + properties!![id] = property + } + + fun buildEntityType(entity: EntityType) { + entity.id = id + entity.description = description + entity.version = version + entity.derivedFrom = derivedFrom + entity.metadata = metadata + entity.properties = properties + entity.attributes = attributes + } +} + +class NodeTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var nodeType = NodeType() + private var capabilities: MutableMap? = null + private var requirements: MutableMap? = null + private var interfaces: MutableMap? = null + private var artifacts: MutableMap? = null + + fun capability(id: String, type: String, description: String, block: CapabilityDefinitionBuilder.() -> Unit) { + if (capabilities == null) + capabilities = hashMapOf() + capabilities!![id] = CapabilityDefinitionBuilder(id, type, description).apply(block).build() + } + + fun requirement(id: String, capability: String, node: String, relationship: String, description: String) { + if (requirements == null) + requirements = hashMapOf() + requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description).build() + } + + fun requirement( + id: String, + capability: String, + node: String, + relationship: String, + description: String, + block: RequirementDefinitionBuilder.() -> Unit + ) { + if (requirements == null) + requirements = hashMapOf() + requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description) + .apply(block).build() + } + + fun artifact(id: String, type: String, file: String) { + if (artifacts == null) + artifacts = hashMapOf() + artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() + } + + private fun nodeInterface(id: String, block: InterfaceDefinitionBuilder.() -> Unit) { + if (interfaces == null) + interfaces = hashMapOf() + interfaces!![id] = InterfaceDefinitionBuilder(id).apply(block).build() + } + + fun operation(interfaceName: String, description: String?, block: OperationDefinitionBuilder.() -> Unit) { + if (interfaces == null) + interfaces = hashMapOf() + + val interfaceDefinition = InterfaceDefinition() + val defaultOperationName = "process" + interfaceDefinition.operations = hashMapOf() + interfaceDefinition.operations!![defaultOperationName] = + OperationDefinitionBuilder(defaultOperationName, description).apply(block).build() + interfaces!![interfaceName] = interfaceDefinition + } + + fun build(): NodeType { + buildEntityType(nodeType) + nodeType.capabilities = capabilities + nodeType.requirements = requirements + nodeType.interfaces = interfaces + nodeType.artifacts = artifacts + return nodeType + } +} + +class ArtifactTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var artifactType = ArtifactType() + private var fileExt: MutableList? = null + + fun fileExt(vararg fileExts: String) { + if (fileExt == null) + fileExt = arrayListOf() + fileExts.forEach { + fileExt!!.add(it) + } + } + + fun build(): ArtifactType { + buildEntityType(artifactType) + artifactType.fileExt = fileExt + return artifactType + } +} + +class PolicyTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var policyType = PolicyType() + + fun targets(targetsStr: String) { + val arrayNode = targetsStr.jsonAsJsonType() as ArrayNode + targets(arrayNode.asListOfString()) + } + + fun targets(target: List) { + policyType.targets = target.toMutableList() + } + + fun build(): PolicyType { + buildEntityType(policyType) + return policyType + } +} + +class RelationshipTypeBuilder( + private val id: String, + private val version: String, + derivedFrom: String, + private val description: String? +) : + EntityTypeBuilder(id, version, derivedFrom, description) { + + private var relationshipType = RelationshipType() + + fun validTargetTypes(validTargetTypesStr: String) { + val arrayNode = validTargetTypesStr.jsonAsJsonType() as ArrayNode + validTargetTypes(arrayNode.asListOfString()) + } + + fun validTargetTypes(validTargetTypes: List) { + relationshipType.validTargetTypes = validTargetTypes.toMutableList() + } + + fun build(): RelationshipType { + buildEntityType(relationshipType) + relationshipType.id = id + relationshipType.version = version + relationshipType.description = description + return relationshipType + } +} + +class DataTypeBuilder( + id: String, + version: String, + derivedFrom: String, + description: String? +) : EntityTypeBuilder(id, version, derivedFrom, description) { + + private var dataType = DataType() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (dataType.constraints == null) { + dataType.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + dataType.constraints!!.add(constraintClause) + } + + fun build(): DataType { + buildEntityType(dataType) + return dataType + } +} + +class CapabilityDefinitionBuilder(private val id: String, private val type: String, private val description: String? = "") { + + private var capabilityDefinition = CapabilityDefinition() + private val properties: MutableMap = hashMapOf() + + fun property(id: String, type: String? = BluePrintConstants.DATA_TYPE_STRING, required: Boolean? = false, description: String? = "") { + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties[id] = property + } + + fun build(): CapabilityDefinition { + capabilityDefinition.id = id + capabilityDefinition.description = description + capabilityDefinition.type = type + capabilityDefinition.properties = properties + return capabilityDefinition + } +} + +class RequirementDefinitionBuilder( + private val id: String, + private val capability: String, + private val node: String, + private val relationship: String, + private val description: String? = "" +) { + + private var requirementDefinition = RequirementDefinition() + + fun build(): RequirementDefinition { + requirementDefinition.id = id + requirementDefinition.description = description + requirementDefinition.capability = capability + requirementDefinition.node = node + requirementDefinition.relationship = relationship + return requirementDefinition + } +} + +class InterfaceDefinitionBuilder(private val id: String) { + + private var interfaceDefinition: InterfaceDefinition = InterfaceDefinition() + private var operations: MutableMap? = null + + fun operation(id: String, description: String? = "", block: OperationDefinitionBuilder.() -> Unit) { + if (operations == null) + operations = hashMapOf() + operations!![id] = OperationDefinitionBuilder(id, description).apply(block).build() + } + + fun build(): InterfaceDefinition { + interfaceDefinition.id = id + interfaceDefinition.operations = operations + return interfaceDefinition + } +} + +class OperationDefinitionBuilder( + private val id: String, + private val description: String? = "" +) { + + private var operationDefinition: OperationDefinition = OperationDefinition() + + fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { + operationDefinition.inputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { + operationDefinition.outputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun build(): OperationDefinition { + operationDefinition.id = id + operationDefinition.description = description + return operationDefinition + } +} + +class AttributeDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val description: String? = "" +) { + + private var attributeDefinition: AttributeDefinition = AttributeDefinition() + + fun entrySchema(entrySchemaType: String) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (attributeDefinition.constraints == null) { + attributeDefinition.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + attributeDefinition.constraints!!.add(constraintClause) + } + + fun defaultValue(defaultValue: Any) { + defaultValue(defaultValue.asJsonType()) + } + + fun defaultValue(defaultValue: JsonNode) { + attributeDefinition.defaultValue = defaultValue + } + + fun build(): AttributeDefinition { + attributeDefinition.id = id + attributeDefinition.type = type!! + attributeDefinition.required = required + attributeDefinition.description = description + return attributeDefinition + } +} + +class PropertiesDefinitionBuilder { + + private val properties: MutableMap = hashMapOf() + + fun property(id: String, property: PropertyDefinition) { + properties[id] = property + } + + fun property(id: String, type: String?, required: Boolean?, description: String? = "") { + val property = PropertyDefinitionBuilder(id, type, required, description).build() + properties[id] = property + } + + fun property( + id: String, + type: String?, + required: Boolean?, + description: String? = "", + block: PropertyDefinitionBuilder.() -> Unit + ) { + val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() + properties[id] = property + } + + fun build(): MutableMap { + return properties + } +} + +class PropertyDefinitionBuilder( + private val id: String, + private val type: String? = BluePrintConstants.DATA_TYPE_STRING, + private val required: Boolean? = false, + private val description: String? = "" +) { + + private var propertyDefinition: PropertyDefinition = PropertyDefinition() + + fun entrySchema(entrySchemaType: String) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() + } + + fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { + propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() + } + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (propertyDefinition.constraints == null) { + propertyDefinition.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + propertyDefinition.constraints!!.add(constraintClause) + } + + fun defaultValue(defaultValue: Any) { + defaultValue(defaultValue.asJsonType()) + } + + fun defaultValue(defaultValue: JsonNode) { + propertyDefinition.defaultValue = defaultValue + } + + fun metadata(name: String, value: String) { + if (propertyDefinition.metadata == null) { + propertyDefinition.metadata = hashMapOf() + } + propertyDefinition.metadata!![name] = value + } + + fun value(value: Any) { + value(value.asJsonType()) + } + + fun value(value: JsonNode) { + propertyDefinition.value = value + } + + fun build(): PropertyDefinition { + propertyDefinition.id = id + propertyDefinition.type = type!! + propertyDefinition.required = required + propertyDefinition.description = description + return propertyDefinition + } +} + +class ConstraintsClauseBuilder { + + val constraints: MutableList = mutableListOf() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + val constraintClause = ConstraintClauseBuilder().apply(block).build() + constraints.add(constraintClause) + } + + fun build(): MutableList { + return constraints + } +} + +class ConstraintClauseBuilder { + + private val constraintClause = ConstraintClause() + + fun equal(equal: Any) = equal(equal.asJsonType()) + + fun equal(equal: JsonNode) { + constraintClause.equal = equal + } + + fun greaterOrEqual(greaterOrEqual: Any) { + constraintClause.greaterOrEqual = greaterOrEqual.asJsonPrimitive() + } + + fun greaterThan(greaterThan: Any) { + constraintClause.greaterThan = greaterThan.asJsonPrimitive() + } + + fun lessOrEqual(lessOrEqual: Any) { + constraintClause.lessOrEqual = lessOrEqual.asJsonPrimitive() + } + + fun lessThan(lessThan: Any) { + constraintClause.lessThan = lessThan.asJsonPrimitive() + } + + fun inRange(inRangeStr: String) = inRange(inRangeStr.jsonAsJsonType() as ArrayNode) + + fun inRange(inRangeNode: ArrayNode) { + constraintClause.inRange = inRangeNode.toMutableList() + } + + fun validValues(validValuesStr: String) = validValues(validValuesStr.jsonAsJsonType() as ArrayNode) + + fun validValues(validValuesNode: ArrayNode) = validValues(validValuesNode.toMutableList()) + + fun validValues(validValues: List) { + constraintClause.validValues = validValues.toMutableList() + } + + fun length(length: Any) { + constraintClause.length = length.asJsonPrimitive() + } + + fun minLength(minLength: Any) { + constraintClause.minLength = minLength.asJsonPrimitive() + } + + fun maxLength(maxLength: Any) { + constraintClause.maxLength = maxLength.asJsonPrimitive() + } + + fun pattern(pattern: String) { + constraintClause.pattern = pattern + } + + fun schema(schema: String) { + constraintClause.schema = schema + } + + fun build(): ConstraintClause { + return constraintClause + } +} + +class EntrySchemaBuilder(private val type: String) { + + private var entrySchema: EntrySchema = EntrySchema() + + fun constrain(block: ConstraintClauseBuilder.() -> Unit) { + if (entrySchema.constraints == null) { + entrySchema.constraints = mutableListOf() + } + val constraintClause = ConstraintClauseBuilder().apply(block).build() + entrySchema.constraints!!.add(constraintClause) + } + + fun build(): EntrySchema { + entrySchema.type = type + return entrySchema + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt new file mode 100644 index 000000000..8a1a9d63c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt @@ -0,0 +1,121 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap +import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import kotlin.reflect.KClass + +class WorkflowBuilder(private val id: String, private val description: String) { + + private var workflow = Workflow() + private var steps: MutableMap? = null + private var inputs: MutableMap? = null + private var outputs: MutableMap? = null + + // Used Internally + fun nodeTemplateStep(nodeTemplateName: String, description: String) { + step(nodeTemplateName, nodeTemplateName, "$description step") + } + + fun step(id: String, target: String, description: String) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).build() + } + + fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { + if (steps == null) + steps = hashMapOf() + steps!![id] = StepBuilder(id, target, description).apply(block).build() + } + + fun inputs(kClazz: KClass<*>) { + inputs = kClazz.asPropertyDefinitionMap() + } + + fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { + inputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { + outputs = PropertiesDefinitionBuilder().apply(block).build() + } + + fun outputs(kClazz: KClass<*>) { + outputs = kClazz.asPropertyDefinitionMap() + } + + fun build(): Workflow { + workflow.id = id + workflow.description = description + workflow.steps = steps + workflow.inputs = inputs + workflow.outputs = outputs + return workflow + } +} + +class StepBuilder( + private val id: String, + private val target: String, + private val description: String +) { + + private var step = Step() + private var activities: ArrayList = arrayListOf() + private var onSuccess: ArrayList? = null + private var onFailure: ArrayList? = null + + fun activity(callOperation: String) { + val activity = Activity() + activity.callOperation = callOperation + activities.add(activity) + } + + fun success(vararg successTargets: String) { + if (onSuccess == null) + onSuccess = arrayListOf() + successTargets.forEach { + onSuccess!!.add(it) + } + } + + fun failure(vararg failureTargets: String) { + if (onFailure == null) + onFailure = arrayListOf() + failureTargets.forEach { + onFailure!!.add(it) + } + } + + fun build(): Step { + step.id = id + step.target = target + // Add Default Activity, Assumption is only one Operation + activity(".${BluePrintConstants.DEFAULT_STEP_OPERATION}") + step.description = description + step.activities = activities + step.onSuccess = onSuccess + step.onFailure = onFailure + return step + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSL.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSL.kt deleted file mode 100644 index 81593c935..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSL.kt +++ /dev/null @@ -1,424 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType - -// CDS DSLs -fun blueprint( - name: String, - version: String, - author: String, - tags: String, - block: DSLBlueprintBuilder.() -> Unit -): DSLBlueprint { - return DSLBlueprintBuilder(name, version, author, tags).apply(block).build() -} - -// TOSCA DSLs -fun serviceTemplate( - name: String, - version: String, - author: String, - tags: String, - block: ServiceTemplateBuilder.() -> Unit -): ServiceTemplate { - return ServiceTemplateBuilder(name, version, author, tags).apply(block).build() -} - -fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit): Workflow { - return WorkflowBuilder(id, description).apply(block).build() -} - -fun nodeTemplate( - id: String, - type: String, - description: String, - block: NodeTemplateBuilder.() -> Unit -): NodeTemplate { - return NodeTemplateBuilder(id, type, description).apply(block).build() -} - -fun nodeType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: NodeTypeBuilder.() -> Unit -): NodeType { - return NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build() -} - -fun dataType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: DataTypeBuilder.() -> Unit -): DataType { - return DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() -} - -fun artifactType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: ArtifactTypeBuilder.() -> Unit -): ArtifactType { - return ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() -} - -fun relationshipType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: RelationshipTypeBuilder.() -> Unit -): RelationshipType { - return RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build() -} - -// DSL Function -fun dslExpression(key: String): JsonNode { - return ("*$key").asJsonPrimitive() -} -// Input Function - -fun getInput(inputKey: String, jsonPath: String? = null): JsonNode { - return """{"get_input": "$inputKey"}""".jsonAsJsonType() -} - -fun getAttribute(attributeId: String, jsonPath: String? = null): JsonNode { - return getNodeTemplateAttribute("SELF", attributeId, jsonPath) -} - -fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String): JsonNode { - return getNodeTemplateAttribute(nodeTemplateId, attributeId, null) -} - -fun getNodeTemplateAttribute(nodeTemplateId: String, attributeId: String, jsonPath: String?): JsonNode { - return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { - """{"get_attribute": ["$nodeTemplateId", "$attributeId"]}""".jsonAsJsonType() - } else { - """{"get_attribute": ["$nodeTemplateId", "$attributeId", "$jsonPath"]}""".jsonAsJsonType() - } -} - -// Property Function - -fun getProperty(propertyId: String, jsonPath: String? = null): JsonNode { - return getNodeTemplateProperty("SELF", propertyId, jsonPath) -} - -fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String): JsonNode { - return getNodeTemplateProperty(nodeTemplateName, propertyId, null) -} - -fun getNodeTemplateProperty(nodeTemplateName: String, propertyId: String, jsonPath: String?): JsonNode { - return if (jsonPath.isNullOrEmpty() || jsonPath.isNullOrBlank()) { - """{"get_property": ["$nodeTemplateName", "$propertyId"]}""".jsonAsJsonType() - } else { - """{"get_property": ["$nodeTemplateName", "$propertyId", "$jsonPath"]}""".jsonAsJsonType() - } -} - -// Artifact Function - -fun getArtifact(artifactId: String): JsonNode { - return getNodeTemplateArtifact("SELF", artifactId) -} - -fun getNodeTemplateArtifact(nodeTemplateName: String, artifactId: String): JsonNode { - return """{"get_artifact": ["$nodeTemplateName", "$artifactId"]}""".jsonAsJsonType() -} - -// Operation Function - -fun getNodeTemplateOperationOutput( - nodeTemplateName: String, - interfaceName: String, - propertyId: String, - jsonPath: String? = null -): JsonNode { - return """{"get_operation_output": ["$nodeTemplateName", "$interfaceName", "process","$propertyId","$jsonPath" ]}""".trimMargin() - .jsonAsJsonType() -} - -/** Blueprint Type Extensions */ -fun ServiceTemplateBuilder.nodeTypeComponent() { - val nodeType = BlueprintTypes.nodeTypeComponent() - if (this.nodeTypes == null) this.nodeTypes = hashMapOf() - this.nodeTypes!![nodeType.id!!] = nodeType -} - -fun BlueprintTypes.nodeTypeComponent(): NodeType { - return nodeType( - id = BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODES_ROOT, - description = "This is default Component Node" - ) { - } -} - -@Deprecated("CDS won't support, use implerative workflow definitions.") -fun BlueprintTypes.nodeTypeWorkflow(): NodeType { - return nodeType( - id = BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODES_ROOT, - description = "This is default Workflow Node" - ) { - } -} - -fun ServiceTemplateBuilder.nodeTypeVnf() { - val nodeType = BlueprintTypes.nodeTypeVnf() - if (this.nodeTypes == null) this.nodeTypes = hashMapOf() - this.nodeTypes!![nodeType.id!!] = nodeType -} - -fun BlueprintTypes.nodeTypeVnf(): NodeType { - return nodeType( - id = BlueprintConstants.MODEL_TYPE_NODE_VNF, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODES_ROOT, - description = "This is default VNF Node" - ) { - } -} - -fun ServiceTemplateBuilder.nodeTypeResourceSource() { - val nodeType = BlueprintTypes.nodeTypeResourceSource() - if (this.nodeTypes == null) this.nodeTypes = hashMapOf() - this.nodeTypes!![nodeType.id!!] = nodeType -} - -fun BlueprintTypes.nodeTypeResourceSource(): NodeType { - return nodeType( - id = BlueprintConstants.MODEL_TYPE_NODE_RESOURCE_SOURCE, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODES_ROOT, - description = "This is default Resource Source Node" - ) { - } -} - -/** Artifacts */ -fun ServiceTemplateBuilder.artifactTypeTemplateVelocity() { - val artifactType = BlueprintTypes.artifactTypeTemplateVelocity() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeTemplateVelocity(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Velocity Artifact" - ) { - fileExt("vtl") - } -} - -fun ServiceTemplateBuilder.artifactTypeTempleJinja() { - val artifactType = BlueprintTypes.artifactTypeTempleJinja() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeTempleJinja(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Jinja Artifact" - ) { - fileExt("jinja") - } -} - -fun ServiceTemplateBuilder.artifactTypeMappingResource() { - val artifactType = BlueprintTypes.artifactTypeMappingResource() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeMappingResource(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_MAPPING_RESOURCE, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Mapping Resource Artifact" - ) { - fileExt("json") - } -} - -@Deprecated("CDS won't support", replaceWith = ReplaceWith("artifactTypeScriptKotlin")) -fun BlueprintTypes.artifactTypeScriptJython(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_JYTHON, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Jython Script Artifact" - ) { - fileExt("py") - } -} - -fun ServiceTemplateBuilder.artifactTypeScriptKotlin() { - val artifactType = BlueprintTypes.artifactTypeScriptKotlin() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeScriptKotlin(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_SCRIPT_KOTLIN, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Kotlin Script Artifact" - ) { - fileExt("kts") - } -} - -fun ServiceTemplateBuilder.artifactTypeK8sProfileFolder() { - val artifactType = BlueprintTypes.artifactTypeK8sProfileFolder() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeK8sProfileFolder(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_PROFILE, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "K8s Profile Folder Artifact" - ) { - } -} - -fun ServiceTemplateBuilder.artifactTypeK8sConfigFolder() { - val artifactType = BlueprintTypes.artifactTypeK8sConfigFolder() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeK8sConfigFolder(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_K8S_CONFIG, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "K8s Config Folder Artifact" - ) { - } -} - -@Deprecated("CDS won't support, use implerative workflow definitions.") -fun BlueprintTypes.artifactTypeDirectedGraph(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_DIRECTED_GRAPH, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Directed Graph Artifact" - ) { - fileExt("xml", "json") - } -} - -fun ServiceTemplateBuilder.artifactTypeComponentJar() { - val artifactType = BlueprintTypes.artifactTypeComponentJar() - if (this.artifactTypes == null) this.artifactTypes = hashMapOf() - this.artifactTypes!![artifactType.id!!] = artifactType -} - -fun BlueprintTypes.artifactTypeComponentJar(): ArtifactType { - return artifactType( - id = BlueprintConstants.MODEL_TYPE_ARTIFACT_COMPONENT_JAR, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION, - description = "Component Artifact" - ) { - fileExt("jar") - } -} - -/** Relationship Types */ - -fun ServiceTemplateBuilder.relationshipTypeConnectsTo() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsTo() - if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() - this.relationshipTypes!![relationshipType.id!!] = relationshipType -} - -fun BlueprintTypes.relationshipTypeConnectsTo(): RelationshipType { - return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, - description = "Relationship connects to" - ) { - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) - } -} - -fun ServiceTemplateBuilder.relationshipTypeDependsOn() { - val relationshipType = BlueprintTypes.relationshipTypeDependsOn() - if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() - this.relationshipTypes!![relationshipType.id!!] = relationshipType -} - -fun BlueprintTypes.relationshipTypeDependsOn(): RelationshipType { - return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_DEPENDS_ON, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, - description = "Relationship depends on" - ) { - } -} - -fun ServiceTemplateBuilder.relationshipTypeHostedOn() { - val relationshipType = BlueprintTypes.relationshipTypeHostedOn() - if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() - this.relationshipTypes!![relationshipType.id!!] = relationshipType -} - -fun BlueprintTypes.relationshipTypeHostedOn(): RelationshipType { - return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_HOSTED_ON, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_ROOT, - description = "Relationship hosted on" - ) { - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLBuilder.kt deleted file mode 100644 index f92a955a5..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLBuilder.kt +++ /dev/null @@ -1,478 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step - -/** - * @author Brinda Santh - */ -class DSLBlueprintBuilder( - private val name: String, - private val version: String, - private val author: String, - private val tags: String -) { - - private var dslBlueprint = DSLBlueprint() - private var metadata: MutableMap = hashMapOf() - var properties: MutableMap? = null - var dataTypes: MutableMap = hashMapOf() - var artifactTypes: MutableMap = hashMapOf() - var components: MutableMap = hashMapOf() - private var registryComponents: MutableMap = hashMapOf() - var workflows: MutableMap = hashMapOf() - - private fun initMetaData() { - metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] = name - metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] = version - metadata[BlueprintConstants.METADATA_TEMPLATE_AUTHOR] = author - metadata[BlueprintConstants.METADATA_TEMPLATE_TAGS] = tags - } - - fun metadata(id: String, value: String) { - metadata[id] = value - } - - fun property(id: String, expression: Any) { - if (properties == null) - properties = hashMapOf() - properties!![id] = expression.asJsonType() - } - - fun dataType(dataType: DataType) { - dataTypes[dataType.id!!] = dataType - } - - fun dataType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: DataTypeBuilder.() -> Unit - ) { - dataTypes[id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build() - } - - fun artifactType(artifactType: ArtifactType) { - artifactTypes[artifactType.id!!] = artifactType - } - - fun artifactType( - id: String, - version: String, - derivedFrom: String, - description: String, - block: ArtifactTypeBuilder.() -> Unit - ) { - artifactTypes[id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build() - } - - fun component( - id: String, - type: String, - version: String, - description: String, - block: DSLComponentBuilder.() -> Unit - ) { - components[id] = DSLComponentBuilder(id, type, version, description).apply(block).build() - } - - fun registryComponent( - id: String, - type: String, - version: String, - interfaceName: String, - description: String, - block: DSLRegistryComponentBuilder.() -> Unit - ) { - registryComponents[id] = DSLRegistryComponentBuilder(id, type, version, interfaceName, description) - .apply(block).build() - } - - fun workflow(id: String, description: String, block: DSLWorkflowBuilder.() -> Unit) { - workflows[id] = DSLWorkflowBuilder(id, description).apply(block).build() - } - - fun build(): DSLBlueprint { - initMetaData() - dslBlueprint.metadata = metadata - dslBlueprint.properties = properties - dslBlueprint.dataTypes = dataTypes - dslBlueprint.artifactTypes = artifactTypes - dslBlueprint.components = components - dslBlueprint.registryComponents = registryComponents - dslBlueprint.workflows = workflows - return dslBlueprint - } -} - -class DSLComponentBuilder( - private val id: String, - private val type: String, - private val version: String, - private val description: String -) { - - private val dslComponent = DSLComponent() - var properties: MutableMap? = null - var attributes: MutableMap? = null - - var artifacts: MutableMap? = null - var implementation: Implementation? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null - - fun attribute(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { - if (attributes == null) - attributes = hashMapOf() - val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() - attributes!![id] = attribute - } - - fun attribute( - id: String, - type: String, - required: Boolean, - expression: Any, - description: String? = "", - block: DSLAttributeDefinitionBuilder.() -> Unit - ) { - if (attributes == null) - attributes = hashMapOf() - val attribute = DSLAttributeDefinitionBuilder(id, type, required, expression.asJsonType(), description) - .apply(block).build() - attributes!![id] = attribute - } - - fun property(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { - if (properties == null) - properties = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description).build() - properties!![id] = property - } - - fun property( - id: String, - type: String, - required: Boolean, - expression: Any, - description: String? = "", - block: DSLPropertyDefinitionBuilder.() -> Unit - ) { - if (properties == null) - properties = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - .apply(block).build() - properties!![id] = property - } - - fun implementation(timeout: Int, operationHost: String? = BlueprintConstants.PROPERTY_SELF) { - implementation = Implementation().apply { - this.operationHost = operationHost!! - this.timeout = timeout - } - } - - fun artifact(id: String, type: String, file: String) { - if (artifacts == null) - artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() - } - - fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { - if (artifacts == null) - artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() - } - - fun input(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { - if (inputs == null) - inputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - inputs!![id] = property.build() - } - - fun input( - id: String, - type: String, - required: Boolean, - expression: Any, - description: String? = "", - block: DSLPropertyDefinitionBuilder.() -> Unit - ) { - if (inputs == null) - inputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - .apply(block).build() - inputs!![id] = property - } - - fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { - if (outputs == null) - outputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - outputs!![id] = property.build() - } - - fun output( - id: String, - type: String, - required: Boolean, - expression: Any, - description: String? = "", - block: DSLPropertyDefinitionBuilder.() -> Unit - ) { - if (outputs == null) - outputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - .apply(block).build() - outputs!![id] = property - } - - fun build(): DSLComponent { - dslComponent.id = id - dslComponent.type = type - dslComponent.version = version - dslComponent.description = description - dslComponent.attributes = attributes - dslComponent.properties = properties - dslComponent.implementation = implementation - dslComponent.artifacts = artifacts - dslComponent.inputs = inputs - dslComponent.outputs = outputs - - return dslComponent - } -} - -class DSLRegistryComponentBuilder( - private val id: String, - private val type: String, - private val version: String, - private val interfaceName: String, - private val description: String -) { - - private val dslComponent = DSLRegistryComponent() - var properties: MutableMap? = null - - var artifacts: MutableMap? = null - var implementation: Implementation? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null - - fun property(id: String, expression: Any) { - if (properties == null) - properties = hashMapOf() - properties!![id] = expression.asJsonType() - } - - fun implementation(timeout: Int, operationHost: String? = BlueprintConstants.PROPERTY_SELF) { - implementation = Implementation().apply { - this.operationHost = operationHost!! - this.timeout = timeout - } - } - - fun artifact(id: String, type: String, file: String) { - if (artifacts == null) - artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() - } - - fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { - if (artifacts == null) - artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() - } - - fun input(id: String, expression: Any) { - if (inputs == null) - inputs = hashMapOf() - inputs!![id] = expression.asJsonType() - } - - fun output(id: String, expression: Any) { - if (outputs == null) - outputs = hashMapOf() - outputs!![id] = expression.asJsonType() - } - - fun build(): DSLRegistryComponent { - dslComponent.id = id - dslComponent.type = type - dslComponent.version = version - dslComponent.interfaceName = interfaceName - dslComponent.description = description - dslComponent.properties = properties - dslComponent.implementation = implementation - dslComponent.artifacts = artifacts - dslComponent.inputs = inputs - dslComponent.outputs = outputs - return dslComponent - } -} - -class DSLWorkflowBuilder(private val actionName: String, private val description: String) { - - private val dslWorkflow = DSLWorkflow() - private var steps: MutableMap? = null - private var inputs: MutableMap? = null - private var outputs: MutableMap? = null - - fun input(id: String, type: String, required: Boolean, description: String? = "") { - if (inputs == null) - inputs = hashMapOf() - val property = PropertyDefinitionBuilder(id, type, required, description) - inputs!![id] = property.build() - } - - fun input( - id: String, - type: String, - required: Boolean, - description: String, - defaultValue: Any?, - block: PropertyDefinitionBuilder.() -> Unit - ) { - if (inputs == null) - inputs = hashMapOf() - val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() - if (defaultValue != null) - property.defaultValue = defaultValue.asJsonType() - inputs!![id] = property - } - - fun output(id: String, type: String, required: Boolean, expression: Any, description: String? = "") { - if (outputs == null) - outputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - outputs!![id] = property.build() - } - - fun output( - id: String, - type: String, - required: Boolean, - expression: Any, - description: String? = "", - block: DSLPropertyDefinitionBuilder.() -> Unit - ) { - if (outputs == null) - outputs = hashMapOf() - val property = DSLPropertyDefinitionBuilder(id, type, required, expression.asJsonType(), description) - .apply(block).build() - outputs!![id] = property - } - - fun step(id: String, target: String, description: String) { - if (steps == null) - steps = hashMapOf() - steps!![id] = StepBuilder(id, target, description).build() - } - - fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { - if (steps == null) - steps = hashMapOf() - steps!![id] = StepBuilder(id, target, description).apply(block).build() - } - - fun build(): DSLWorkflow { - dslWorkflow.actionName = actionName - dslWorkflow.description = description - dslWorkflow.inputs = inputs - dslWorkflow.outputs = outputs - dslWorkflow.steps = steps!! - return dslWorkflow - } -} - -class DSLAttributeDefinitionBuilder( - private val id: String, - private val type: String? = BlueprintConstants.DATA_TYPE_STRING, - private val required: Boolean? = false, - private val expression: JsonNode, - private val description: String? = "" -) { - - private var attributeDefinition = AttributeDefinition() - - fun entrySchema(entrySchemaType: String) { - attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() - } - - fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { - attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() - } - // TODO("Constrains") - - fun defaultValue(defaultValue: JsonNode) { - attributeDefinition.defaultValue = defaultValue - } - - fun build(): AttributeDefinition { - attributeDefinition.id = id - attributeDefinition.type = type!! - attributeDefinition.required = required - attributeDefinition.value = expression - attributeDefinition.description = description - return attributeDefinition - } -} - -class DSLPropertyDefinitionBuilder( - private val id: String, - private val type: String? = BlueprintConstants.DATA_TYPE_STRING, - private val required: Boolean? = false, - private val expression: JsonNode, - private val description: String? = "" -) { - - private var propertyDefinition: PropertyDefinition = PropertyDefinition() - - fun entrySchema(entrySchemaType: String) { - propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() - } - - fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { - propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() - } - // TODO("Constrains") - - fun defaultValue(defaultValue: JsonNode) { - propertyDefinition.defaultValue = defaultValue - } - - fun build(): PropertyDefinition { - propertyDefinition.id = id - propertyDefinition.type = type!! - propertyDefinition.required = required - propertyDefinition.value = expression - propertyDefinition.description = description - return propertyDefinition - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLData.kt deleted file mode 100644 index 8f1a8d145..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLData.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.annotation.JsonIgnore -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step - -/** - * This is simplified version of DSL, which is used for generating the Service template - * @author Brinda Santh - */ - -class DSLBlueprint { - - var metadata: MutableMap = hashMapOf() - var properties: MutableMap? = null - var dataTypes: MutableMap = hashMapOf() - var artifactTypes: MutableMap = hashMapOf() - var components: MutableMap = hashMapOf() - var registryComponents: MutableMap = hashMapOf() - var workflows: MutableMap = hashMapOf() -} - -class DSLWorkflow { - - @get:JsonIgnore - var id: String? = null - lateinit var description: String - lateinit var actionName: String - lateinit var steps: MutableMap - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} - -class DSLComponent { - - @get:JsonIgnore - lateinit var id: String - lateinit var type: String - lateinit var version: String - lateinit var description: String - var implementation: Implementation? = null - var attributes: MutableMap? = null - var properties: MutableMap? = null - var artifacts: MutableMap? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} - -class DSLRegistryComponent { - - lateinit var id: String - lateinit var type: String - lateinit var version: String - lateinit var interfaceName: String - lateinit var description: String - var implementation: Implementation? = null - var properties: MutableMap? = null - var artifacts: MutableMap? = null - var inputs: MutableMap? = null - var outputs: MutableMap? = null -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintServiceTemplateGenerator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintServiceTemplateGenerator.kt deleted file mode 100644 index 21bc8c7d8..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintServiceTemplateGenerator.kt +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.bpClone -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow - -/** - * Generate Service Template for the simplified DSL. - * @author Brinda Santh - */ -class BlueprintServiceTemplateGenerator(private val dslBlueprint: DSLBlueprint) { - - private var serviceTemplate = ServiceTemplate() - - private val nodeTypes: MutableMap = hashMapOf() - private val artifactTypes: MutableMap = hashMapOf() - private val dataTypes: MutableMap = hashMapOf() - - fun serviceTemplate(): ServiceTemplate { - serviceTemplate.metadata = dslBlueprint.metadata - serviceTemplate.dslDefinitions = dslBlueprint.properties - - dataTypes.putAll(dslBlueprint.dataTypes) - artifactTypes.putAll(dslBlueprint.artifactTypes) - - serviceTemplate.dataTypes = dataTypes - serviceTemplate.artifactTypes = artifactTypes - serviceTemplate.nodeTypes = nodeTypes - - serviceTemplate.topologyTemplate = populateTopologyTemplate() - - return serviceTemplate - } - - private fun populateTopologyTemplate(): TopologyTemplate { - val topologyTemplate = TopologyTemplate() - topologyTemplate.nodeTemplates = populateNodeTemplates() - topologyTemplate.workflows = populateWorkflow() - return topologyTemplate - } - - private fun populateNodeTemplates(): MutableMap { - - val nodeTemplates: MutableMap = hashMapOf() - - // For New or Dynamic Components - val components = dslBlueprint.components - components.forEach { (dslCompName, dslComp) -> - val nodeTemplate = NodeTemplate() - nodeTemplate.type = dslComp.type - nodeTemplate.properties = propertyAssignments(dslComp.properties) - nodeTemplate.artifacts = dslComp.artifacts - nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) - nodeTemplates[dslCompName] = nodeTemplate - - /** Populate Type **/ - nodeTypes[dslComp.type] = populateNodeType(dslComp) - } - - // For Registry Components - val registryComponents = dslBlueprint.registryComponents - registryComponents.forEach { (dslCompName, dslComp) -> - val nodeTemplate = NodeTemplate() - nodeTemplate.type = dslComp.type - nodeTemplate.properties = dslComp.properties - nodeTemplate.artifacts = dslComp.artifacts - nodeTemplate.interfaces = populateInterfaceAssignments(dslComp) - nodeTemplates[dslCompName] = nodeTemplate - } - return nodeTemplates - } - - private fun populateWorkflow(): MutableMap? { - var workflows: MutableMap? = null - if (dslBlueprint.workflows.isNotEmpty()) { - workflows = hashMapOf() - - dslBlueprint.workflows.forEach { (dslWorkflowName, dslWorkflow) -> - val workflow = Workflow() - workflow.description = dslWorkflow.description - workflow.steps = dslWorkflow.steps - workflow.inputs = dslWorkflow.inputs - workflow.outputs = dslWorkflow.outputs - workflows[dslWorkflowName] = workflow - } - } - return workflows - } - - private fun populateNodeType(dslComponent: DSLComponent): NodeType { - val nodeType = NodeType() - nodeType.derivedFrom = BlueprintConstants.MODEL_TYPE_NODES_ROOT - nodeType.version = dslComponent.version - nodeType.description = dslComponent.description - nodeType.interfaces = populateInterfaceDefinitions(dslComponent, nodeType) - return nodeType - } - - private fun populateInterfaceDefinitions(dslComponent: DSLComponent, nodeType: NodeType): MutableMap { - - // Populate Node Type Attribute - nodeType.attributes = attributeDefinitions(dslComponent.attributes) - - val operationDefinition = OperationDefinition() - operationDefinition.inputs = propertyDefinitions(dslComponent.inputs) - operationDefinition.outputs = propertyDefinitions(dslComponent.outputs) - - val operations: MutableMap = hashMapOf() - operations[BlueprintConstants.DEFAULT_STEP_OPERATION] = operationDefinition - - val interfaceDefinition = InterfaceDefinition() - interfaceDefinition.operations = operations - - val interfaces: MutableMap = hashMapOf() - interfaces[BlueprintConstants.DEFAULT_STEP_INTERFACE] = interfaceDefinition - return interfaces - } - - private fun populateInterfaceAssignments(dslComponent: DSLRegistryComponent): MutableMap { - val operationAssignment = OperationAssignment() - operationAssignment.implementation = dslComponent.implementation - operationAssignment.inputs = dslComponent.inputs - operationAssignment.outputs = dslComponent.outputs - - val operations: MutableMap = hashMapOf() - operations[BlueprintConstants.DEFAULT_STEP_OPERATION] = operationAssignment - - val interfaceAssignment = InterfaceAssignment() - interfaceAssignment.operations = operations - - val interfaces: MutableMap = hashMapOf() - interfaces[dslComponent.interfaceName] = interfaceAssignment - return interfaces - } - - private fun populateInterfaceAssignments(dslComponent: DSLComponent): MutableMap { - val operationAssignment = OperationAssignment() - operationAssignment.implementation = dslComponent.implementation - operationAssignment.inputs = propertyAssignments(dslComponent.inputs) - operationAssignment.outputs = propertyAssignments(dslComponent.outputs) - - val operations: MutableMap = hashMapOf() - operations[BlueprintConstants.DEFAULT_STEP_OPERATION] = operationAssignment - - val interfaceAssignment = InterfaceAssignment() - interfaceAssignment.operations = operations - - val interfaces: MutableMap = hashMapOf() - interfaces[BlueprintConstants.DEFAULT_STEP_INTERFACE] = interfaceAssignment - return interfaces - } - - private fun propertyDefinitions(propertyDefinitions: Map?): MutableMap? { - val definitions: MutableMap? = propertyDefinitions?.bpClone()?.toMutableMap() - - definitions?.forEach { (_, prop) -> - prop.value = null - } - return definitions - } - - private fun attributeDefinitions(attributeDefinitions: Map?): MutableMap? { - val definitions: MutableMap? = attributeDefinitions?.bpClone()?.toMutableMap() - - definitions?.forEach { (_, prop) -> - prop.value = null - } - return definitions - } - - private fun propertyAssignments(propertyDefinitions: Map?): MutableMap? { - var assignments: MutableMap? = null - if (propertyDefinitions != null) { - assignments = hashMapOf() - propertyDefinitions.forEach { (propertyName, property) -> - assignments[propertyName] = property.value ?: NullNode.instance - } - } - return assignments - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTemplateDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTemplateDSLBuilder.kt deleted file mode 100644 index f8f6080ad..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTemplateDSLBuilder.kt +++ /dev/null @@ -1,482 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import kotlin.reflect.KClass -import kotlin.reflect.KMutableProperty1 -import kotlin.reflect.full.createInstance -import kotlin.reflect.jvm.reflect - -open class TopologyTemplateBuilder { - - private var topologyTemplate = TopologyTemplate() - var nodeTemplates: MutableMap? = null - var relationshipTemplates: MutableMap? = null - private var workflows: MutableMap? = null - - fun nodeTemplate(id: String, type: String, description: String, block: NodeTemplateBuilder.() -> Unit) { - if (nodeTemplates == null) nodeTemplates = hashMapOf() - nodeTemplates!![id] = NodeTemplateBuilder(id, type, description).apply(block).build() - } - - fun nodeTemplate(nodeTemplate: NodeTemplate) { - if (nodeTemplates == null) nodeTemplates = hashMapOf() - nodeTemplates!![nodeTemplate.id!!] = nodeTemplate - } - - fun relationshipTemplate( - id: String, - type: String, - description: String, - block: RelationshipTemplateBuilder.() -> Unit - ) { - if (relationshipTemplates == null) relationshipTemplates = hashMapOf() - relationshipTemplates!![id] = RelationshipTemplateBuilder(id, type, description).apply(block).build() - } - - fun relationshipTemplate(relationshipTemplate: RelationshipTemplate) { - if (relationshipTemplates == null) relationshipTemplates = hashMapOf() - relationshipTemplates!![relationshipTemplate.id!!] = relationshipTemplate - } - - fun nodeTemplateOperation( - nodeTemplateName: String, - type: String, - interfaceName: String, - description: String, - operationBlock: OperationAssignmentBuilder.() -> Unit - ) { - if (nodeTemplates == null) nodeTemplates = hashMapOf() - - val nodeTemplateBuilder = NodeTemplateBuilder(nodeTemplateName, type, description) - nodeTemplateBuilder.operation(interfaceName, "$description operation", operationBlock) - nodeTemplates!![nodeTemplateName] = nodeTemplateBuilder.build() - } - - fun workflow(id: String, description: String, block: WorkflowBuilder.() -> Unit) { - if (workflows == null) workflows = hashMapOf() - workflows!![id] = WorkflowBuilder(id, description).apply(block).build() - } - - fun workflow(workflow: Workflow) { - if (workflows == null) workflows = hashMapOf() - workflows!![workflow.id!!] = workflow - } - - // TODO("populate inputs, outputs") - fun workflowNodeTemplate( - actionName: String, - nodeTemplateType: String, - description: String, - block: NodeTemplateBuilder.() -> Unit - ) { - if (nodeTemplates == null) nodeTemplates = hashMapOf() - - if (workflows == null) workflows = hashMapOf() - - val workflowBuilder = WorkflowBuilder(actionName, description) - workflowBuilder.nodeTemplateStep(actionName, description) - // Workflow name is NodeTemplate name - workflows!![actionName] = workflowBuilder.build() - - nodeTemplates!![actionName] = - NodeTemplateBuilder(actionName, nodeTemplateType, description).apply(block).build() - } - - fun build(): TopologyTemplate { - topologyTemplate.nodeTemplates = nodeTemplates - topologyTemplate.relationshipTemplates = relationshipTemplates - topologyTemplate.workflows = workflows - return topologyTemplate - } -} - -open class NodeTemplateBuilder( - private val id: String, - private val type: String, - private val description: String? = "" -) { - - var nodeTemplate: NodeTemplate = NodeTemplate() - var properties: MutableMap? = null - var interfaces: MutableMap? = null - var artifacts: MutableMap? = null - var capabilities: MutableMap? = null - var requirements: MutableMap? = null - - fun properties(properties: Map) { - if (this.properties == null) this.properties = hashMapOf() - this.properties!!.putAll(properties) - } - - fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { - if (properties == null) properties = hashMapOf() - properties = PropertiesAssignmentBuilder().apply(block).build() - } - - open fun typedProperties(block: Prop.() -> Unit) { - if (properties == null) properties = hashMapOf() - val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() - properties = instance.apply(block).build() - } - - open fun typedOperation( - interfaceName: String, - description: String = "", - block: OperationAssignmentBuilder.() -> Unit - ) { - if (interfaces == null) interfaces = hashMapOf() - - val interfaceAssignment = InterfaceAssignment() - val defaultOperationName = BlueprintConstants.DEFAULT_STEP_OPERATION - interfaceAssignment.operations = hashMapOf() - interfaceAssignment.operations!![defaultOperationName] = - OperationAssignmentBuilder(defaultOperationName, description).apply(block).build() - interfaces!![interfaceName] = interfaceAssignment - } - - fun operation( - interfaceName: String, - description: String, - block: OperationAssignmentBuilder.() -> Unit - ) { - typedOperation(interfaceName, description, block) - } - - fun artifact(id: String, type: String, file: String) { - if (artifacts == null) artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() - } - - fun artifact(id: String, type: String, file: String, block: ArtifactDefinitionBuilder.() -> Unit) { - if (artifacts == null) artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).apply(block).build() - } - - fun artifacts(artifacts: MutableMap?) { - this.artifacts = artifacts - } - - fun capability(id: String, block: CapabilityAssignmentBuilder.() -> Unit) { - if (capabilities == null) capabilities = hashMapOf() - capabilities!![id] = CapabilityAssignmentBuilder(id).apply(block).build() - } - - fun capabilities(capabilities: MutableMap) { - if (this.capabilities == null) this.capabilities = hashMapOf() - this.capabilities!!.putAll(capabilities) - } - - fun requirement(id: String, capability: String, node: String, relationship: String) { - if (requirements == null) requirements = hashMapOf() - requirements!![id] = RequirementAssignmentBuilder(id, capability, node, relationship).build() - } - - fun requirements(requirements: MutableMap) { - if (this.requirements == null) this.requirements = hashMapOf() - this.requirements!!.putAll(requirements) - } - - open fun build(): NodeTemplate { - nodeTemplate.id = id - nodeTemplate.type = type - nodeTemplate.description = description - nodeTemplate.properties = properties - nodeTemplate.interfaces = interfaces - nodeTemplate.artifacts = artifacts - nodeTemplate.capabilities = capabilities - nodeTemplate.requirements = requirements - return nodeTemplate - } -} - -open class RelationshipTemplateBuilder( - private val id: String, - private val type: String, - private val description: String? = "" -) { - - var relationshipTemplate: RelationshipTemplate = RelationshipTemplate() - var properties: MutableMap? = null - - fun properties(properties: Map) { - if (this.properties == null) this.properties = hashMapOf() - this.properties!!.putAll(properties) - } - - fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { - if (properties == null) properties = hashMapOf() - properties = PropertiesAssignmentBuilder().apply(block).build() - } - - fun property(id: String, value: Any) { - if (properties == null) properties = hashMapOf() - properties!![id] = value.asJsonType() - } - - fun property(id: String, value: JsonNode) { - if (properties == null) properties = hashMapOf() - properties!![id] = value - } - - fun copy(copy: String) { - relationshipTemplate.copy = copy - } - - open fun typedProperties(block: Prop.() -> Unit) { - if (properties == null) properties = hashMapOf() - val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() - properties = instance.apply(block).build() - } - - open fun build(): RelationshipTemplate { - relationshipTemplate.id = id - relationshipTemplate.type = type - relationshipTemplate.description = description - relationshipTemplate.properties = properties - return relationshipTemplate - } -} - -class ArtifactDefinitionBuilder(private val id: String, private val type: String, private val file: String) { - - private var artifactDefinition: ArtifactDefinition = ArtifactDefinition() - private var properties: MutableMap? = null - - fun repository(repository: String) { - artifactDefinition.repository = repository - } - - fun deployPath(deployPath: String) { - artifactDefinition.deployPath = deployPath - } - - fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { - if (properties == null) - properties = hashMapOf() - properties = PropertiesAssignmentBuilder().apply(block).build() - } - - fun build(): ArtifactDefinition { - artifactDefinition.id = id - artifactDefinition.type = type - artifactDefinition.file = file - artifactDefinition.properties = properties - return artifactDefinition - } -} - -open class CapabilityAssignmentBuilder(private val id: String) { - - var capabilityAssignment: CapabilityAssignment = CapabilityAssignment() - var attributes: MutableMap? = null - var properties: MutableMap? = null - - fun attributes(block: AttributesAssignmentBuilder.() -> Unit) { - if (attributes == null) attributes = hashMapOf() - attributes = AttributesAssignmentBuilder().apply(block).build() - } - - fun properties(block: PropertiesAssignmentBuilder.() -> Unit) { - if (properties == null) properties = hashMapOf() - properties = PropertiesAssignmentBuilder().apply(block).build() - } - - fun property(id: String, value: Any) { - if (properties == null) properties = hashMapOf() - properties!![id] = value.asJsonType() - } - - fun property(id: String, value: JsonNode) { - if (properties == null) properties = hashMapOf() - properties!![id] = value - } - - open fun build(): CapabilityAssignment { - capabilityAssignment.properties = properties - capabilityAssignment.attributes = attributes - return capabilityAssignment - } -} - -open class RequirementAssignmentBuilder( - private val id: String, - private val capability: String, - private val node: String, - private val relationship: String -) { - - private var requirementAssignment: RequirementAssignment = RequirementAssignment() - - fun build(): RequirementAssignment { - requirementAssignment.id = id - requirementAssignment.capability = capability - requirementAssignment.node = node - requirementAssignment.relationship = relationship - return requirementAssignment - } -} - -class InterfaceAssignmentBuilder(private val id: String) { - - private var interfaceAssignment: InterfaceAssignment = InterfaceAssignment() - private var operations: MutableMap? = null - - fun operation( - id: String, - description: String? = "", - block: OperationAssignmentBuilder.() -> Unit - ) { - if (operations == null) - operations = hashMapOf() - operations!![id] = OperationAssignmentBuilder( - id, description - ).apply(block).build() - } - - fun build(): InterfaceAssignment { - interfaceAssignment.id = id - interfaceAssignment.operations = operations - return interfaceAssignment - } -} - -class OperationAssignmentBuilder( - private val id: String, - private val description: String? = "" -) { - - private var operationAssignment: OperationAssignment = OperationAssignment() - - fun implementation(implementation: Implementation?) { - operationAssignment.implementation = implementation - } - - fun implementation(timeout: Int, operationHost: String? = BlueprintConstants.PROPERTY_SELF) { - operationAssignment.implementation = Implementation().apply { - this.operationHost = operationHost!! - this.timeout = timeout - } - } - - fun implementation( - timeout: Int, - operationHost: String? = BlueprintConstants.PROPERTY_SELF, - block: ImplementationBuilder.() -> Unit - ) { - operationAssignment.implementation = ImplementationBuilder(timeout, operationHost!!).apply(block).build() - } - - fun inputs(inputs: MutableMap?) { - operationAssignment.inputs = inputs - } - - fun inputs(block: In.() -> Unit) { - val instance: In = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() - operationAssignment.inputs = instance.apply(block).build() - } - - fun outputs(outputs: MutableMap?) { - operationAssignment.outputs = outputs - } - - fun outputs(block: Out.() -> Unit) { - val instance: Out = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass).createInstance() - operationAssignment.outputs = instance.apply(block).build() - } - - fun build(): OperationAssignment { - operationAssignment.id = id - operationAssignment.description = description - return operationAssignment - } -} - -class ImplementationBuilder(private val timeout: Int, private val operationHost: String) { - - private val implementation = Implementation() - - fun primary(primary: String) { - implementation.primary = primary - } - - fun dependencies(vararg dependencies: String) { - if (implementation.dependencies == null) - implementation.dependencies = arrayListOf() - dependencies.forEach { - implementation.dependencies!!.add(it) - } - } - - fun build(): Implementation { - implementation.timeout = timeout - implementation.operationHost = operationHost - return implementation - } -} - -open class PropertiesAssignmentBuilder { - - var properties: MutableMap = hashMapOf() - - fun property(id: String, value: Any) { - property(id, value.asJsonType()) - } - - fun property(id: String, value: JsonNode) { - properties[id] = value - } - - fun property(kProperty: KMutableProperty1<*, *>, value: JsonNode) { - properties[kProperty.name] = value - } - - open fun build(): MutableMap { - return properties - } -} - -open class AttributesAssignmentBuilder { - - var attributes: MutableMap = hashMapOf() - - fun attribute(id: String, value: String) { - attribute(id, value.asJsonType()) - } - - fun attribute(id: String, value: JsonNode) { - attributes[id] = value - } - - fun build(): MutableMap { - return attributes - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTypeDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTypeDSLBuilder.kt deleted file mode 100644 index 3b3b4b41f..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintTypeDSLBuilder.kt +++ /dev/null @@ -1,585 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ArrayNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType -import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType - -open class EntityTypeBuilder( - private val id: String, - private val version: String, - private val derivedFrom: String, - private val description: String? = "" -) { - - var metadata: MutableMap? = null - var properties: MutableMap? = null - var attributes: MutableMap? = null - - fun metadata(key: String, value: String) { - if (metadata == null) - metadata = hashMapOf() - metadata!![key] = value - } - - fun attribute(id: String, type: String, required: Boolean, description: String? = "") { - if (attributes == null) - attributes = hashMapOf() - val attribute = AttributeDefinitionBuilder(id, type, required, description).build() - attributes!![id] = attribute - } - - fun attribute( - id: String, - type: String, - required: Boolean, - description: String? = "", - block: AttributeDefinitionBuilder.() -> Unit - ) { - if (attributes == null) - attributes = hashMapOf() - val attribute = AttributeDefinitionBuilder(id, type, required, description).apply(block).build() - attributes!![id] = attribute - } - - fun property(id: String, type: String, required: Boolean, description: String? = "") { - if (properties == null) - properties = hashMapOf() - val property = PropertyDefinitionBuilder(id, type, required, description).build() - properties!![id] = property - } - - fun property( - id: String, - type: String, - required: Boolean, - description: String? = "", - block: PropertyDefinitionBuilder.() -> Unit - ) { - if (properties == null) - properties = hashMapOf() - val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() - properties!![id] = property - } - - fun buildEntityType(entity: EntityType) { - entity.id = id - entity.description = description - entity.version = version - entity.derivedFrom = derivedFrom - entity.metadata = metadata - entity.properties = properties - entity.attributes = attributes - } -} - -class NodeTypeBuilder( - id: String, - version: String, - derivedFrom: String, - description: String? -) : EntityTypeBuilder(id, version, derivedFrom, description) { - - private var nodeType = NodeType() - private var capabilities: MutableMap? = null - private var requirements: MutableMap? = null - private var interfaces: MutableMap? = null - private var artifacts: MutableMap? = null - - fun capability(id: String, type: String, description: String, block: CapabilityDefinitionBuilder.() -> Unit) { - if (capabilities == null) - capabilities = hashMapOf() - capabilities!![id] = CapabilityDefinitionBuilder(id, type, description).apply(block).build() - } - - fun requirement(id: String, capability: String, node: String, relationship: String, description: String) { - if (requirements == null) - requirements = hashMapOf() - requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description).build() - } - - fun requirement( - id: String, - capability: String, - node: String, - relationship: String, - description: String, - block: RequirementDefinitionBuilder.() -> Unit - ) { - if (requirements == null) - requirements = hashMapOf() - requirements!![id] = RequirementDefinitionBuilder(id, capability, node, relationship, description) - .apply(block).build() - } - - fun artifact(id: String, type: String, file: String) { - if (artifacts == null) - artifacts = hashMapOf() - artifacts!![id] = ArtifactDefinitionBuilder(id, type, file).build() - } - - private fun nodeInterface(id: String, block: InterfaceDefinitionBuilder.() -> Unit) { - if (interfaces == null) - interfaces = hashMapOf() - interfaces!![id] = InterfaceDefinitionBuilder(id).apply(block).build() - } - - fun operation(interfaceName: String, description: String?, block: OperationDefinitionBuilder.() -> Unit) { - if (interfaces == null) - interfaces = hashMapOf() - - val interfaceDefinition = InterfaceDefinition() - val defaultOperationName = "process" - interfaceDefinition.operations = hashMapOf() - interfaceDefinition.operations!![defaultOperationName] = - OperationDefinitionBuilder(defaultOperationName, description).apply(block).build() - interfaces!![interfaceName] = interfaceDefinition - } - - fun build(): NodeType { - buildEntityType(nodeType) - nodeType.capabilities = capabilities - nodeType.requirements = requirements - nodeType.interfaces = interfaces - nodeType.artifacts = artifacts - return nodeType - } -} - -class ArtifactTypeBuilder( - id: String, - version: String, - derivedFrom: String, - description: String? -) : EntityTypeBuilder(id, version, derivedFrom, description) { - - private var artifactType = ArtifactType() - private var fileExt: MutableList? = null - - fun fileExt(vararg fileExts: String) { - if (fileExt == null) - fileExt = arrayListOf() - fileExts.forEach { - fileExt!!.add(it) - } - } - - fun build(): ArtifactType { - buildEntityType(artifactType) - artifactType.fileExt = fileExt - return artifactType - } -} - -class PolicyTypeBuilder( - id: String, - version: String, - derivedFrom: String, - description: String? -) : EntityTypeBuilder(id, version, derivedFrom, description) { - - private var policyType = PolicyType() - - fun targets(targetsStr: String) { - val arrayNode = targetsStr.jsonAsJsonType() as ArrayNode - targets(arrayNode.asListOfString()) - } - - fun targets(target: List) { - policyType.targets = target.toMutableList() - } - - fun build(): PolicyType { - buildEntityType(policyType) - return policyType - } -} - -class RelationshipTypeBuilder( - private val id: String, - private val version: String, - derivedFrom: String, - private val description: String? -) : - EntityTypeBuilder(id, version, derivedFrom, description) { - - private var relationshipType = RelationshipType() - - fun validTargetTypes(validTargetTypesStr: String) { - val arrayNode = validTargetTypesStr.jsonAsJsonType() as ArrayNode - validTargetTypes(arrayNode.asListOfString()) - } - - fun validTargetTypes(validTargetTypes: List) { - relationshipType.validTargetTypes = validTargetTypes.toMutableList() - } - - fun build(): RelationshipType { - buildEntityType(relationshipType) - relationshipType.id = id - relationshipType.version = version - relationshipType.description = description - return relationshipType - } -} - -class DataTypeBuilder( - id: String, - version: String, - derivedFrom: String, - description: String? -) : EntityTypeBuilder(id, version, derivedFrom, description) { - - private var dataType = DataType() - - fun constrain(block: ConstraintClauseBuilder.() -> Unit) { - if (dataType.constraints == null) { - dataType.constraints = mutableListOf() - } - val constraintClause = ConstraintClauseBuilder().apply(block).build() - dataType.constraints!!.add(constraintClause) - } - - fun build(): DataType { - buildEntityType(dataType) - return dataType - } -} - -class CapabilityDefinitionBuilder(private val id: String, private val type: String, private val description: String? = "") { - - private var capabilityDefinition = CapabilityDefinition() - private val properties: MutableMap = hashMapOf() - - fun property(id: String, type: String? = BlueprintConstants.DATA_TYPE_STRING, required: Boolean? = false, description: String? = "") { - val property = PropertyDefinitionBuilder(id, type, required, description).build() - properties[id] = property - } - - fun build(): CapabilityDefinition { - capabilityDefinition.id = id - capabilityDefinition.description = description - capabilityDefinition.type = type - capabilityDefinition.properties = properties - return capabilityDefinition - } -} - -class RequirementDefinitionBuilder( - private val id: String, - private val capability: String, - private val node: String, - private val relationship: String, - private val description: String? = "" -) { - - private var requirementDefinition = RequirementDefinition() - - fun build(): RequirementDefinition { - requirementDefinition.id = id - requirementDefinition.description = description - requirementDefinition.capability = capability - requirementDefinition.node = node - requirementDefinition.relationship = relationship - return requirementDefinition - } -} - -class InterfaceDefinitionBuilder(private val id: String) { - - private var interfaceDefinition: InterfaceDefinition = InterfaceDefinition() - private var operations: MutableMap? = null - - fun operation(id: String, description: String? = "", block: OperationDefinitionBuilder.() -> Unit) { - if (operations == null) - operations = hashMapOf() - operations!![id] = OperationDefinitionBuilder(id, description).apply(block).build() - } - - fun build(): InterfaceDefinition { - interfaceDefinition.id = id - interfaceDefinition.operations = operations - return interfaceDefinition - } -} - -class OperationDefinitionBuilder( - private val id: String, - private val description: String? = "" -) { - - private var operationDefinition: OperationDefinition = OperationDefinition() - - fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { - operationDefinition.inputs = PropertiesDefinitionBuilder().apply(block).build() - } - - fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { - operationDefinition.outputs = PropertiesDefinitionBuilder().apply(block).build() - } - - fun build(): OperationDefinition { - operationDefinition.id = id - operationDefinition.description = description - return operationDefinition - } -} - -class AttributeDefinitionBuilder( - private val id: String, - private val type: String? = BlueprintConstants.DATA_TYPE_STRING, - private val required: Boolean? = false, - private val description: String? = "" -) { - - private var attributeDefinition: AttributeDefinition = AttributeDefinition() - - fun entrySchema(entrySchemaType: String) { - attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() - } - - fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { - attributeDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() - } - - fun constrain(block: ConstraintClauseBuilder.() -> Unit) { - if (attributeDefinition.constraints == null) { - attributeDefinition.constraints = mutableListOf() - } - val constraintClause = ConstraintClauseBuilder().apply(block).build() - attributeDefinition.constraints!!.add(constraintClause) - } - - fun defaultValue(defaultValue: Any) { - defaultValue(defaultValue.asJsonType()) - } - - fun defaultValue(defaultValue: JsonNode) { - attributeDefinition.defaultValue = defaultValue - } - - fun build(): AttributeDefinition { - attributeDefinition.id = id - attributeDefinition.type = type!! - attributeDefinition.required = required - attributeDefinition.description = description - return attributeDefinition - } -} - -class PropertiesDefinitionBuilder { - - private val properties: MutableMap = hashMapOf() - - fun property(id: String, property: PropertyDefinition) { - properties[id] = property - } - - fun property(id: String, type: String?, required: Boolean?, description: String? = "") { - val property = PropertyDefinitionBuilder(id, type, required, description).build() - properties[id] = property - } - - fun property( - id: String, - type: String?, - required: Boolean?, - description: String? = "", - block: PropertyDefinitionBuilder.() -> Unit - ) { - val property = PropertyDefinitionBuilder(id, type, required, description).apply(block).build() - properties[id] = property - } - - fun build(): MutableMap { - return properties - } -} - -class PropertyDefinitionBuilder( - private val id: String, - private val type: String? = BlueprintConstants.DATA_TYPE_STRING, - private val required: Boolean? = false, - private val description: String? = "" -) { - - private var propertyDefinition: PropertyDefinition = PropertyDefinition() - - fun entrySchema(entrySchemaType: String) { - propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).build() - } - - fun entrySchema(entrySchemaType: String, block: EntrySchemaBuilder.() -> Unit) { - propertyDefinition.entrySchema = EntrySchemaBuilder(entrySchemaType).apply(block).build() - } - - fun constrain(block: ConstraintClauseBuilder.() -> Unit) { - if (propertyDefinition.constraints == null) { - propertyDefinition.constraints = mutableListOf() - } - val constraintClause = ConstraintClauseBuilder().apply(block).build() - propertyDefinition.constraints!!.add(constraintClause) - } - - fun defaultValue(defaultValue: Any) { - defaultValue(defaultValue.asJsonType()) - } - - fun defaultValue(defaultValue: JsonNode) { - propertyDefinition.defaultValue = defaultValue - } - - fun metadata(name: String, value: String) { - if (propertyDefinition.metadata == null) { - propertyDefinition.metadata = hashMapOf() - } - propertyDefinition.metadata!![name] = value - } - - fun value(value: Any) { - value(value.asJsonType()) - } - - fun value(value: JsonNode) { - propertyDefinition.value = value - } - - fun build(): PropertyDefinition { - propertyDefinition.id = id - propertyDefinition.type = type!! - propertyDefinition.required = required - propertyDefinition.description = description - return propertyDefinition - } -} - -class ConstraintsClauseBuilder { - - val constraints: MutableList = mutableListOf() - - fun constrain(block: ConstraintClauseBuilder.() -> Unit) { - val constraintClause = ConstraintClauseBuilder().apply(block).build() - constraints.add(constraintClause) - } - - fun build(): MutableList { - return constraints - } -} - -class ConstraintClauseBuilder { - - private val constraintClause = ConstraintClause() - - fun equal(equal: Any) = equal(equal.asJsonType()) - - fun equal(equal: JsonNode) { - constraintClause.equal = equal - } - - fun greaterOrEqual(greaterOrEqual: Any) { - constraintClause.greaterOrEqual = greaterOrEqual.asJsonPrimitive() - } - - fun greaterThan(greaterThan: Any) { - constraintClause.greaterThan = greaterThan.asJsonPrimitive() - } - - fun lessOrEqual(lessOrEqual: Any) { - constraintClause.lessOrEqual = lessOrEqual.asJsonPrimitive() - } - - fun lessThan(lessThan: Any) { - constraintClause.lessThan = lessThan.asJsonPrimitive() - } - - fun inRange(inRangeStr: String) = inRange(inRangeStr.jsonAsJsonType() as ArrayNode) - - fun inRange(inRangeNode: ArrayNode) { - constraintClause.inRange = inRangeNode.toMutableList() - } - - fun validValues(validValuesStr: String) = validValues(validValuesStr.jsonAsJsonType() as ArrayNode) - - fun validValues(validValuesNode: ArrayNode) = validValues(validValuesNode.toMutableList()) - - fun validValues(validValues: List) { - constraintClause.validValues = validValues.toMutableList() - } - - fun length(length: Any) { - constraintClause.length = length.asJsonPrimitive() - } - - fun minLength(minLength: Any) { - constraintClause.minLength = minLength.asJsonPrimitive() - } - - fun maxLength(maxLength: Any) { - constraintClause.maxLength = maxLength.asJsonPrimitive() - } - - fun pattern(pattern: String) { - constraintClause.pattern = pattern - } - - fun schema(schema: String) { - constraintClause.schema = schema - } - - fun build(): ConstraintClause { - return constraintClause - } -} - -class EntrySchemaBuilder(private val type: String) { - - private var entrySchema: EntrySchema = EntrySchema() - - fun constrain(block: ConstraintClauseBuilder.() -> Unit) { - if (entrySchema.constraints == null) { - entrySchema.constraints = mutableListOf() - } - val constraintClause = ConstraintClauseBuilder().apply(block).build() - entrySchema.constraints!!.add(constraintClause) - } - - fun build(): EntrySchema { - entrySchema.type = type - return entrySchema - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintWorkflowDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintWorkflowDSLBuilder.kt deleted file mode 100644 index 0de1a510c..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintWorkflowDSLBuilder.kt +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap -import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import kotlin.reflect.KClass - -class WorkflowBuilder(private val id: String, private val description: String) { - - private var workflow = Workflow() - private var steps: MutableMap? = null - private var inputs: MutableMap? = null - private var outputs: MutableMap? = null - - // Used Internally - fun nodeTemplateStep(nodeTemplateName: String, description: String) { - step(nodeTemplateName, nodeTemplateName, "$description step") - } - - fun step(id: String, target: String, description: String) { - if (steps == null) - steps = hashMapOf() - steps!![id] = StepBuilder(id, target, description).build() - } - - fun step(id: String, target: String, description: String, block: StepBuilder.() -> Unit) { - if (steps == null) - steps = hashMapOf() - steps!![id] = StepBuilder(id, target, description).apply(block).build() - } - - fun inputs(kClazz: KClass<*>) { - inputs = kClazz.asPropertyDefinitionMap() - } - - fun inputs(block: PropertiesDefinitionBuilder.() -> Unit) { - inputs = PropertiesDefinitionBuilder().apply(block).build() - } - - fun outputs(block: PropertiesDefinitionBuilder.() -> Unit) { - outputs = PropertiesDefinitionBuilder().apply(block).build() - } - - fun outputs(kClazz: KClass<*>) { - outputs = kClazz.asPropertyDefinitionMap() - } - - fun build(): Workflow { - workflow.id = id - workflow.description = description - workflow.steps = steps - workflow.inputs = inputs - workflow.outputs = outputs - return workflow - } -} - -class StepBuilder( - private val id: String, - private val target: String, - private val description: String -) { - - private var step = Step() - private var activities: ArrayList = arrayListOf() - private var onSuccess: ArrayList? = null - private var onFailure: ArrayList? = null - - fun activity(callOperation: String) { - val activity = Activity() - activity.callOperation = callOperation - activities.add(activity) - } - - fun success(vararg successTargets: String) { - if (onSuccess == null) - onSuccess = arrayListOf() - successTargets.forEach { - onSuccess!!.add(it) - } - } - - fun failure(vararg failureTargets: String) { - if (onFailure == null) - onFailure = arrayListOf() - failureTargets.forEach { - onFailure!!.add(it) - } - } - - fun build(): Step { - step.id = id - step.target = target - // Add Default Activity, Assumption is only one Operation - activity(".${BlueprintConstants.DEFAULT_STEP_OPERATION}") - step.description = description - step.activities = activities - step.onSuccess = onSuccess - step.onFailure = onFailure - return step - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/ServiceTemplateBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/ServiceTemplateBuilder.kt index 4391e89e0..254e644b3 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/ServiceTemplateBuilder.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/ServiceTemplateBuilder.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.controllerblueprints.core.dsl import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asBlueprintsDataTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asBluePrintsDataTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap @@ -51,10 +51,10 @@ class ServiceTemplateBuilder( var policyTypes: MutableMap? = null private fun initMetaData() { - metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] = name - metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] = version - metadata[BlueprintConstants.METADATA_TEMPLATE_AUTHOR] = author - metadata[BlueprintConstants.METADATA_TEMPLATE_TAGS] = tags + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = name + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = version + metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] = author + metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] = tags } fun metadata(id: String, value: String) { @@ -73,7 +73,7 @@ class ServiceTemplateBuilder( } fun dataType(dataType: KClass<*>) { - dataType(dataType.asBlueprintsDataTypes()) + dataType(dataType.asBluePrintsDataTypes()) } fun dsl(id: String, content: Any) { diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt new file mode 100755 index 000000000..bd45bed06 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import java.io.File +import java.nio.file.Path + +interface BluePrintCatalogService { + + /** + * Save the CBA to database. + * @param processingId Processing Id + * @param blueprintFile Either a directory, or an archive + * @param validate whether to validate blueprint content. Default true. + * @return The unique blueprint identifier + * @throws BluePrintException if process failed + */ + @Throws(BluePrintException::class) + suspend fun saveToDatabase(processingId: String, blueprintFile: File, validate: Boolean = true): String + + /** + * Retrieve the CBA from database either archived or extracted. + * @param name Name of the blueprint + * @param version Version of the blueprint + * @param extract true to extract the content, false for archived content. Default to true + * @return Path where CBA is located + * @throws BluePrintException if process failed + */ + + @Throws(BluePrintException::class) + suspend fun getFromDatabase(name: String, version: String, extract: Boolean = true): Path + + /** + * Delete the CBA from database. + * @param name Name of the blueprint + * @param version Version of the blueprint + * @throws BluePrintException if process failed + */ + + @Throws(BluePrintException::class) + suspend fun deleteFromDatabase(name: String, version: String) +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt new file mode 100644 index 000000000..fcc9bf2d7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt @@ -0,0 +1,60 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate + +interface BluePrintDefinitions { + + /** Define the service Template Model */ + fun serviceTemplate(): ServiceTemplate + + /** Load Custom Definitions that may used during runtime **/ + fun loadOtherDefinitions() + + /** Utility Method to add the definition */ + fun addOtherDefinition(key: String, definition: Any) + + /** Utility method to get the definition */ + fun otherDefinition(key: String): T + + fun otherDefinitions(): MutableMap +} + +abstract class AbstractBluePrintDefinitions : BluePrintDefinitions { + + private val otherDefinitionMap: MutableMap = hashMapOf() + + constructor() { + loadOtherDefinitions() + } + + override fun loadOtherDefinitions() { + } + + override fun otherDefinition(key: String): T { + return otherDefinitionMap[key] as T + } + + override fun addOtherDefinition(key: String, definition: Any) { + otherDefinitionMap[key] = definition + } + + override fun otherDefinitions(): MutableMap { + return otherDefinitionMap + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt new file mode 100644 index 000000000..2080cd161 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt @@ -0,0 +1,242 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BluePrintEnhancer { + + fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T) +} + +interface BluePrintServiceTemplateEnhancer : BluePrintEnhancer + +interface BluePrintTopologyTemplateEnhancer : BluePrintEnhancer + +interface BluePrintWorkflowEnhancer : BluePrintEnhancer + +interface BluePrintNodeTemplateEnhancer : BluePrintEnhancer + +interface BluePrintNodeTypeEnhancer : BluePrintEnhancer + +interface BluePrintRelationshipTemplateEnhancer : BluePrintEnhancer + +interface BluePrintRelationshipTypeEnhancer : BluePrintEnhancer + +interface BluePrintArtifactDefinitionEnhancer : BluePrintEnhancer + +interface BluePrintPolicyTypeEnhancer : BluePrintEnhancer + +interface BluePrintPropertyDefinitionEnhancer : BluePrintEnhancer + +interface BluePrintAttributeDefinitionEnhancer : BluePrintEnhancer + +interface BluePrintEnhancerService { + + @Throws(BluePrintException::class) + suspend fun enhance(basePath: String, enrichedBasePath: String): BluePrintContext + + @Throws(BluePrintException::class) + suspend fun enhance(basePath: String): BluePrintContext +} + +interface BluePrintTypeEnhancerService { + + fun getServiceTemplateEnhancers(): List + + fun getTopologyTemplateEnhancers(): List + + fun getWorkflowEnhancers(): List + + fun getNodeTemplateEnhancers(): List + + fun getNodeTypeEnhancers(): List + + fun getRelationshipTemplateEnhancers(): List + + fun getRelationshipTypeEnhancers(): List + + fun getArtifactDefinitionEnhancers(): List + + fun getPolicyTypeEnhancers(): List + + fun getPropertyDefinitionEnhancers(): List + + fun getAttributeDefinitionEnhancers(): List + + fun enhanceServiceTemplate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + serviceTemplate: ServiceTemplate + ) { + val enhancers = getServiceTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, serviceTemplate, enhancers) + } + + fun enhanceTopologyTemplate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + topologyTemplate: TopologyTemplate + ) { + val enhancers = getTopologyTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, topologyTemplate, enhancers) + } + + fun enhanceWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { + val enhancers = getWorkflowEnhancers() + doEnhancement(bluePrintRuntimeService, name, workflow, enhancers) + } + + fun enhanceNodeTemplate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + nodeTemplate: NodeTemplate + ) { + val enhancers = getNodeTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, nodeTemplate, enhancers) + } + + fun enhanceNodeType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { + val enhancers = getNodeTypeEnhancers() + doEnhancement(bluePrintRuntimeService, name, nodeType, enhancers) + } + + fun enhanceRelationshipTemplate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipTemplate: RelationshipTemplate + ) { + val enhancers = getRelationshipTemplateEnhancers() + doEnhancement(bluePrintRuntimeService, name, relationshipTemplate, enhancers) + } + + fun enhanceRelationshipType( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipType: RelationshipType + ) { + val enhancers = getRelationshipTypeEnhancers() + doEnhancement(bluePrintRuntimeService, name, relationshipType, enhancers) + } + + fun enhanceArtifactDefinition( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + artifactDefinition: ArtifactDefinition + ) { + val enhancers = getArtifactDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, artifactDefinition, enhancers) + } + + fun enhancePolicyType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, policyType: PolicyType) { + val enhancers = getPolicyTypeEnhancers() + doEnhancement(bluePrintRuntimeService, name, policyType, enhancers) + } + + fun enhancePropertyDefinitions( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + properties: MutableMap + ) { + val errorMap = linkedMapOf() + properties.forEach { propertyName, propertyDefinition -> + try { + enhancePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition) + } catch (e: BluePrintException) { + errorMap[propertyName] = e + } + } + if (errorMap.isNotEmpty()) { + val nestedErrors = errorMap.keys.map { "[ property: ${errorMap[it]?.message} ]" }.joinToString(";") + throw BluePrintException("Failed to enhance properties $nestedErrors") + } + } + + fun enhancePropertyDefinition( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + propertyDefinition: PropertyDefinition + ) { + val enhancers = getPropertyDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, propertyDefinition, enhancers) + } + + fun enhanceAttributeDefinitions( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + attributes: MutableMap + ) { + val errorMap = linkedMapOf() + attributes.forEach { attributeName, attributeDefinition -> + try { + enhanceAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition) + } catch (e: BluePrintException) { + errorMap[attributeName] = e + } + } + if (errorMap.isNotEmpty()) { + val nestedErrors = errorMap.keys.map { "[ attribute: ${errorMap[it]?.message} ]" }.joinToString(";") + throw BluePrintException("Failed to enhance attributes $nestedErrors") + } + } + + fun enhanceAttributeDefinition( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + attributeDefinition: AttributeDefinition + ) { + val enhancers = getAttributeDefinitionEnhancers() + doEnhancement(bluePrintRuntimeService, name, attributeDefinition, enhancers) + } + + @Suppress("UNCHECKED_CAST") + private fun doEnhancement( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + definition: Any, + enhancers: List> + ) { + if (enhancers.isNotEmpty()) { + val errorMap = linkedMapOf() + enhancers.forEach { + try { + it.enhance(bluePrintRuntimeService, name, definition as T) + } catch (e: BluePrintException) { + errorMap[name] = e + } + } + if (errorMap.isNotEmpty()) { + val nestedErrors = errorMap.keys.map { + "${errorMap[it]?.message ?: errorMap[it].toString()}" + }.joinToString(";") + throw BluePrintException("$name-->$nestedErrors") + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt new file mode 100644 index 000000000..8d04e5489 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt @@ -0,0 +1,50 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import java.io.Serializable + +/** + * BluePrintRepoFileService + * @author Brinda Santh + * + */ + +interface BluePrintRepoService : Serializable { + + @Throws(BluePrintException::class) + fun getNodeType(nodeTypeName: String): NodeType + + @Throws(BluePrintException::class) + fun getDataType(dataTypeName: String): DataType + + @Throws(BluePrintException::class) + fun getArtifactType(artifactTypeName: String): ArtifactType + + @Throws(BluePrintException::class) + fun getRelationshipType(relationshipTypeName: String): RelationshipType + + @Throws(BluePrintException::class) + fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt new file mode 100644 index 000000000..aa61b0c4d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt @@ -0,0 +1,39 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintSourceCode + +interface BluePrintScriptsService { + + suspend fun scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T + + suspend fun scriptInstance( + blueprintBasePath: String, + artifactName: String, + artifactVersion: String, + scriptClassName: String, + reCompile: Boolean + ): T + + suspend fun scriptInstance(blueprintBasePath: String, scriptClassName: String, reCompile: Boolean): T + + suspend fun scriptInstance(cacheKey: String, scriptClassName: String): T + + suspend fun scriptInstance(scriptClassName: String): T +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt new file mode 100644 index 000000000..70c797326 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt @@ -0,0 +1,28 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.interfaces + +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +interface BluePrintWorkflowExecutionService { + + suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: Input, + properties: MutableMap = hashMapOf() + ): Output +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintCatalogService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintCatalogService.kt deleted file mode 100644 index 87ee0e4f9..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintCatalogService.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import java.io.File -import java.nio.file.Path - -interface BlueprintCatalogService { - - /** - * Save the CBA to database. - * @param processingId Processing Id - * @param blueprintFile Either a directory, or an archive - * @param validate whether to validate blueprint content. Default true. - * @return The unique blueprint identifier - * @throws BlueprintException if process failed - */ - @Throws(BlueprintException::class) - suspend fun saveToDatabase(processingId: String, blueprintFile: File, validate: Boolean = true): String - - /** - * Retrieve the CBA from database either archived or extracted. - * @param name Name of the blueprint - * @param version Version of the blueprint - * @param extract true to extract the content, false for archived content. Default to true - * @return Path where CBA is located - * @throws BlueprintException if process failed - */ - - @Throws(BlueprintException::class) - suspend fun getFromDatabase(name: String, version: String, extract: Boolean = true): Path - - /** - * Delete the CBA from database. - * @param name Name of the blueprint - * @param version Version of the blueprint - * @throws BlueprintException if process failed - */ - - @Throws(BlueprintException::class) - suspend fun deleteFromDatabase(name: String, version: String) -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintDefinitions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintDefinitions.kt deleted file mode 100644 index 109bc7b85..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintDefinitions.kt +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate - -interface BlueprintDefinitions { - - /** Define the service Template Model */ - fun serviceTemplate(): ServiceTemplate - - /** Load Custom Definitions that may used during runtime **/ - fun loadOtherDefinitions() - - /** Utility Method to add the definition */ - fun addOtherDefinition(key: String, definition: Any) - - /** Utility method to get the definition */ - fun otherDefinition(key: String): T - - fun otherDefinitions(): MutableMap -} - -abstract class AbstractBlueprintDefinitions : BlueprintDefinitions { - - private val otherDefinitionMap: MutableMap = hashMapOf() - - constructor() { - loadOtherDefinitions() - } - - override fun loadOtherDefinitions() { - } - - override fun otherDefinition(key: String): T { - return otherDefinitionMap[key] as T - } - - override fun addOtherDefinition(key: String, definition: Any) { - otherDefinitionMap[key] = definition - } - - override fun otherDefinitions(): MutableMap { - return otherDefinitionMap - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintEnhancer.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintEnhancer.kt deleted file mode 100644 index 318fd2b91..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintEnhancer.kt +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService - -interface BlueprintEnhancer { - - fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: T) -} - -interface BlueprintServiceTemplateEnhancer : BlueprintEnhancer - -interface BlueprintTopologyTemplateEnhancer : BlueprintEnhancer - -interface BlueprintWorkflowEnhancer : BlueprintEnhancer - -interface BlueprintNodeTemplateEnhancer : BlueprintEnhancer - -interface BlueprintNodeTypeEnhancer : BlueprintEnhancer - -interface BlueprintRelationshipTemplateEnhancer : BlueprintEnhancer - -interface BlueprintRelationshipTypeEnhancer : BlueprintEnhancer - -interface BlueprintArtifactDefinitionEnhancer : BlueprintEnhancer - -interface BlueprintPolicyTypeEnhancer : BlueprintEnhancer - -interface BlueprintPropertyDefinitionEnhancer : BlueprintEnhancer - -interface BlueprintAttributeDefinitionEnhancer : BlueprintEnhancer - -interface BlueprintEnhancerService { - - @Throws(BlueprintException::class) - suspend fun enhance(basePath: String, enrichedBasePath: String): BlueprintContext - - @Throws(BlueprintException::class) - suspend fun enhance(basePath: String): BlueprintContext -} - -interface BlueprintTypeEnhancerService { - - fun getServiceTemplateEnhancers(): List - - fun getTopologyTemplateEnhancers(): List - - fun getWorkflowEnhancers(): List - - fun getNodeTemplateEnhancers(): List - - fun getNodeTypeEnhancers(): List - - fun getRelationshipTemplateEnhancers(): List - - fun getRelationshipTypeEnhancers(): List - - fun getArtifactDefinitionEnhancers(): List - - fun getPolicyTypeEnhancers(): List - - fun getPropertyDefinitionEnhancers(): List - - fun getAttributeDefinitionEnhancers(): List - - fun enhanceServiceTemplate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - serviceTemplate: ServiceTemplate - ) { - val enhancers = getServiceTemplateEnhancers() - doEnhancement(bluePrintRuntimeService, name, serviceTemplate, enhancers) - } - - fun enhanceTopologyTemplate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - topologyTemplate: TopologyTemplate - ) { - val enhancers = getTopologyTemplateEnhancers() - doEnhancement(bluePrintRuntimeService, name, topologyTemplate, enhancers) - } - - fun enhanceWorkflow(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, workflow: Workflow) { - val enhancers = getWorkflowEnhancers() - doEnhancement(bluePrintRuntimeService, name, workflow, enhancers) - } - - fun enhanceNodeTemplate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - nodeTemplate: NodeTemplate - ) { - val enhancers = getNodeTemplateEnhancers() - doEnhancement(bluePrintRuntimeService, name, nodeTemplate, enhancers) - } - - fun enhanceNodeType(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeType: NodeType) { - val enhancers = getNodeTypeEnhancers() - doEnhancement(bluePrintRuntimeService, name, nodeType, enhancers) - } - - fun enhanceRelationshipTemplate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipTemplate: RelationshipTemplate - ) { - val enhancers = getRelationshipTemplateEnhancers() - doEnhancement(bluePrintRuntimeService, name, relationshipTemplate, enhancers) - } - - fun enhanceRelationshipType( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipType: RelationshipType - ) { - val enhancers = getRelationshipTypeEnhancers() - doEnhancement(bluePrintRuntimeService, name, relationshipType, enhancers) - } - - fun enhanceArtifactDefinition( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - artifactDefinition: ArtifactDefinition - ) { - val enhancers = getArtifactDefinitionEnhancers() - doEnhancement(bluePrintRuntimeService, name, artifactDefinition, enhancers) - } - - fun enhancePolicyType(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, policyType: PolicyType) { - val enhancers = getPolicyTypeEnhancers() - doEnhancement(bluePrintRuntimeService, name, policyType, enhancers) - } - - fun enhancePropertyDefinitions( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - properties: MutableMap - ) { - val errorMap = linkedMapOf() - properties.forEach { propertyName, propertyDefinition -> - try { - enhancePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition) - } catch (e: BlueprintException) { - errorMap[propertyName] = e - } - } - if (errorMap.isNotEmpty()) { - val nestedErrors = errorMap.keys.map { "[ property: ${errorMap[it]?.message} ]" }.joinToString(";") - throw BlueprintException("Failed to enhance properties $nestedErrors") - } - } - - fun enhancePropertyDefinition( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - propertyDefinition: PropertyDefinition - ) { - val enhancers = getPropertyDefinitionEnhancers() - doEnhancement(bluePrintRuntimeService, name, propertyDefinition, enhancers) - } - - fun enhanceAttributeDefinitions( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - attributes: MutableMap - ) { - val errorMap = linkedMapOf() - attributes.forEach { attributeName, attributeDefinition -> - try { - enhanceAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition) - } catch (e: BlueprintException) { - errorMap[attributeName] = e - } - } - if (errorMap.isNotEmpty()) { - val nestedErrors = errorMap.keys.map { "[ attribute: ${errorMap[it]?.message} ]" }.joinToString(";") - throw BlueprintException("Failed to enhance attributes $nestedErrors") - } - } - - fun enhanceAttributeDefinition( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - attributeDefinition: AttributeDefinition - ) { - val enhancers = getAttributeDefinitionEnhancers() - doEnhancement(bluePrintRuntimeService, name, attributeDefinition, enhancers) - } - - @Suppress("UNCHECKED_CAST") - private fun doEnhancement( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - definition: Any, - enhancers: List> - ) { - if (enhancers.isNotEmpty()) { - val errorMap = linkedMapOf() - enhancers.forEach { - try { - it.enhance(bluePrintRuntimeService, name, definition as T) - } catch (e: BlueprintException) { - errorMap[name] = e - } - } - if (errorMap.isNotEmpty()) { - val nestedErrors = errorMap.keys.map { - "${errorMap[it]?.message ?: errorMap[it].toString()}" - }.joinToString(";") - throw BlueprintException("$name-->$nestedErrors") - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt index 4f6689022..b56fac541 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt @@ -18,29 +18,29 @@ package org.onap.ccsdk.cds.controllerblueprints.core.interfaces import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import java.util.function.Function interface BlueprintFunctionNode : Function { fun getName(): String - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun prepareRequest(executionRequest: T): T = runBlocking { prepareRequestNB(executionRequest) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun process(executionRequest: T) = runBlocking { processNB(executionRequest) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun recover(runtimeException: RuntimeException, executionRequest: T) = runBlocking { recoverNB(runtimeException, executionRequest) } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun prepareResponse(): R = runBlocking { prepareResponseNB() } @@ -55,18 +55,18 @@ interface BlueprintFunctionNode : Function { return prepareResponse() } - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) suspend fun prepareRequestNB(executionRequest: T): T - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) suspend fun processNB(executionRequest: T) - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: T) - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) suspend fun prepareResponseNB(): R - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) suspend fun applyNB(t: T): R } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintRepoService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintRepoService.kt deleted file mode 100644 index 631236a40..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintRepoService.kt +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import java.io.Serializable - -/** - * BlueprintRepoFileService - * @author Brinda Santh - * - */ - -interface BlueprintRepoService : Serializable { - - @Throws(BlueprintException::class) - fun getNodeType(nodeTypeName: String): NodeType - - @Throws(BlueprintException::class) - fun getDataType(dataTypeName: String): DataType - - @Throws(BlueprintException::class) - fun getArtifactType(artifactTypeName: String): ArtifactType - - @Throws(BlueprintException::class) - fun getRelationshipType(relationshipTypeName: String): RelationshipType - - @Throws(BlueprintException::class) - fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintScriptsService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintScriptsService.kt deleted file mode 100644 index b7a06e264..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintScriptsService.kt +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintSourceCode - -interface BlueprintScriptsService { - - suspend fun scriptInstance(bluePrintSourceCode: BlueprintSourceCode, scriptClassName: String): T - - suspend fun scriptInstance( - blueprintBasePath: String, - artifactName: String, - artifactVersion: String, - scriptClassName: String, - reCompile: Boolean - ): T - - suspend fun scriptInstance(blueprintBasePath: String, scriptClassName: String, reCompile: Boolean): T - - suspend fun scriptInstance(cacheKey: String, scriptClassName: String): T - - suspend fun scriptInstance(scriptClassName: String): T -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt index 799011568..1958e23ac 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt @@ -18,7 +18,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.interfaces import com.fasterxml.jackson.core.io.CharTypes import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.TextNode -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService interface BlueprintTemplateService { @@ -35,7 +35,7 @@ interface BlueprintTemplateService { * **/ suspend fun generateContent( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, artifactName: String, jsonData: String = "", @@ -47,14 +47,14 @@ interface BlueprintTemplateService { /** * Customise JsonNodeFactory and TextNode, Since it introduces quotes for string data. */ -open class BlueprintJsonNodeFactory : JsonNodeFactory() { +open class BluePrintJsonNodeFactory : JsonNodeFactory() { override fun textNode(text: String): TextNode { - return BlueprintTextNode(text) + return BluePrintTextNode(text) } } -open class BlueprintTextNode(v: String) : TextNode(v) { +open class BluePrintTextNode(v: String) : TextNode(v) { override fun toString(): String { var len = this._value.length diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt index 5f36e8ede..0d9876b81 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.interfaces -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition @@ -28,85 +28,85 @@ import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService -interface BlueprintValidator { +interface BluePrintValidator { - fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: T) + fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T) } -interface BlueprintServiceTemplateValidator : BlueprintValidator +interface BluePrintServiceTemplateValidator : BluePrintValidator -interface BlueprintTopologyTemplateValidator : BlueprintValidator +interface BluePrintTopologyTemplateValidator : BluePrintValidator -interface BlueprintArtifactTypeValidator : BlueprintValidator +interface BluePrintArtifactTypeValidator : BluePrintValidator -interface BlueprintArtifactDefinitionValidator : BlueprintValidator +interface BluePrintArtifactDefinitionValidator : BluePrintValidator -interface BlueprintDataTypeValidator : BlueprintValidator +interface BluePrintDataTypeValidator : BluePrintValidator -interface BlueprintNodeTypeValidator : BlueprintValidator +interface BluePrintNodeTypeValidator : BluePrintValidator -interface BlueprintNodeTemplateValidator : BlueprintValidator +interface BluePrintNodeTemplateValidator : BluePrintValidator -interface BlueprintWorkflowValidator : BlueprintValidator +interface BluePrintWorkflowValidator : BluePrintValidator -interface BlueprintPropertyDefinitionValidator : BlueprintValidator +interface BluePrintPropertyDefinitionValidator : BluePrintValidator -interface BlueprintAttributeDefinitionValidator : BlueprintValidator +interface BluePrintAttributeDefinitionValidator : BluePrintValidator /** * Blueprint Validation Interface. */ -interface BlueprintValidatorService { +interface BluePrintValidatorService { - @Throws(BlueprintException::class) - suspend fun validateBlueprints(basePath: String): Boolean + @Throws(BluePrintException::class) + suspend fun validateBluePrints(basePath: String): Boolean - @Throws(BlueprintException::class) - suspend fun validateBlueprints(bluePrintRuntimeService: BlueprintRuntimeService<*>): Boolean + @Throws(BluePrintException::class) + suspend fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean } -interface BlueprintTypeValidatorService { +interface BluePrintTypeValidatorService { - fun > bluePrintValidator(referenceName: String, classType: Class): T? + fun > bluePrintValidator(referenceName: String, classType: Class): T? - fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? + fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? - fun > bluePrintValidators(classType: Class): List? + fun > bluePrintValidators(classType: Class): List? - fun getServiceTemplateValidators(): List + fun getServiceTemplateValidators(): List - fun getDataTypeValidators(): List + fun getDataTypeValidators(): List - fun getArtifactTypeValidators(): List + fun getArtifactTypeValidators(): List - fun getArtifactDefinitionsValidators(): List + fun getArtifactDefinitionsValidators(): List - fun getNodeTypeValidators(): List + fun getNodeTypeValidators(): List - fun getTopologyTemplateValidators(): List + fun getTopologyTemplateValidators(): List - fun getNodeTemplateValidators(): List + fun getNodeTemplateValidators(): List - fun getWorkflowValidators(): List + fun getWorkflowValidators(): List - fun getPropertyDefinitionValidators(): List + fun getPropertyDefinitionValidators(): List - fun getAttributeDefinitionValidators(): List + fun getAttributeDefinitionValidators(): List - fun validateServiceTemplate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { + fun validateServiceTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { val validators = getServiceTemplateValidators() doValidation(bluePrintRuntimeService, name, serviceTemplate, validators) } - fun validateArtifactType(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, artifactType: ArtifactType) { + fun validateArtifactType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) { val validators = getArtifactTypeValidators() doValidation(bluePrintRuntimeService, name, artifactType, validators) } fun validateArtifactDefinition( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition ) { @@ -114,59 +114,59 @@ interface BlueprintTypeValidatorService { doValidation(bluePrintRuntimeService, name, artifactDefinition, validators) } - fun validateDataType(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, dataType: DataType) { + fun validateDataType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, dataType: DataType) { val validators = getDataTypeValidators() doValidation(bluePrintRuntimeService, name, dataType, validators) } - fun validateNodeType(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeType: NodeType) { + fun validateNodeType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { val validators = getNodeTypeValidators() doValidation(bluePrintRuntimeService, name, nodeType, validators) } - fun validateTopologyTemplate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { + fun validateTopologyTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { val validators = getTopologyTemplateValidators() doValidation(bluePrintRuntimeService, name, topologyTemplate, validators) } - fun validateNodeTemplate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + fun validateNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { val validators = getNodeTemplateValidators() doValidation(bluePrintRuntimeService, name, nodeTemplate, validators) } - fun validateWorkflow(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, workflow: Workflow) { + fun validateWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { val validators = getWorkflowValidators() doValidation(bluePrintRuntimeService, name, workflow, validators) } - fun validatePropertyDefinitions(bluePrintRuntimeService: BlueprintRuntimeService<*>, properties: MutableMap) { + fun validatePropertyDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, properties: MutableMap) { properties.forEach { propertyName, propertyDefinition -> validatePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition) } } - fun validatePropertyDefinition(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + fun validatePropertyDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { val validators = getPropertyDefinitionValidators() doValidation(bluePrintRuntimeService, name, propertyDefinition, validators) } - fun validateAttributeDefinitions(bluePrintRuntimeService: BlueprintRuntimeService<*>, attributes: MutableMap) { + fun validateAttributeDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, attributes: MutableMap) { attributes.forEach { attributeName, attributeDefinition -> validateAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition) } } - fun validateAttributeDefinition(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { + fun validateAttributeDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { val validators = getAttributeDefinitionValidators() doValidation(bluePrintRuntimeService, name, attributeDefinition, validators) } @Suppress("UNCHECKED_CAST") private fun doValidation( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, definition: Any, - validators: List> + validators: List> ) { validators.forEach { it.validate(bluePrintRuntimeService, name, definition as T) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintWorkflowExecutionService.kt deleted file mode 100644 index 4f20a1a33..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintWorkflowExecutionService.kt +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.interfaces - -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService - -interface BlueprintWorkflowExecutionService { - - suspend fun executeBlueprintWorkflow( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - executionServiceInput: Input, - properties: MutableMap = hashMapOf() - ): Output -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt new file mode 100644 index 000000000..230097f3c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt @@ -0,0 +1,187 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.scripts + +import com.google.common.cache.CacheBuilder +import com.google.common.cache.CacheLoader +import com.google.common.cache.LoadingCache +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.jetbrains.kotlin.cli.common.ExitCode +import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation +import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity +import org.jetbrains.kotlin.cli.common.messages.MessageCollector +import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler +import org.jetbrains.kotlin.config.Services +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import java.io.File +import java.net.URLClassLoader +import java.util.ArrayList +import kotlin.script.experimental.api.SourceCode +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.system.measureTimeMillis + +open class BluePrintCompileService { + + val log = logger(BluePrintCompileService::class) + + companion object { + + val classPaths = classpathFromClasspathProperty()?.joinToString(File.pathSeparator) { + it.absolutePath + } + val mutexCache: LoadingCache = CacheBuilder.newBuilder() + .build(CacheLoader.from { s -> Mutex() }) + } + + /** Compile the [bluePrintSourceCode] and get the [kClassName] instance for the constructor [args] */ + suspend fun eval( + bluePrintSourceCode: BluePrintSourceCode, + kClassName: String, + args: ArrayList? + ): T { + /** Compile the source code if needed */ + log.debug("Jar Exists : ${bluePrintSourceCode.targetJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}") + + mutexCache.get(bluePrintSourceCode.targetJarFile.absolutePath).withLock { + if (!bluePrintSourceCode.targetJarFile.exists() || bluePrintSourceCode.regenerate) { + compile(bluePrintSourceCode) + } + } + + val classLoaderWithDependencies = BluePrintCompileCache.classLoader(bluePrintSourceCode.cacheKey) + + /** Create the instance from the class loader */ + return instance(classLoaderWithDependencies, kClassName, args) + } + + /** Compile [bluePrintSourceCode] and put into cache */ + suspend fun compile(bluePrintSourceCode: BluePrintSourceCode) { + // TODO("Include Multiple folders") + val sourcePath = bluePrintSourceCode.blueprintKotlinSources.first() + val compiledJarFile = bluePrintSourceCode.targetJarFile + + log.info("compiling for cache key(${bluePrintSourceCode.cacheKey})") + coroutineScope { + val timeTaken = measureTimeMillis { + /** Create compile arguments */ + val args = mutableListOf().apply { + add("-no-stdlib") + add("-no-reflect") + add("-module-name") + add(bluePrintSourceCode.moduleName) + add("-cp") + add(classPaths!!) + add(sourcePath) + add("-d") + add(compiledJarFile.absolutePath) + } + val deferredCompile = async { + val k2jvmCompiler = K2JVMCompiler() + + /** Construct Arguments */ + val arguments = k2jvmCompiler.createArguments() + parseCommandLineArguments(args, arguments) + val messageCollector = CompilationMessageCollector() + + /** Compile with arguments */ + val exitCode: ExitCode = k2jvmCompiler.exec(messageCollector, Services.EMPTY, arguments) + when (exitCode) { + ExitCode.OK -> { + checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" } + } + else -> { + throw BluePrintException("$exitCode :${messageCollector.errors().joinToString("\n")}") + } + } + } + deferredCompile.await() + } + log.info("compiled in ($timeTaken)mSec for cache key(${bluePrintSourceCode.cacheKey})") + } + } + + /** create class [kClassName] instance from [classLoader] */ + fun instance(classLoader: URLClassLoader, kClassName: String, args: ArrayList? = arrayListOf()): T { + val kClazz = classLoader.loadClass(kClassName) + ?: throw BluePrintException("failed to load class($kClassName) from current class loader.") + + val instance = if (args.isNullOrEmpty()) { + kClazz.newInstance() + } else { + kClazz.constructors + .single().newInstance(*args.toArray()) + } ?: throw BluePrintException("failed to create class($kClassName) instance for constructor argument($args).") + + return instance as T + } +} + +/** Compile source code information */ +open class BluePrintSourceCode : SourceCode { + + lateinit var blueprintKotlinSources: MutableList + lateinit var moduleName: String + lateinit var targetJarFile: File + lateinit var cacheKey: String + var regenerate: Boolean = false + + override val text: String + get() = "" + + override val locationId: String? = null + + override val name: String? + get() = moduleName +} + +/** Class to collect compilation Data */ +data class CompiledMessageData( + val severity: CompilerMessageSeverity, + val message: String, + val location: CompilerMessageLocation? +) + +/** Class to collect compilation results */ +class CompilationMessageCollector : MessageCollector { + + private val compiledMessages: MutableList = arrayListOf() + + override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { + synchronized(compiledMessages) { + compiledMessages.add(CompiledMessageData(severity, message, location)) + } + } + + override fun hasErrors() = + synchronized(compiledMessages) { + compiledMessages.any { it.severity.isError } + } + + override fun clear() { + synchronized(compiledMessages) { + compiledMessages.clear() + } + } + + fun errors(): List = compiledMessages.filter { it.severity == CompilerMessageSeverity.ERROR } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt new file mode 100644 index 000000000..a0efc619c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.scripts + +import com.google.common.cache.CacheBuilder +import com.google.common.cache.CacheLoader +import com.google.common.cache.LoadingCache +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import java.net.URLClassLoader + +object BluePrintCompileCache { + + val log = logger(BluePrintCompileCache::class) + + private val classLoaderCache: LoadingCache = CacheBuilder.newBuilder() + .maximumSize(50) + .build(BluePrintClassLoader) + + fun classLoader(key: String): URLClassLoader { + return classLoaderCache.get(key) + } + + fun cleanClassLoader(key: String) { + if (hasClassLoader(key)) { + // Make sure to close all classloader loaded resources before we let go of it. + // This fixes a Delete failure message on filesystem that keeps locks on opened jars; + // like Windows and NFS. + classLoaderCache.get(key).close() + classLoaderCache.invalidate(key) + log.info("Cleaned compiled cache($key)") + } else { + log.warn("No compiled cache($key) present to clean.") + } + } + + fun hasClassLoader(key: String): Boolean { + return classLoaderCache.asMap().containsKey(key) + } +} + +object BluePrintClassLoader : CacheLoader() { + + val log = logger(BluePrintClassLoader::class) + + override fun load(key: String) = try { + log.info("loading compiled cache($key)") + BluePrintFileUtils.getURLClassLoaderFromDirectory(key) + } catch (e: Exception) { + throw BluePrintException("failed to load cache($key) with Exception($e)") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt new file mode 100644 index 000000000..f3eb1a2b9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.scripts + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintScriptsService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import java.util.ArrayList + +open class BluePrintScriptsServiceImpl : BluePrintScriptsService { + + val log = logger(BluePrintScriptsServiceImpl::class) + + override suspend fun scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T { + val bluePrintCompileService = BluePrintCompileService() + return bluePrintCompileService.eval(bluePrintSourceCode, scriptClassName, null) + } + + override suspend fun scriptInstance( + blueprintBasePath: String, + artifactName: String, + artifactVersion: String, + scriptClassName: String, + reCompile: Boolean + ): T { + + val sources: MutableList = arrayListOf() + sources.add(normalizedPathName(blueprintBasePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR)) + + val scriptSource = BluePrintSourceCode() + scriptSource.blueprintKotlinSources = sources + scriptSource.moduleName = "$artifactName-$artifactVersion-cba-kts" + scriptSource.cacheKey = BluePrintFileUtils.compileCacheKey(blueprintBasePath) + scriptSource.targetJarFile = BluePrintFileUtils.compileJarFile(blueprintBasePath, artifactName, artifactVersion) + scriptSource.regenerate = reCompile + return scriptInstance(scriptSource, scriptClassName) + } + + override suspend fun scriptInstance( + blueprintBasePath: String, + scriptClassName: String, + reCompile: Boolean + ): T { + val toscaMetaData = BluePrintMetadataUtils.toscaMetaData(blueprintBasePath) + checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" } + checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" } + return scriptInstance( + blueprintBasePath, toscaMetaData.templateName!!, toscaMetaData.templateVersion!!, + scriptClassName, reCompile + ) + } + + override suspend fun scriptInstance(cacheKey: String, scriptClassName: String): T { + val args = ArrayList() + return BluePrintCompileCache.classLoader(cacheKey).loadClass(scriptClassName).constructors + .single().newInstance(*args.toArray()) as T + } + + override suspend fun scriptInstance(scriptClassName: String): T { + val args = ArrayList() + return Thread.currentThread().contextClassLoader.loadClass(scriptClassName).constructors + .single().newInstance(*args.toArray()) as T + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompileService.kt deleted file mode 100644 index 5cf0a93af..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompileService.kt +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.scripts - -import com.google.common.cache.CacheBuilder -import com.google.common.cache.CacheLoader -import com.google.common.cache.LoadingCache -import kotlinx.coroutines.async -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.jetbrains.kotlin.cli.common.ExitCode -import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments -import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation -import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity -import org.jetbrains.kotlin.cli.common.messages.MessageCollector -import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler -import org.jetbrains.kotlin.config.Services -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.checkFileExists -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import java.io.File -import java.net.URLClassLoader -import java.util.ArrayList -import kotlin.script.experimental.api.SourceCode -import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty -import kotlin.system.measureTimeMillis - -open class BlueprintCompileService { - - val log = logger(BlueprintCompileService::class) - - companion object { - - val classPaths = classpathFromClasspathProperty()?.joinToString(File.pathSeparator) { - it.absolutePath - } - val mutexCache: LoadingCache = CacheBuilder.newBuilder() - .build(CacheLoader.from { s -> Mutex() }) - } - - /** Compile the [bluePrintSourceCode] and get the [kClassName] instance for the constructor [args] */ - suspend fun eval( - bluePrintSourceCode: BlueprintSourceCode, - kClassName: String, - args: ArrayList? - ): T { - /** Compile the source code if needed */ - log.debug("Jar Exists : ${bluePrintSourceCode.targetJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}") - - mutexCache.get(bluePrintSourceCode.targetJarFile.absolutePath).withLock { - if (!bluePrintSourceCode.targetJarFile.exists() || bluePrintSourceCode.regenerate) { - compile(bluePrintSourceCode) - } - } - - val classLoaderWithDependencies = BlueprintCompileCache.classLoader(bluePrintSourceCode.cacheKey) - - /** Create the instance from the class loader */ - return instance(classLoaderWithDependencies, kClassName, args) - } - - /** Compile [bluePrintSourceCode] and put into cache */ - suspend fun compile(bluePrintSourceCode: BlueprintSourceCode) { - // TODO("Include Multiple folders") - val sourcePath = bluePrintSourceCode.blueprintKotlinSources.first() - val compiledJarFile = bluePrintSourceCode.targetJarFile - - log.info("compiling for cache key(${bluePrintSourceCode.cacheKey})") - coroutineScope { - val timeTaken = measureTimeMillis { - /** Create compile arguments */ - val args = mutableListOf().apply { - add("-no-stdlib") - add("-no-reflect") - add("-module-name") - add(bluePrintSourceCode.moduleName) - add("-cp") - add(classPaths!!) - add(sourcePath) - add("-d") - add(compiledJarFile.absolutePath) - } - val deferredCompile = async { - val k2jvmCompiler = K2JVMCompiler() - - /** Construct Arguments */ - val arguments = k2jvmCompiler.createArguments() - parseCommandLineArguments(args, arguments) - val messageCollector = CompilationMessageCollector() - - /** Compile with arguments */ - val exitCode: ExitCode = k2jvmCompiler.exec(messageCollector, Services.EMPTY, arguments) - when (exitCode) { - ExitCode.OK -> { - checkFileExists(compiledJarFile) { "couldn't generate compiled jar(${compiledJarFile.absolutePath})" } - } - else -> { - throw BlueprintException("$exitCode :${messageCollector.errors().joinToString("\n")}") - } - } - } - deferredCompile.await() - } - log.info("compiled in ($timeTaken)mSec for cache key(${bluePrintSourceCode.cacheKey})") - } - } - - /** create class [kClassName] instance from [classLoader] */ - fun instance(classLoader: URLClassLoader, kClassName: String, args: ArrayList? = arrayListOf()): T { - val kClazz = classLoader.loadClass(kClassName) - ?: throw BlueprintException("failed to load class($kClassName) from current class loader.") - - val instance = if (args.isNullOrEmpty()) { - kClazz.newInstance() - } else { - kClazz.constructors - .single().newInstance(*args.toArray()) - } ?: throw BlueprintException("failed to create class($kClassName) instance for constructor argument($args).") - - return instance as T - } -} - -/** Compile source code information */ -open class BlueprintSourceCode : SourceCode { - - lateinit var blueprintKotlinSources: MutableList - lateinit var moduleName: String - lateinit var targetJarFile: File - lateinit var cacheKey: String - var regenerate: Boolean = false - - override val text: String - get() = "" - - override val locationId: String? = null - - override val name: String? - get() = moduleName -} - -/** Class to collect compilation Data */ -data class CompiledMessageData( - val severity: CompilerMessageSeverity, - val message: String, - val location: CompilerMessageLocation? -) - -/** Class to collect compilation results */ -class CompilationMessageCollector : MessageCollector { - - private val compiledMessages: MutableList = arrayListOf() - - override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { - synchronized(compiledMessages) { - compiledMessages.add(CompiledMessageData(severity, message, location)) - } - } - - override fun hasErrors() = - synchronized(compiledMessages) { - compiledMessages.any { it.severity.isError } - } - - override fun clear() { - synchronized(compiledMessages) { - compiledMessages.clear() - } - } - - fun errors(): List = compiledMessages.filter { it.severity == CompilerMessageSeverity.ERROR } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompilerCache.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompilerCache.kt deleted file mode 100644 index a6d4571a2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintCompilerCache.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.scripts - -import com.google.common.cache.CacheBuilder -import com.google.common.cache.CacheLoader -import com.google.common.cache.LoadingCache -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import java.net.URLClassLoader - -object BlueprintCompileCache { - - val log = logger(BlueprintCompileCache::class) - - private val classLoaderCache: LoadingCache = CacheBuilder.newBuilder() - .maximumSize(50) - .build(BlueprintClassLoader) - - fun classLoader(key: String): URLClassLoader { - return classLoaderCache.get(key) - } - - fun cleanClassLoader(key: String) { - if (hasClassLoader(key)) { - // Make sure to close all classloader loaded resources before we let go of it. - // This fixes a Delete failure message on filesystem that keeps locks on opened jars; - // like Windows and NFS. - classLoaderCache.get(key).close() - classLoaderCache.invalidate(key) - log.info("Cleaned compiled cache($key)") - } else { - log.warn("No compiled cache($key) present to clean.") - } - } - - fun hasClassLoader(key: String): Boolean { - return classLoaderCache.asMap().containsKey(key) - } -} - -object BlueprintClassLoader : CacheLoader() { - - val log = logger(BlueprintClassLoader::class) - - override fun load(key: String) = try { - log.info("loading compiled cache($key)") - BlueprintFileUtils.getURLClassLoaderFromDirectory(key) - } catch (e: Exception) { - throw BlueprintException("failed to load cache($key) with Exception($e)") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImpl.kt deleted file mode 100644 index c89d74dfb..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImpl.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.scripts - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintScriptsService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import java.util.ArrayList - -open class BlueprintScriptsServiceImpl : BlueprintScriptsService { - - val log = logger(BlueprintScriptsServiceImpl::class) - - override suspend fun scriptInstance(bluePrintSourceCode: BlueprintSourceCode, scriptClassName: String): T { - val bluePrintCompileService = BlueprintCompileService() - return bluePrintCompileService.eval(bluePrintSourceCode, scriptClassName, null) - } - - override suspend fun scriptInstance( - blueprintBasePath: String, - artifactName: String, - artifactVersion: String, - scriptClassName: String, - reCompile: Boolean - ): T { - - val sources: MutableList = arrayListOf() - sources.add(normalizedPathName(blueprintBasePath, BlueprintConstants.TOSCA_SCRIPTS_KOTLIN_DIR)) - - val scriptSource = BlueprintSourceCode() - scriptSource.blueprintKotlinSources = sources - scriptSource.moduleName = "$artifactName-$artifactVersion-cba-kts" - scriptSource.cacheKey = BlueprintFileUtils.compileCacheKey(blueprintBasePath) - scriptSource.targetJarFile = BlueprintFileUtils.compileJarFile(blueprintBasePath, artifactName, artifactVersion) - scriptSource.regenerate = reCompile - return scriptInstance(scriptSource, scriptClassName) - } - - override suspend fun scriptInstance( - blueprintBasePath: String, - scriptClassName: String, - reCompile: Boolean - ): T { - val toscaMetaData = BlueprintMetadataUtils.toscaMetaData(blueprintBasePath) - checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" } - checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" } - return scriptInstance( - blueprintBasePath, toscaMetaData.templateName!!, toscaMetaData.templateVersion!!, - scriptClassName, reCompile - ) - } - - override suspend fun scriptInstance(cacheKey: String, scriptClassName: String): T { - val args = ArrayList() - return BlueprintCompileCache.classLoader(cacheKey).loadClass(scriptClassName).constructors - .single().newInstance(*args.toArray()) as T - } - - override suspend fun scriptInstance(scriptClassName: String): T { - val args = ArrayList() - return Thread.currentThread().contextClassLoader.loadClass(scriptClassName).constructors - .single().newInstance(*args.toArray()) as T - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt new file mode 100644 index 000000000..1a43c3066 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt @@ -0,0 +1,125 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition + +/** + * + * + * @author Brinda Santh + */ +internal class BluePrintChainedService { + + var bpc: BluePrintContext + + constructor(bpc: BluePrintContext) { + this.bpc = bpc + } + + fun nodeTypeChained(nodeTypeName: String): NodeType { + + val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) + val attributes = hashMapOf() + val properties = hashMapOf() + val requirements = hashMapOf() + val capabilities = hashMapOf() + val interfaces = hashMapOf() + val artifacts = hashMapOf() + + recNodeTypesChained(nodeTypeName).forEach { nodeType -> + + val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes + if (subAttributes != null) { + attributes.putAll(subAttributes) + } + + val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties + if (subProperties != null) { + properties.putAll(subProperties) + } + + val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements + if (subRequirements != null) { + requirements.putAll(subRequirements) + } + val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities + if (subCapabilities != null) { + capabilities.putAll(subCapabilities) + } + val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces + if (subInterfaces != null) { + interfaces.putAll(subInterfaces) + } + + val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts + if (subArtifacts != null) { + artifacts.putAll(subArtifacts) + } + } + nodeType.attributes = attributes + nodeType.properties = properties + nodeType.requirements = requirements + nodeType.capabilities = capabilities + nodeType.interfaces = interfaces + nodeType.artifacts = artifacts + return nodeType + } + + fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap? { + val nodeType = bpc.nodeTypeByName(nodeTypeName) + val properties = hashMapOf() + + recNodeTypesChained(nodeTypeName).forEach { nodeType -> + val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties + if (subProperties != null) { + properties.putAll(subProperties) + } + } + return properties + } + + private fun recNodeTypesChained(nodeTypeName: String, nodeTypes: MutableList? = arrayListOf()): MutableList { + val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) + nodeType.id = nodeTypeName + val derivedFrom: String = nodeType.derivedFrom + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + recNodeTypesChained(derivedFrom, nodeTypes) + } + nodeTypes!!.add(nodeType) + return nodeTypes + } + + private fun recDataTypesChained(dataTypeName: String, dataTypes: MutableList? = arrayListOf()): MutableList { + val dataType: DataType = bpc.dataTypeByName(dataTypeName)!! + dataType.id = dataTypeName + val derivedFrom: String = dataType.derivedFrom + if (!BluePrintTypes.rootDataTypes().contains(derivedFrom)) { + recDataTypesChained(derivedFrom, dataTypes) + } + dataTypes!!.add(dataType) + return dataTypes + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt new file mode 100644 index 000000000..76a6ff7cf --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt @@ -0,0 +1,354 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +class BluePrintContext(val serviceTemplate: ServiceTemplate) { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + /** + * Blueprint CBA extracted file location + */ + var rootPath = "." + + /** + * Root Definition file path + */ + var entryDefinition = "" + + /** Other definitions along with model, It may Resource Definition, Resource Assignments, Configurations etc..*/ + var otherDefinitions: MutableMap = hashMapOf() + + fun otherDefinition(key: String) = otherDefinitions[key] as T + + fun checkOtherDefinition(key: String) = otherDefinitions.containsKey(key) + + fun imports(): List? = serviceTemplate.imports + + fun dslDefinitions() = serviceTemplate.dslDefinitions + + val metadata: MutableMap? = serviceTemplate.metadata + + fun dataTypes(): MutableMap? = serviceTemplate.dataTypes + + fun inputs(): MutableMap? = serviceTemplate.topologyTemplate?.inputs + + fun blueprintJson(pretty: Boolean = false): String = print("json", pretty) + + private fun print(type: String? = "json", pretty: Boolean = false): String { + return JacksonUtils.getJson(serviceTemplate, pretty) + } + + fun name(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_NAME) + ?: throw BluePrintException("could't get template name from meta data") + + fun version(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_VERSION) + ?: throw BluePrintException("could't get template version from meta data") + + fun author(): String = metadata?.get(BluePrintConstants.METADATA_TEMPLATE_AUTHOR) + ?: throw BluePrintException("could't get template author from meta data") + + // Workflow + fun workflows(): MutableMap? = serviceTemplate.topologyTemplate?.workflows + + fun workflowByName(workFlowName: String): Workflow = workflows()?.get(workFlowName) + ?: throw BluePrintException("could't get workflow($workFlowName)") + + fun workflowInputs(workFlowName: String) = workflowByName(workFlowName).inputs + + fun workflowSteps(workFlowName: String) = + workflowByName(workFlowName).steps ?: throw BluePrintException("could't get steps for workflow($workFlowName)") + + fun workflowStepByName(workFlowName: String, stepName: String): Step { + return workflowSteps(workFlowName)[stepName] + ?: throw BluePrintException("could't get step($stepName) for workflow($workFlowName)") + } + + fun workflowStepNodeTemplate(workFlowName: String, stepName: String): String { + return workflowStepByName(workFlowName, stepName).target + ?: throw BluePrintException("could't get node template name for workflow($workFlowName)'s step($stepName)") + } + + fun workflowFirstStepNodeTemplate(workFlowName: String): String { + val firstStepName = workflowSteps(workFlowName).keys.ifEmpty { + throw BluePrintException("could't get first step for workflow($workFlowName)") + }.first() + return workflowStepNodeTemplate(workFlowName, firstStepName) + } + + fun workflowStepFirstCallOperation(workFlowName: String, stepName: String): String { + return workflowStepByName( + workFlowName, + stepName + ).activities?.filter { it.callOperation != null }?.single()?.callOperation + ?: throw BluePrintException("couldn't get first callOperation for WorkFlow($workFlowName) ") + } + + // DSL + fun dslPropertiesByName(name: String): JsonNode = dslDefinitions()?.get(name) + ?: throw BluePrintException("couldn't get policy type for the dsl($name)") + + // Data Type + fun dataTypeByName(name: String): DataType? = dataTypes()?.get(name) + + // Artifact Type + fun artifactTypes(): MutableMap? = serviceTemplate.artifactTypes + + // Policy Types + fun policyTypes(): MutableMap? = serviceTemplate.policyTypes + + fun policyTypeByName(policyName: String) = policyTypes()?.get(policyName) + ?: throw BluePrintException("could't get policy type for the name($policyName)") + + fun policyTypesDerivedFrom(name: String): MutableMap? { + return policyTypes()?.filterValues { policyType -> policyType.derivedFrom == name }?.toMutableMap() + } + + fun policyTypesTarget(target: String): MutableMap? { + return policyTypes()?.filterValues { it.targets.contains(target) }?.toMutableMap() + } + + fun policyTypesTargetNDerivedFrom(target: String, derivedFrom: String): MutableMap? { + return policyTypesDerivedFrom(derivedFrom)?.filterValues { + it.targets.contains(target) + }?.toMutableMap() + } + + // Node Type Methods + fun nodeTypes(): MutableMap? = serviceTemplate.nodeTypes + + fun nodeTypeByName(name: String): NodeType = + nodeTypes()?.get(name) + ?: throw BluePrintException("could't get node type for the name($name)") + + fun nodeTypeDerivedFrom(name: String): MutableMap? { + return nodeTypes()?.filterValues { nodeType -> nodeType.derivedFrom == name }?.toMutableMap() + } + + fun nodeTypeInterface(nodeTypeName: String, interfaceName: String): InterfaceDefinition { + return nodeTypeByName(nodeTypeName).interfaces?.get(interfaceName) + ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName)") + } + + fun nodeTypeInterfaceOperation( + nodeTypeName: String, + interfaceName: String, + operationName: String + ): OperationDefinition { + return nodeTypeInterface(nodeTypeName, interfaceName).operations?.get(operationName) + ?: throw BluePrintException("could't get node type($nodeTypeName)'s interface definition($interfaceName) operation definition($operationName)") + } + + fun interfaceNameForNodeType(nodeTypeName: String): String { + return nodeTypeByName(nodeTypeName).interfaces?.keys?.first() + ?: throw BluePrintException("could't get NodeType($nodeTypeName)'s first InterfaceDefinition name") + } + + fun nodeTypeInterfaceOperationInputs( + nodeTypeName: String, + interfaceName: String, + operationName: String + ): MutableMap? { + return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).inputs + } + + fun nodeTypeInterfaceOperationOutputs( + nodeTypeName: String, + interfaceName: String, + operationName: String + ): MutableMap? { + return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).outputs + } + + // Relationship Type Methods + fun relationshipTypes(): MutableMap? = serviceTemplate.relationshipTypes + + fun relationshipTypeByName(name: String): RelationshipType = relationshipTypes()?.get(name) + ?: throw BluePrintException("could't get relationship type for the name($name)") + + // Node Template Methods + fun nodeTemplates(): MutableMap? = serviceTemplate.topologyTemplate?.nodeTemplates + + fun nodeTemplateByName(name: String): NodeTemplate = + nodeTemplates()?.get(name) ?: throw BluePrintException("could't get node template for the name($name)") + + fun nodeTemplateForNodeType(name: String): MutableMap? { + return nodeTemplates()?.filterValues { nodeTemplate -> nodeTemplate.type == name }?.toMutableMap() + } + + fun nodeTemplateNodeType(nodeTemplateName: String): NodeType { + val nodeTemplateType: String = nodeTemplateByName(nodeTemplateName).type + return nodeTypeByName(nodeTemplateType) + } + + fun nodeTemplateProperty(nodeTemplateName: String, propertyName: String): Any? { + return nodeTemplateByName(nodeTemplateName).properties?.get(propertyName) + } + + fun nodeTemplateArtifacts(nodeTemplateName: String): MutableMap? { + return nodeTemplateByName(nodeTemplateName).artifacts + } + + fun checkNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition? { + return nodeTemplateArtifacts(nodeTemplateName)?.get(artifactName) + } + + fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition { + return checkNodeTemplateArtifact(nodeTemplateName, artifactName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s ArtifactDefinition($artifactName)") + } + + fun nodeTemplateArtifactForArtifactType(nodeTemplateName: String, artifactType: String): ArtifactDefinition { + return nodeTemplateArtifacts(nodeTemplateName)?.filter { it.value.type == artifactType }?.map { it.value }?.get(0) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s Artifact Type($artifactType)") + } + + fun nodeTemplateFirstInterface(nodeTemplateName: String): InterfaceAssignment { + return nodeTemplateByName(nodeTemplateName).interfaces?.values?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment") + } + + fun nodeTemplateFirstInterfaceName(nodeTemplateName: String): String { + return nodeTemplateByName(nodeTemplateName).interfaces?.keys?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment name") + } + + fun nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName: String): String { + return nodeTemplateFirstInterface(nodeTemplateName).operations?.keys?.first() + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment's first OperationAssignment name") + } + + fun nodeTemplateOperationImplementation(nodeTemplateName: String, interfaceName: String, operationName: String): + Implementation? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).implementation + } + + fun nodeTemplateInterfaceOperationInputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).inputs + } + + fun nodeTemplateInterfaceOperationOutputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap? { + return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).outputs + } + + fun nodeTemplateInterface(nodeTemplateName: String, interfaceName: String): InterfaceAssignment { + return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName)") + } + + fun nodeTemplateInterfaceOperation( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): OperationAssignment { + return nodeTemplateInterface(nodeTemplateName, interfaceName).operations?.get(operationName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName) OperationAssignment($operationName)") + } + + fun nodeTemplateCapability(nodeTemplateName: String, capabilityName: String): CapabilityAssignment { + return nodeTemplateByName(nodeTemplateName).capabilities?.get(capabilityName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s CapabilityAssignment($capabilityName)") + } + + fun nodeTemplateRequirement(nodeTemplateName: String, requirementName: String): RequirementAssignment { + return nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName) + ?: throw BluePrintException("could't get NodeTemplate($nodeTemplateName)'s first RequirementAssignment($requirementName)") + } + + fun nodeTemplateRequirementNode(nodeTemplateName: String, requirementName: String): NodeTemplate { + val filteredNodeTemplateName: String = + nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)?.node + ?: throw BluePrintException("could't NodeTemplate for NodeTemplate's($nodeTemplateName) requirement's ($requirementName) ") + return nodeTemplateByName(filteredNodeTemplateName) + } + + fun nodeTemplateCapabilityProperty(nodeTemplateName: String, capabilityName: String, propertyName: String): Any? { + return nodeTemplateCapability(nodeTemplateName, capabilityName).properties?.get(propertyName) + } + + // Relationship Template Methods + fun relationshipTemplates(): MutableMap? = + serviceTemplate.topologyTemplate?.relationshipTemplates + + fun relationshipTemplateByName(name: String): RelationshipTemplate = relationshipTemplates()?.get(name) + ?: throw BluePrintException("could't get relationship template for the name($name)") + + fun relationshipTemplateProperty(relationshipTemplateName: String, propertyName: String): Any? { + return nodeTemplateByName(relationshipTemplateName).properties?.get(propertyName) + } + + fun relationshipTemplateForRelationshipType(name: String): MutableMap? { + return relationshipTemplates()?.filterValues { relationshipTemplate -> relationshipTemplate.type == name } + ?.toMutableMap() + } + + fun relationshipTemplateRelationshipType(relationshipName: String): RelationshipType { + val relationshipTemplateType: String = relationshipTemplateByName(relationshipName).type + return relationshipTypeByName(relationshipTemplateType) + } + + // Chained Functions + + fun nodeTypeChained(nodeTypeName: String): NodeType { + return BluePrintChainedService(this).nodeTypeChained(nodeTypeName) + } + + fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap? { + return BluePrintChainedService(this).nodeTypeChainedProperties(nodeTypeName) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt new file mode 100644 index 000000000..e8457283e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt @@ -0,0 +1,62 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.springframework.context.ApplicationContext +import org.springframework.context.ConfigurableApplicationContext +import kotlin.reflect.KClass + +/** + * Generic Bluepring Dependency Service, which will be used mainly in scripts. + * This will be initialised only once during the Application startup. + * Function modules, shall add their own dependency function names as an extension function. + * + * @author Brinda Santh + */ + +object BluePrintDependencyService { + + lateinit var applicationContext: ApplicationContext + + fun inject(applicationContext: ApplicationContext) { + BluePrintDependencyService.applicationContext = applicationContext + } + + /** Used to inject [instance] into spring application context for the [key], + * Use this method only for testing + * */ + fun registerSingleton(key: String, instance: Any) { + val configurableApplicationContext = applicationContext as ConfigurableApplicationContext + configurableApplicationContext.beanFactory.registerSingleton(key, instance) + } + + inline fun instance(name: String): T { + return applicationContext.getBean(name) as? T + ?: throw BluePrintProcessorException("failed to get instance($name)") + } + + inline fun instance(type: Class): T { + return applicationContext.getBean(type) + ?: throw BluePrintProcessorException("failed to get instance($type)") + } + + inline fun instance(type: KClass<*>): T { + return applicationContext.getBean(type.java) as? T + ?: throw BluePrintProcessorException("failed to get instance($type)") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt new file mode 100644 index 000000000..193ff7888 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt @@ -0,0 +1,235 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.databind.node.TextNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.DSLExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData +import org.onap.ccsdk.cds.controllerblueprints.core.data.InputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +object BluePrintExpressionService { + + val log = LoggerFactory.getLogger(this::class.toString()) + + @JvmStatic + fun checkContainsExpression(propertyAssignmentNode: JsonNode): Boolean { + val json = propertyAssignmentNode.toString() + // FIXME("Check if any Optimisation needed") + return ( + json.contains(BluePrintConstants.EXPRESSION_GET_INPUT) || + json.contains(BluePrintConstants.EXPRESSION_GET_ATTRIBUTE) || + json.contains(BluePrintConstants.EXPRESSION_GET_PROPERTY) + ) + } + + @JvmStatic + fun getExpressionData(propertyAssignmentNode: JsonNode): ExpressionData { + log.trace("Assignment Data/Expression : {}", propertyAssignmentNode) + val expressionData = ExpressionData(valueNode = propertyAssignmentNode) + if (propertyAssignmentNode is ObjectNode) { + val commands: Set = propertyAssignmentNode.fieldNames().asSequence().toList().intersect(BluePrintTypes.validCommands()) + if (commands.isNotEmpty()) { + expressionData.isExpression = true + expressionData.command = commands.first() + expressionData.expressionNode = propertyAssignmentNode + + when (expressionData.command) { + BluePrintConstants.EXPRESSION_GET_INPUT -> { + expressionData.inputExpression = populateInputExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> { + expressionData.attributeExpression = populateAttributeExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_PROPERTY -> { + expressionData.propertyExpression = populatePropertyExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { + expressionData.operationOutputExpression = populateOperationOutputExpression(propertyAssignmentNode) + } + BluePrintConstants.EXPRESSION_GET_ARTIFACT -> { + expressionData.artifactExpression = populateArtifactExpression(propertyAssignmentNode) + } + } + } + } else if (propertyAssignmentNode is TextNode && + propertyAssignmentNode.textValue().startsWith(BluePrintConstants.EXPRESSION_DSL_REFERENCE) + ) { + expressionData.isExpression = true + expressionData.command = BluePrintConstants.EXPRESSION_DSL_REFERENCE + expressionData.dslExpression = populateDSLExpression(propertyAssignmentNode) + } + return expressionData + } + + @JvmStatic + fun populateDSLExpression(jsonNode: TextNode): DSLExpression { + return DSLExpression( + propertyName = jsonNode.textValue() + .removePrefix(BluePrintConstants.EXPRESSION_DSL_REFERENCE) + ) + } + + @JvmStatic + fun populateInputExpression(jsonNode: JsonNode): InputExpression { + return InputExpression(propertyName = jsonNode.first().textValue()) + } + + @JvmStatic + fun populatePropertyExpression(jsonNode: JsonNode): PropertyExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing property expression, " + + "it should be [ , , , " + + ", ..., ] , but present {}", + jsonNode + ) + ) + } + var reqOrCapEntityName: String? = null + var propertyName = "" + var subProperty: String? = null + when { + arrayNode.size() == 2 -> propertyName = arrayNode[1].textValue() + arrayNode.size() == 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + propertyName = arrayNode[2].textValue() + } + arrayNode.size() > 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + propertyName = arrayNode[2].textValue() + val propertyPaths: List = arrayNode.filterIndexed { index, _ -> + index >= 3 + }.map { it.textValue() } + subProperty = propertyPaths.joinToString(".") + } + } + + return PropertyExpression( + modelableEntityName = arrayNode[0].asText(), + reqOrCapEntityName = reqOrCapEntityName, + propertyName = propertyName, + subPropertyName = subProperty + ) + } + + @JvmStatic + fun populateAttributeExpression(jsonNode: JsonNode): AttributeExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing attribute expression, " + + "it should be [ , , ," + + " , ..., ] , but present {}", + jsonNode + ) + ) + } + + var reqOrCapEntityName: String? = null + var attributeName = "" + var subAttributeName: String? = null + when { + arrayNode.size() == 2 -> attributeName = arrayNode[1].textValue() + arrayNode.size() == 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + attributeName = arrayNode[2].textValue() + } + arrayNode.size() > 3 -> { + reqOrCapEntityName = arrayNode[1].textValue() + attributeName = arrayNode[2].textValue() + val propertyPaths: List = arrayNode.filterIndexed { index, _ -> + index >= 3 + }.map { it.textValue() } + subAttributeName = propertyPaths.joinToString(".") + } + } + return AttributeExpression( + modelableEntityName = arrayNode[0].asText(), + reqOrCapEntityName = reqOrCapEntityName, + attributeName = attributeName, + subAttributeName = subAttributeName + ) + } + + @JvmStatic + fun populateOperationOutputExpression(jsonNode: JsonNode): OperationOutputExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + + check(arrayNode.size() >= 4) { + throw BluePrintException( + String.format( + "missing operation output expression, " + + "it should be (, , , ) , but present {}", + jsonNode + ) + ) + } + + var subPropertyName: String? = null + if (arrayNode.size() == 5) + subPropertyName = arrayNode[4].asText() + + return OperationOutputExpression( + modelableEntityName = arrayNode[0].asText(), + interfaceName = arrayNode[1].asText(), + operationName = arrayNode[2].asText(), + propertyName = arrayNode[3].asText(), + subPropertyName = subPropertyName + ) + } + + @JvmStatic + fun populateArtifactExpression(jsonNode: JsonNode): ArtifactExpression { + val arrayNode: ArrayNode = jsonNode.first() as ArrayNode + + check(arrayNode.size() >= 2) { + throw BluePrintException( + String.format( + "missing artifact expression, " + + "it should be [ , , , ] , but present {}", + jsonNode + ) + ) + } + return ArtifactExpression( + modelableEntityName = arrayNode[0].asText(), + artifactName = arrayNode[1].asText(), + location = arrayNode[2]?.asText() ?: "LOCAL_FILE", + remove = arrayNode[3]?.asBoolean() ?: false + ) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt new file mode 100644 index 000000000..80b742705 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt @@ -0,0 +1,95 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.utils.ServiceTemplateUtils +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import java.io.File +import java.net.URL +import java.net.URLDecoder +import java.nio.charset.Charset + +class BluePrintImportService(private val parentServiceTemplate: ServiceTemplate, private val blueprintBasePath: String) { + companion object { + + private const val PARENT_SERVICE_TEMPLATE: String = "parent" + } + + private val log: Logger = LoggerFactory.getLogger(this::class.toString()) + + private var importServiceTemplateMap: MutableMap = hashMapOf() + + suspend fun getImportResolvedServiceTemplate(): ServiceTemplate { + // Populate Imported Service Templates + traverseSchema(PARENT_SERVICE_TEMPLATE, parentServiceTemplate) + + importServiceTemplateMap.forEach { key, serviceTemplate -> + ServiceTemplateUtils.merge(parentServiceTemplate, serviceTemplate) + log.debug("merged service template $key") + } + return parentServiceTemplate + } + + private suspend fun traverseSchema(key: String, serviceTemplate: ServiceTemplate) { + if (key != PARENT_SERVICE_TEMPLATE) { + importServiceTemplateMap[key] = serviceTemplate + } + val imports: List? = serviceTemplate.imports + + imports?.let { + serviceTemplate.imports?.forEach { importDefinition -> + val childServiceTemplate = resolveImportDefinition(importDefinition) + val keyName: String = importDefinition.file + traverseSchema(keyName, childServiceTemplate) + } + } + } + + private suspend fun resolveImportDefinition(importDefinition: ImportDefinition): ServiceTemplate { + var serviceTemplate: ServiceTemplate? = null + val file: String = importDefinition.file + val decodedSystemId: String = URLDecoder.decode(file, Charset.defaultCharset().toString()) + log.trace("file ({}), decodedSystemId ({}) ", file, decodedSystemId) + try { + if (decodedSystemId.startsWith("http", true) || + decodedSystemId.startsWith("https", true) + ) { + val givenUrl: String = URL(decodedSystemId).toString() + val systemUrl: String = File(".").toURI().toURL().toString() + log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl) + if (givenUrl.startsWith(systemUrl)) { + } + } else { + if (!decodedSystemId.startsWith("/")) { + importDefinition.file = StringBuilder().append(blueprintBasePath).append(File.separator).append(file).toString() + } + serviceTemplate = ServiceTemplateUtils.getServiceTemplate(importDefinition.file) + } + } catch (e: Exception) { + throw BluePrintException("failed to populate service template for ${importDefinition.file} original error: ${e.message}", e) + } + if (serviceTemplate == null) { + throw BluePrintException("failed to populate service template for : ${importDefinition.file}") + } + return serviceTemplate + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt new file mode 100644 index 000000000..fdc348bf7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.hubspot.jinjava.Jinjava +import com.hubspot.jinjava.JinjavaConfig +import com.hubspot.jinjava.interpret.JinjavaInterpreter +import com.hubspot.jinjava.loader.ResourceLocator +import com.hubspot.jinjava.loader.ResourceNotFoundException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode +import java.io.IOException +import java.nio.charset.Charset +import java.nio.file.Files.readAllBytes +import java.nio.file.Paths + +object BluePrintJinjaTemplateService { + + /** + * To enable inheritance within CBA, we need Jinja runtime to know where to load the templates. + */ + class BlueprintRelatedTemplateLocator( + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val artifactName: String, + private val artifactVersion: String + ) : ResourceLocator { + + @Throws(IOException::class) + override fun getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter): String { + try { + val deployFile = + normalizedPathName( + bluePrintLoadConfiguration.blueprintDeployPath, + artifactName, + artifactVersion, + fullName + ) + + return String(readAllBytes(Paths.get(deployFile))) + } catch (var5: IllegalArgumentException) { + throw ResourceNotFoundException("Couldn't find resource: $fullName") + } + } + } + + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap, + bluePrintLoadConfiguration: BluePrintLoadConfiguration, + artifactName: String, + artifactVersion: String + ): String { + + return generateContent( + template, + json, + ignoreJsonNull, + additionalContext, + BlueprintRelatedTemplateLocator(bluePrintLoadConfiguration, artifactName, artifactVersion) + ) + } + + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap, + resourceLocator: ResourceLocator? = null + ): String { + val jinJava = Jinjava(JinjavaConfig()) + if (resourceLocator != null) { + jinJava.resourceLocator = resourceLocator + } + + val mapper = ObjectMapper() + val nodeFactory = BluePrintJsonNodeFactory() + mapper.nodeFactory = nodeFactory + + // Add the JSON Data to the context + if (json.isNotEmpty()) { + val jsonNode = mapper.readValue(json, JsonNode::class.java) + ?: throw BluePrintProcessorException("couldn't get json node from json") + if (ignoreJsonNull) { + jsonNode.removeNullNode() + } + + val jsonMap: Map = mapper.readValue(json, object : TypeReference>() {}) + additionalContext.putAll(jsonMap) + } + + return jinJava.render(template, additionalContext) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt new file mode 100644 index 000000000..1f71495a3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt @@ -0,0 +1,76 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory + +open class BluePrintRepoFileService(modelTypePath: String) : BluePrintRepoService { + + private val log = LoggerFactory.getLogger(BluePrintRepoFileService::class.toString()) + + private val dataTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + private val nodeTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) + private val artifactTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) + private val capabilityTypePath = + modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) + private val relationshipTypePath = + modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) + private val extension = ".json" + + override fun getDataType(dataTypeName: String): DataType { + val fileName = dataTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(dataTypeName).plus(extension) + return getModelType(fileName, DataType::class.java) + } + + override fun getNodeType(nodeTypeName: String): NodeType { + val fileName = nodeTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(nodeTypeName).plus(extension) + return getModelType(fileName, NodeType::class.java) + } + + override fun getArtifactType(artifactTypeName: String): ArtifactType { + val fileName = artifactTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(artifactTypeName).plus(extension) + return getModelType(fileName, ArtifactType::class.java) + } + + override fun getRelationshipType(relationshipTypeName: String): RelationshipType { + val fileName = relationshipTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(relationshipTypeName).plus(extension) + return getModelType(fileName, RelationshipType::class.java) + } + + override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { + val fileName = capabilityTypePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(capabilityDefinitionName).plus(extension) + return getModelType(fileName, CapabilityDefinition::class.java) + } + + private fun getModelType(fileName: String, valueType: Class): T { + return JacksonUtils.readValueFromFile(fileName, valueType) + ?: throw BluePrintException("couldn't get file($fileName) for type(${valueType.name}") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt new file mode 100644 index 000000000..873e3a082 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt @@ -0,0 +1,799 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing +import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect +import org.slf4j.LoggerFactory +import java.io.File + +interface BluePrintRuntimeService { + + fun id(): String + + fun bluePrintContext(): BluePrintContext + + fun getExecutionContext(): T + + fun setExecutionContext(executionContext: T) + + fun put(key: String, value: JsonNode) + + fun get(key: String): JsonNode? + + fun check(key: String): Boolean + + fun cleanRuntime() + + fun getAsString(key: String): String? + + fun getAsBoolean(key: String): Boolean? + + fun getAsInt(key: String): Int? + + fun getAsDouble(key: String): Double? + + fun getBluePrintError(): BluePrintError + + fun setBluePrintError(bluePrintError: BluePrintError) + + fun loadEnvironments(type: String, fileName: String) + + fun resolveWorkflowOutputs(workflowName: String): MutableMap + + fun resolveDSLExpression(dslPropertyName: String): JsonNode + + /** Resolve Property Definition [definitionName] for type [definitionType] with [propertyDefinitions] + * Definition Type may be : node_template, relationship_template, dsl, workflow + * Assumption is Definition holds the expressions or value assigned in it. Mainly used for workflow outputs. + */ + fun resolvePropertyDefinitions( + definitionType: String, + definitionName: String, + propertyDefinitions: MutableMap + ): MutableMap + + /** Resolve Property Assignments [definitionName] for type [definitionType] with [propertyDefinitions] + * and [propertyAssignments] + * Definition Type may be : node_template, relationship_template, dsl, workflow + */ + fun resolvePropertyAssignments( + definitionType: String, + definitionName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap + + /** Resolve Property Assignments [definitionName] for type [definitionType] with [propertyAssignments] + * Definition Type may be : node_template, relationship_template, dsl, workflow + */ + fun resolvePropertyAssignments( + definitionType: String, + definitionName: String, + propertyAssignments: MutableMap + ): MutableMap + + /** Resolve Node Template [nodeTemplateName] Property Assignments */ + fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap + + /** Resolve Node Template [nodeTemplateName] Property Assignments with [propertyDefinitions] and [propertyAssignments]*/ + fun resolveNodeTemplatePropertyAssignments( + nodeTemplateName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap + + fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): MutableMap + + fun resolveNodeTemplateInterfaceOperationInputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap + + fun resolveNodeTemplateInterfaceOperationOutputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap + + suspend fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String + + fun resolveNodeTemplateArtifactDefinition(nodeTemplateName: String, artifactName: String): ArtifactDefinition + + /** Resolve Node Template [relationshipTemplateName] Property Assignments */ + fun resolveRelationshipTemplateProperties(relationshipTemplateName: String): MutableMap + + /** Resolve Relationship Template [relationshipTemplateName] Property Assignments with + * [propertyDefinitions] and [propertyAssignments] */ + fun resolveRelationshipTemplatePropertyAssignments( + relationshipTemplateName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap + + fun setInputValue(propertyName: String, value: JsonNode) + + fun setWorkflowInputValue( + workflowName: String, + propertyName: String, + propertyDefinition: PropertyDefinition, + value: JsonNode + ) + + fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) + + fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) + + fun setNodeTemplateOperationPropertyValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun setNodeTemplateOperationInputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun setNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) + + fun getInputValue(propertyName: String): JsonNode + + fun getNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String + ): JsonNode + + fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode? + + fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode? + + fun getRelationshipTemplatePropertyValue(relationshipTemplateName: String, propertyName: String): JsonNode? + + fun getRelationshipTemplateAttributeValue(relationshipTemplateName: String, attributeName: String): JsonNode? + + fun assignInputs(jsonNode: JsonNode) + + fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) + + fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List): JsonNode + + suspend fun close() +} + +/** + * + * + * @author Brinda Santh + */ +open class DefaultBluePrintRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) : + BluePrintRuntimeService> { + + @Transient + private val log = LoggerFactory.getLogger(BluePrintRuntimeService::class.toString()) + + private var store: MutableMap = hashMapOf() + + private var bluePrintError = BluePrintError() + + init { + /** + * Load Blueprint Environments Properties + */ + val absoluteEnvFilePath = bluePrintContext.rootPath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR) + loadEnvironments(BluePrintConstants.PROPERTY_BPP, absoluteEnvFilePath) + } + + override fun id(): String { + return id + } + + override fun bluePrintContext(): BluePrintContext { + return bluePrintContext + } + + override fun getExecutionContext(): MutableMap { + return store + } + + @Suppress("UNCHECKED_CAST") + override fun setExecutionContext(executionContext: MutableMap) { + this.store = executionContext + } + + override fun put(key: String, value: JsonNode) { + store[key] = value + } + + override fun get(key: String): JsonNode { + return store[key] ?: throw BluePrintProcessorException("failed to get execution property($key)") + } + + override fun check(key: String): Boolean { + return store.containsKey(key) + } + + override fun cleanRuntime() { + store.clear() + } + + private fun getJsonNode(key: String): JsonNode { + return get(key) + } + + override fun getAsString(key: String): String? { + return get(key).asText() + } + + override fun getAsBoolean(key: String): Boolean? { + return get(key).asBoolean() + } + + override fun getAsInt(key: String): Int? { + return get(key).asInt() + } + + override fun getAsDouble(key: String): Double? { + return get(key).asDouble() + } + + override fun getBluePrintError(): BluePrintError { + return this.bluePrintError + } + + override fun setBluePrintError(bluePrintError: BluePrintError) { + this.bluePrintError = bluePrintError + } + + override fun loadEnvironments(type: String, fileName: String) { + BluePrintMetadataUtils.environmentFileProperties(fileName).forEach { key, value -> + setNodeTemplateAttributeValue(type, key.toString(), value.asJsonType()) + } + } + + override fun resolveWorkflowOutputs(workflowName: String): MutableMap { + log.info("resolveWorkflowOutputs for workflow($workflowName)") + val outputs = bluePrintContext.workflowByName(workflowName).outputs ?: mutableMapOf() + return resolvePropertyDefinitions(BluePrintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, "WORKFLOW", outputs) + } + + /** + * Read the DSL Property reference, If there is any expression, then resolve those expression and return as Json + * Type + */ + override fun resolveDSLExpression(dslPropertyName: String): JsonNode { + val propertyAssignments = bluePrintContext.dslPropertiesByName(dslPropertyName) + return if (BluePrintExpressionService.checkContainsExpression(propertyAssignments) && + propertyAssignments is ObjectNode + ) { + val rootKeyMap = propertyAssignments.rootFieldsToMap() + val propertyAssignmentValue: MutableMap = hashMapOf() + rootKeyMap.forEach { (propertyName, propertyValue) -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + propertyAssignmentValue[propertyName] = propertyAssignmentExpression + .resolveAssignmentExpression( + BluePrintConstants.MODEL_DEFINITION_TYPE_DSL, + "DSL", + propertyName, + propertyValue + ) + } + propertyAssignmentValue.asJsonNode() + } else { + propertyAssignments + } + } + + override fun resolvePropertyDefinitions( + definitionType: String, + definitionName: String, + propertyDefinitions: MutableMap + ): MutableMap { + val propertyAssignmentValue: MutableMap = hashMapOf() + + propertyDefinitions.forEach { (propertyName, propertyDefinition) -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + val expression = propertyDefinition.value ?: propertyDefinition.defaultValue + if (expression != null) { + propertyAssignmentValue[propertyName] = + propertyAssignmentExpression.resolveAssignmentExpression( + definitionType, + definitionName, + propertyName, + expression + ) + } + } + return propertyAssignmentValue + } + + override fun resolvePropertyAssignments( + definitionType: String, + definitionName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap { + + val propertyAssignmentValue: MutableMap = hashMapOf() + + propertyDefinitions.forEach { (nodeTypePropertyName, nodeTypeProperty) -> + // Get the Express or Value for the Node Template + val propertyAssignment: JsonNode? = propertyAssignments[nodeTypePropertyName] + + var resolvedValue: JsonNode = NullNode.getInstance() + if (propertyAssignment != null) { + // Resolve the Expressing + val propertyAssignmentExpression = PropertyAssignmentService(this) + resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression( + definitionType, definitionName, nodeTypePropertyName, propertyAssignment + ) + } + + // Set default value if null + if (resolvedValue is NullNode) { + nodeTypeProperty.defaultValue?.let { resolvedValue = nodeTypeProperty.defaultValue!! } + } + + /** If property is Map type, then resolve the property value, It may have expressions */ + if (nodeTypeProperty.type == BluePrintConstants.DATA_TYPE_MAP && + resolvedValue.returnNullIfMissing() != null + ) { + val mapResolvedValue = resolvePropertyAssignments( + definitionType, definitionName, resolvedValue.rootFieldsToMap() + ) + resolvedValue = mapResolvedValue.asJsonNode() + } + + // Set for Return of method + propertyAssignmentValue[nodeTypePropertyName] = resolvedValue + } + return propertyAssignmentValue + } + + override fun resolvePropertyAssignments( + definitionType: String, + definitionName: String, + propertyAssignments: MutableMap + ): MutableMap { + val propertyAssignmentValue: MutableMap = hashMapOf() + + propertyAssignments.forEach { (propertyName, propertyExpression) -> + val propertyAssignmentExpression = PropertyAssignmentService(this) + propertyAssignmentValue[propertyName] = + propertyAssignmentExpression.resolveAssignmentExpression( + definitionType, definitionName, propertyName, propertyExpression + ) + } + return propertyAssignmentValue + } + + override fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap { + log.info("resolveNodeTemplatePropertyValues for node template ({})", nodeTemplateName) + + val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + val propertyAssignments: MutableMap = nodeTemplate.properties!! + + // Get the Node Type Definitions + val nodeTypePropertiesDefinitions: MutableMap = bluePrintContext + .nodeTypeChainedProperties(nodeTemplate.type)!! + + /** + * Resolve the NodeTemplate Property Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments( + nodeTemplateName, + nodeTypePropertiesDefinitions, + propertyAssignments + ) + } + + /** + * Resolve any property assignments for the node + */ + override fun resolveNodeTemplatePropertyAssignments( + nodeTemplateName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap { + return resolvePropertyAssignments( + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + nodeTemplateName, propertyDefinitions, propertyAssignments + ) + } + + override fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): + MutableMap { + log.info("resolveNodeTemplateCapabilityProperties for node template($nodeTemplateName) capability($capabilityName)") + val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + val propertyAssignments = nodeTemplate.capabilities?.get(capabilityName)?.properties ?: hashMapOf() + + val propertyDefinitions = bluePrintContext.nodeTemplateNodeType(nodeTemplateName) + .capabilities?.get(capabilityName)?.properties ?: hashMapOf() + + /** + * Resolve the Capability Property Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments(nodeTemplateName, propertyDefinitions, propertyAssignments) + } + + override fun resolveNodeTemplateInterfaceOperationInputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap { + log.info( + "resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " + + "interface name($interfaceName), operationName($operationName)" + ) + + val propertyAssignments: MutableMap = + bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) + ?: hashMapOf() + + val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type + + val nodeTypeInterfaceOperationInputs: MutableMap = + bluePrintContext.nodeTypeInterfaceOperationInputs(nodeTypeName, interfaceName, operationName) + ?: hashMapOf() + + log.info("input definition for node template ($nodeTemplateName), values ($propertyAssignments)") + + /** + * Resolve the Property Input Assignment Values. + */ + return resolveNodeTemplatePropertyAssignments( + nodeTemplateName, + nodeTypeInterfaceOperationInputs, + propertyAssignments + ) + } + + override fun resolveNodeTemplateInterfaceOperationOutputs( + nodeTemplateName: String, + interfaceName: String, + operationName: String + ): MutableMap { + log.info( + "resolveNodeTemplateInterfaceOperationOutputs for node template ($nodeTemplateName),interface name " + + "($interfaceName), operationName($operationName)" + ) + + val propertyAssignments: MutableMap = + bluePrintContext.nodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName) + ?: hashMapOf() + + val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type + + val nodeTypeInterfaceOperationOutputs: MutableMap = + bluePrintContext.nodeTypeInterfaceOperationOutputs(nodeTypeName, interfaceName, operationName) + ?: hashMapOf() + + /** + * Resolve the Property Output Assignment Values. + */ + val propertyAssignmentValue = + resolveNodeTemplatePropertyAssignments( + nodeTemplateName, + nodeTypeInterfaceOperationOutputs, + propertyAssignments + ) + + // Store operation output values into context + propertyAssignmentValue.forEach { (key, value) -> + setNodeTemplateOperationOutputValue(nodeTemplateName, interfaceName, operationName, key, value) + } + return propertyAssignmentValue + } + + override suspend fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String { + val artifactDefinition: ArtifactDefinition = + resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) + val propertyAssignmentExpression = PropertyAssignmentService(this) + return propertyAssignmentExpression.artifactContent(artifactDefinition) + } + + override fun resolveNodeTemplateArtifactDefinition( + nodeTemplateName: String, + artifactName: String + ): ArtifactDefinition { + val nodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + return nodeTemplate.artifacts?.get(artifactName) + ?: throw BluePrintProcessorException( + "failed to get artifact definition($artifactName) from the node template" + ) + } + + override fun resolveRelationshipTemplateProperties(relationshipTemplateName: String): MutableMap { + log.info("resolveRelationshipTemplateProperties for relationship template ({})", relationshipTemplateName) + + val relationshipTemplate = bluePrintContext.relationshipTemplateByName(relationshipTemplateName) + + val propertyAssignments = relationshipTemplate.properties!! + + // Get the Relationship Type Definitions + val propertiesDefinitions = bluePrintContext.relationshipTypeByName(relationshipTemplate.type).properties + ?: throw BluePrintProcessorException("failed to get ${relationshipTemplate.type} properties.") + + /** + * Resolve the RelationshipTemplate Property Assignment Values. + */ + return resolveRelationshipTemplatePropertyAssignments( + relationshipTemplateName, + propertiesDefinitions, + propertyAssignments + ) + } + + override fun resolveRelationshipTemplatePropertyAssignments( + relationshipTemplateName: String, + propertyDefinitions: MutableMap, + propertyAssignments: MutableMap + ): MutableMap { + return resolvePropertyAssignments( + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE, + relationshipTemplateName, propertyDefinitions, propertyAssignments + ) + } + + override fun setInputValue(propertyName: String, value: JsonNode) { + val path = """${BluePrintConstants.PATH_INPUTS}${BluePrintConstants.PATH_DIVIDER}$propertyName""" + put(path, value) + } + + override fun setWorkflowInputValue( + workflowName: String, + propertyName: String, + propertyDefinition: PropertyDefinition, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_WORKFLOWS) + .append(BluePrintConstants.PATH_DIVIDER).append(workflowName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).append(attributeName).toString() + put(path, value) + } + + override fun setNodeTemplateOperationPropertyValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + log.trace("setting operation property path ({}), values ({})", path, value) + put(path, value) + } + + override fun setNodeTemplateOperationInputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun setNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String, + value: JsonNode + ) { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OUTPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + put(path, value) + } + + override fun getInputValue(propertyName: String): JsonNode { + val path = StringBuilder(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplateOperationOutputValue( + nodeTemplateName: String, + interfaceName: String, + operationName: String, + propertyName: String + ): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_INTERFACES) + .append(BluePrintConstants.PATH_DIVIDER).append(interfaceName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OPERATIONS) + .append(BluePrintConstants.PATH_DIVIDER).append(operationName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_OUTPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode { + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).append(attributeName).toString() + return getJsonNode(path) + } + + override fun getRelationshipTemplatePropertyValue( + relationshipTemplateName: String, + propertyName: String + ): JsonNode? { + val path: String = StringBuilder(BluePrintConstants.PATH_RELATIONSHIP_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(relationshipTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_PROPERTIES) + .append(BluePrintConstants.PATH_DIVIDER).append(propertyName).toString() + return getJsonNode(path) + } + + override fun getRelationshipTemplateAttributeValue( + relationshipTemplateName: String, + attributeName: String + ): JsonNode? { + val path: String = StringBuilder(BluePrintConstants.PATH_RELATIONSHIP_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(relationshipTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).append(attributeName).toString() + return getJsonNode(path) + } + + override fun assignInputs(jsonNode: JsonNode) { + log.info("assignInputs from input JSON ({})", jsonNode.toString()) + bluePrintContext.inputs()?.forEach { propertyName, property -> + val valueNode: JsonNode = jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName) + ?: property.defaultValue + ?: NullNode.getInstance() + setInputValue(propertyName, valueNode) + } + } + + override fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) { + log.info("Deriving input data for workflow: ($workflowName)") + + val dynamicInputPropertiesName = "$workflowName-properties" + + bluePrintContext.workflowByName(workflowName).inputs + ?.filter { (propertyName, property) -> propertyName != dynamicInputPropertiesName } + ?.forEach { propertyName, property -> findAndSetInputValue(propertyName, property, jsonNode) } + // Load Dynamic data Types + jsonNode.get(dynamicInputPropertiesName)?.let { + bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName") + ?.properties + ?.forEach { propertyName, property -> findAndSetInputValue(propertyName, property, it) } + } + } + + private fun findAndSetInputValue(propertyName: String, property: PropertyDefinition, jsonNode: JsonNode) { + val valueNode = jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName) + .returnNullIfMissing() + ?: property.defaultValue + ?: NullNode.getInstance() + val loggableValue = if (hasLogProtect(property)) LOG_REDACTED else valueNode.toString() + log.trace("Setting input data - attribute:($propertyName) value:($loggableValue)") + setInputValue(propertyName, valueNode) + } + + override fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List): JsonNode { + + val jsonNode: ObjectNode = jacksonObjectMapper().createObjectNode() + val path: String = StringBuilder(BluePrintConstants.PATH_NODE_TEMPLATES) + .append(BluePrintConstants.PATH_DIVIDER).append(nodeTemplateName) + .append(BluePrintConstants.PATH_DIVIDER).append(BluePrintConstants.PATH_ATTRIBUTES) + .append(BluePrintConstants.PATH_DIVIDER).toString() + store.keys.filter { + it.startsWith(path) + }.map { + val key = it.replace(path, "") + if (keys.contains(key)) { + val value = store[it] as JsonNode + jsonNode.set(key, value) + } + } + return jsonNode + } + + override suspend fun close() { + store.clear() + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt new file mode 100644 index 000000000..d7f7b9a60 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt @@ -0,0 +1,65 @@ +/* + * Copyright © 2019 IBM, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTemplateService +import org.springframework.stereotype.Service + +@Service +class BluePrintTemplateService(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration) : + BlueprintTemplateService { + + override suspend fun generateContent( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + nodeTemplateName: String, + artifactName: String, + jsonData: String, + ignoreJsonNull: Boolean, + additionalContext: MutableMap + ): String { + + val artifactDefinition = + bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) + val templateType = artifactDefinition.type + val template = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) + + return when (templateType) { + BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA -> { + BluePrintJinjaTemplateService.generateContent( + template, + jsonData, + ignoreJsonNull, + additionalContext, + bluePrintLoadConfiguration, + bluePrintRuntimeService.bluePrintContext().name(), + bluePrintRuntimeService.bluePrintContext().version() + ) + } + BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY -> { + BluePrintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext) + } + else -> { + throw BluePrintProcessorException( + "Unknown Artifact type, expecting ${BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA}" + + "or ${BluePrintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY}" + ) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt new file mode 100644 index 000000000..8a8ded752 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt @@ -0,0 +1,711 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.google.common.base.Preconditions +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.format +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import java.io.Serializable + +/** + * + * + * @author Brinda Santh + */ +interface BluePrintValidatorService : Serializable { + + @Throws(BluePrintException::class) + fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap) + + @Throws(BluePrintException::class) + fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap) +} + +@Deprecated("Decomposed implementation moved to blueprint-validation module") +open class BluePrintValidatorDefaultService : BluePrintValidatorService { + + val log = LoggerFactory.getLogger(BluePrintValidatorDefaultService::class.toString()) + + lateinit var bluePrintContext: BluePrintContext + lateinit var serviceTemplate: ServiceTemplate + lateinit var properties: MutableMap + var message: StringBuilder = StringBuilder() + private val separator: String = BluePrintConstants.PATH_DIVIDER + var paths: MutableList = arrayListOf() + + @Throws(BluePrintException::class) + override fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap) { + validateBlueprint(bluePrintContext.serviceTemplate, properties) + } + + @Throws(BluePrintException::class) + override fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap) { + this.bluePrintContext = BluePrintContext(serviceTemplate) + this.serviceTemplate = serviceTemplate + this.properties = properties + try { + message.appendln("-> Config Blueprint") + serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) } + serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) } + serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) } + serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) } + serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) } + } catch (e: Exception) { + log.error("validation failed in the path : {}", paths.joinToString(separator), e) + log.error("validation trace message :{} ", message) + throw BluePrintException( + e, + format("failed to validate blueprint on path ({}) with message {}", paths.joinToString(separator), e.message) + ) + } + } + + @Throws(BluePrintException::class) + open fun validateMetadata(metaDataMap: MutableMap) { + paths.add("metadata") + + val templateName = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_NAME] + val templateVersion = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_VERSION] + val templateTags = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_TAGS] + val templateAuthor = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + + Preconditions.checkArgument(StringUtils.isNotBlank(templateName), "failed to get template name metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateVersion), "failed to get template version metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateTags), "failed to get template tags metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateAuthor), "failed to get template author metadata") + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateArtifactTypes(artifactTypes: MutableMap) { + paths.add("artifact_types") + artifactTypes.forEach { artifactName, artifactType -> + paths.add(artifactName) + message.appendln("--> Artifact Type :" + paths.joinToString(separator)) + artifactType.properties?.let { validatePropertyDefinitions(artifactType.properties!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateDataTypes(dataTypes: MutableMap) { + paths.add("dataTypes") + dataTypes.forEach { dataTypeName, dataType -> + paths.add(dataTypeName) + message.appendln("--> DataType :" + paths.joinToString(separator)) + dataType.properties?.let { validatePropertyDefinitions(dataType.properties!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTypes(nodeTypes: MutableMap) { + paths.add("nodeTypes") + nodeTypes.forEach { nodeTypeName, nodeType -> + // Validate Single Node Type + validateNodeType(nodeTypeName, nodeType) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeType(nodeTypeName: String, nodeType: NodeType) { + paths.add(nodeTypeName) + message.appendln("--> Node Type :" + paths.joinToString(separator)) + val derivedFrom: String = nodeType.derivedFrom + // Check Derived From + checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom) + + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + serviceTemplate.nodeTypes?.get(derivedFrom) + ?: throw BluePrintException( + format( + "Failed to get derivedFrom NodeType({})'s for NodeType({}) ", + derivedFrom, nodeTypeName + ) + ) + } + + nodeType.properties?.let { validatePropertyDefinitions(nodeType.properties!!) } + nodeType.capabilities?.let { validateCapabilityDefinitions(nodeTypeName, nodeType) } + nodeType.requirements?.let { validateRequirementDefinitions(nodeTypeName, nodeType) } + nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun checkValidNodeTypesDerivedFrom(nodeTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validNodeTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get node type ({})'s derivedFrom({}) definition ", nodeTypeName, derivedFrom)) + } + } + + @Throws(BluePrintException::class) + open fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) { + paths.add("topology") + message.appendln("--> Topology Template") + topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) } + topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) } + topologyTemplate.workflows?.let { validateWorkFlows(topologyTemplate.workflows!!) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateInputs(inputs: MutableMap) { + paths.add("inputs") + message.appendln("---> Input :" + paths.joinToString(separator)) + validatePropertyDefinitions(inputs) + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTemplates(nodeTemplates: MutableMap) { + paths.add("nodeTemplates") + nodeTemplates.forEach { nodeTemplateName, nodeTemplate -> + validateNodeTemplate(nodeTemplateName, nodeTemplate) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateNodeTemplate(nodeTemplateName: String, nodeTemplate: NodeTemplate) { + paths.add(nodeTemplateName) + message.appendln("---> NodeTemplate :" + paths.joinToString(separator)) + val type: String = nodeTemplate.type + + val nodeType: NodeType = serviceTemplate.nodeTypes?.get(type) + ?: throw BluePrintException(format("Failed to get NodeType({}) definition for NodeTemplate({})", type, nodeTemplateName)) + + nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) } + nodeTemplate.properties?.let { validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) } + nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, nodeTemplateName, nodeTemplate) } + nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, nodeTemplateName, nodeTemplate) } + nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeType, nodeTemplateName, nodeTemplate) } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateArtifactDefinitions(artifacts: MutableMap) { + paths.add("artifacts") + artifacts.forEach { artifactDefinitionName, artifactDefinition -> + paths.add(artifactDefinitionName) + message.appendln("Validating artifact " + paths.joinToString(separator)) + val type: String = artifactDefinition.type + ?: throw BluePrintException(format("type is missing for ArtifactDefinition({})", artifactDefinitionName)) + // Check Artifact Type + checkValidArtifactType(artifactDefinitionName, type) + + val file: String = artifactDefinition.file + ?: throw BluePrintException(format("file is missing for ArtifactDefinition({})", artifactDefinitionName)) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateWorkFlows(workflows: MutableMap) { + paths.add("workflows") + workflows.forEach { workflowName, workflow -> + + // Validate Single workflow + validateWorkFlow(workflowName, workflow) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateWorkFlow(workflowName: String, workflow: Workflow) { + paths.add(workflowName) + message.appendln("---> Workflow :" + paths.joinToString(separator)) + // Step Validation Start + paths.add("steps") + workflow.steps?.forEach { stepName, _ -> + paths.add(stepName) + message.appendln("----> Steps :" + paths.joinToString(separator)) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + // Step Validation Ends + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validatePropertyDefinitions(properties: MutableMap) { + paths.add("properties") + properties.forEach { propertyName, propertyDefinition -> + paths.add(propertyName) + val dataType: String = propertyDefinition.type + when { + BluePrintTypes.validPrimitiveTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validCollectionTypes().contains(dataType) -> { + val entrySchemaType: String = propertyDefinition.entrySchema?.type + ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, propertyName)) + checkPrimitiveOrComplex(entrySchemaType, propertyName) + } + else -> checkPropertyDataType(dataType, propertyName) + } + message.appendln("property " + paths.joinToString(separator) + " of type " + dataType) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validatePropertyAssignments( + nodeTypeProperties: MutableMap, + properties: MutableMap + ) { + properties.forEach { propertyName, propertyAssignment -> + val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName] + ?: throw BluePrintException(format("failed to get definition for the property ({})", propertyName)) + + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + } + + @Throws(BluePrintException::class) + open fun validatePropertyAssignment( + propertyName: String, + propertyDefinition: PropertyDefinition, + propertyAssignment: JsonNode + ) { + // Check and Validate if Expression Node + val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment) + if (!expressionData.isExpression) { + checkPropertyValue(propertyName, propertyDefinition, propertyAssignment) + } + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val capabilities = nodeTemplate.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityAssignment -> + paths.add(capabilityName) + + val capabilityDefinition = nodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) capability definition ({}) " + + "from NodeType({}) ", + nodeTemplateName, capabilityName, nodeTemplate.type + ) + ) + + validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignment( + nodeTemplateName: String, + capabilityName: String, + capabilityDefinition: CapabilityDefinition, + capabilityAssignment: CapabilityAssignment + ) { + + capabilityAssignment.properties?.let { validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) } + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val requirements = nodeTemplate.requirements + paths.add("requirements") + requirements?.forEach { requirementName, requirementAssignment -> + paths.add(requirementName) + val requirementDefinition = nodeType.requirements?.get(requirementName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) requirement definition ({}) from" + + " NodeType({}) ", + nodeTemplateName, requirementName, nodeTemplate.type + ) + ) + // Validate Requirement Assignment + validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignment( + nodeTemplateName: String, + requirementAssignmentName: String, + requirementDefinition: RequirementDefinition, + requirementAssignment: RequirementAssignment + ) { + log.info("Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, requirementAssignmentName) + val requirementNodeTemplateName = requirementAssignment.node!! + val capabilityName = requirementAssignment.capability + val relationship = requirementAssignment.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException( + format( + "Failed to get relationship type ({}) for NodeTemplate({})'s requirement({}) ", + relationship, nodeTemplateName, requirementAssignmentName + ) + ) + } + + val relationShipNodeTemplate = serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeTemplate({})'s for NodeTemplate({}) requirement({}) ", + requirementNodeTemplateName, nodeTemplateName, requirementAssignmentName + ) + ) + + relationShipNodeTemplate.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeTemplate({})'s capability({}) for NodeTemplate ({})'s requirement({}) ", + requirementNodeTemplateName, capabilityName, nodeTemplateName, requirementAssignmentName + ) + ) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + + val interfaces = nodeTemplate.interfaces + paths.add("interfaces") + interfaces?.forEach { interfaceAssignmentName, interfaceAssignment -> + paths.add(interfaceAssignmentName) + val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) interface definition ({}) from" + + " NodeType({}) ", + nodeTemplateName, interfaceAssignmentName, nodeTemplate.type + ) + ) + + validateInterfaceAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + validateInterfaceOperationsAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + } + } + + @Throws(BluePrintException::class) + open fun validateInterfaceOperationsAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + it.forEach { operationAssignmentName, operationAssignments -> + + val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) ", + nodeTemplateName, operationAssignmentName + ) + ) + + log.info( + "Validation NodeTemplate({}) Interface({}) Operation ({})", nodeTemplateName, + interfaceAssignmentName, operationAssignmentName + ) + + val inputs = operationAssignments.inputs + val outputs = operationAssignments.outputs + + inputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.inputs?.get(propertyName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) " + + "property definition({})", + nodeTemplateName, operationAssignmentName, propertyName + ) + ) + // Check the property values with property definition + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + + outputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.outputs?.get(propertyName) + ?: throw BluePrintException( + format( + "Failed to get NodeTemplate({}) operation definition ({}) " + + "output property definition({})", + nodeTemplateName, operationAssignmentName, + propertyName + ) + ) + // Check the property values with property definition + validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + } + } + } + + @Throws(BluePrintException::class) + open fun validateCapabilityDefinitions(nodeTypeName: String, nodeType: NodeType) { + val capabilities = nodeType.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityDefinition -> + paths.add(capabilityName) + + validateCapabilityDefinition(nodeTypeName, nodeType, capabilityName, capabilityDefinition) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityDefinition( + nodeTypeName: String, + nodeType: NodeType, + capabilityName: String, + capabilityDefinition: CapabilityDefinition + ) { + val capabilityType = capabilityDefinition.type + check(BluePrintTypes.validCapabilityTypes.contains(capabilityType)) { + throw BluePrintException( + format( + "Failed to get CapabilityType({}) for NodeType({})", + capabilityType, nodeTypeName + ) + ) + } + } + + @Throws(BluePrintException::class) + open fun validateRequirementDefinitions(nodeName: String, nodeType: NodeType) { + paths.add("requirements") + val requirements = nodeType.requirements + + requirements?.forEach { requirementDefinitionName, requirementDefinition -> + paths.add(requirementDefinitionName) + message.appendln("Validating : " + paths.joinToString(separator)) + validateRequirementDefinition(nodeName, nodeType, requirementDefinitionName, requirementDefinition) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateRequirementDefinition( + nodeTypeName: String, + nodeType: NodeType, + requirementDefinitionName: String, + requirementDefinition: RequirementDefinition + ) { + + log.info("Validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName) + val requirementNodeTypeName = requirementDefinition.node!! + val capabilityName = requirementDefinition.capability + val relationship = requirementDefinition.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException( + format( + "Failed to get relationship({}) for NodeType({})'s requirement({}) ", + relationship, nodeTypeName, requirementDefinitionName + ) + ) + } + + val relationShipNodeType = serviceTemplate.nodeTypes?.get(requirementNodeTypeName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeType({})'s for requirement({}) ", + requirementNodeTypeName, requirementDefinitionName + ) + ) + + relationShipNodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + format( + "Failed to get requirement NodeType({})'s capability({}) for NodeType ({})'s requirement({}) ", + requirementNodeTypeName, capabilityName, nodeTypeName, requirementDefinitionName + ) + ) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceDefinitions(interfaces: MutableMap) { + paths.add("interfaces") + interfaces.forEach { interfaceName, interfaceDefinition -> + paths.add(interfaceName) + message.appendln("Validating : " + paths.joinToString(separator)) + interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateOperationDefinitions(operations: MutableMap) { + paths.add("operations") + operations.forEach { opertaionName, operationDefinition -> + paths.add(opertaionName) + message.appendln("Validating : " + paths.joinToString(separator)) + operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) } + operationDefinition.inputs?.let { validatePropertyDefinitions(operationDefinition.inputs!!) } + operationDefinition.outputs?.let { validatePropertyDefinitions(operationDefinition.outputs!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateImplementation(implementation: Implementation) { + checkNotEmpty(implementation.primary) { "couldn't get implementation" } + } + + @Throws(BluePrintException::class) + open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) { + + val artifactType = serviceTemplate.artifactTypes?.get(artifactTypeName) + ?: throw BluePrintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)") + + checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom) + } + + @Throws(BluePrintException::class) + open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition") + } + } + + @Throws(BluePrintException::class) + open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom)) + } + } + + @Throws(BluePrintException::class) + open fun checkValidRelationshipTypeDerivedFrom(relationshipTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validRelationShipDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get relationship type ({})'s derivedFrom({}) definition ", relationshipTypeName, derivedFrom)) + } + } + + open fun checkPropertyValue(propertyName: String, propertyDefinition: PropertyDefinition, propertyAssignment: JsonNode) { + val propertyType = propertyDefinition.type + val isValid: Boolean + + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) { + isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment) + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + + val entrySchemaType = propertyDefinition.entrySchema?.type + ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName)) + + if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) { + checkPropertyDataType(entrySchemaType, propertyName) + } + isValid = JacksonUtils.checkJsonNodeValueOfCollectionType(propertyType, propertyAssignment) + } else { + checkPropertyDataType(propertyType, propertyName) + isValid = true + } + + check(isValid) { + throw BluePrintException( + format( + "property({}) defined of type({}) is not comptable with the value ({})", + propertyName, propertyType, propertyAssignment + ) + ) + } + } + + private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { + + val dataType = serviceTemplate.dataTypes?.get(dataTypeName) + ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) + + checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) + } + + private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { + if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { + return true + } else { + throw BluePrintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName)) + } + } + + private fun checkDataType(key: String): Boolean { + return serviceTemplate.dataTypes?.containsKey(key) ?: false + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt new file mode 100644 index 000000000..43e27d047 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt @@ -0,0 +1,99 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Modifications Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.commons.lang3.BooleanUtils +import org.apache.commons.lang3.StringUtils +import org.apache.velocity.VelocityContext +import org.apache.velocity.app.VelocityEngine +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory +import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode +import java.io.StringWriter + +object BluePrintVelocityTemplateService { + + /** + * Generate Content from Velocity Template and JSON Content with injected API + */ + fun generateContent( + template: String, + json: String, + ignoreJsonNull: Boolean = false, + additionalContext: MutableMap = mutableMapOf() + ): String { + + // Customized Object Mapper to remove String double quotes + val mapper = ObjectMapper() + val nodeFactory = BluePrintJsonNodeFactory() + mapper.nodeFactory = nodeFactory + + val jsonNode: JsonNode? = if (json.isNotEmpty()) { + mapper.readValue(json, JsonNode::class.java) + ?: throw BluePrintProcessorException("couldn't get json node from json") + } else { + null + } + return generateContent(template, jsonNode, ignoreJsonNull, additionalContext) + } + + /** + * Generate Content from Velocity Template and JSON Node with injected API + */ + fun generateContent( + template: String, + jsonNode: JsonNode?, + ignoreJsonNull: Boolean = false, + additionalContext: MutableMap = mutableMapOf() + ): String { + + /* + * create a new instance of the velocity engine + */ + val velocity = VelocityEngine() + + /* + * initialize the engine + */ + velocity.init() + + val velocityContext = VelocityContext() + velocityContext.put("StringUtils", StringUtils::class.java) + velocityContext.put("BooleanUtils", BooleanUtils::class.java) + + // Add the Custom Velocity Context API + additionalContext.forEach { (name, value) -> velocityContext.put(name, value) } + + // Add the JSON Data to the context + if (jsonNode != null) { + if (ignoreJsonNull) + jsonNode.removeNullNode() + jsonNode.fields().forEach { entry -> + velocityContext.put(entry.key, entry.value) + } + } + + val stringWriter = StringWriter() + velocity.evaluate(velocityContext, stringWriter, "TemplateData", template) + stringWriter.flush() + return stringWriter.toString() + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt new file mode 100644 index 000000000..f3e4e59aa --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt @@ -0,0 +1,353 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.channels.actor +import kotlinx.coroutines.channels.consumeEach +import kotlinx.coroutines.launch +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeStatus +import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeStatus +import org.onap.ccsdk.cds.controllerblueprints.core.incomingEdges +import org.onap.ccsdk.cds.controllerblueprints.core.isEndNode +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdges +import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdgesNotInLabels +import org.onap.ccsdk.cds.controllerblueprints.core.startNodes +import kotlin.coroutines.CoroutineContext + +interface BluePrintWorkFlowService { + + /** Executes imperative workflow graph [graph] for the bluePrintRuntimeService [bluePrintRuntimeService] + * and workflow input [input]*/ + suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: In): Out + + suspend fun initializeWorkflow(input: In): EdgeLabel + + suspend fun prepareWorkflowOutput(): Out + + /** Prepare the message for the Node */ + suspend fun prepareNodeExecutionMessage(node: Graph.Node): NodeExecuteMessage + + suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage + + suspend fun executeNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun skipNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun cancelNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel + + suspend fun restartNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel +} + +/** Workflow Message Types */ +sealed class WorkflowMessage + +class WorkflowExecuteMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() + +class WorkflowCancelMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() + +class WorkflowRestartMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() + +/** Node Message Types */ +sealed class NodeMessage + +class NodeReadyMessage(val fromEdge: Graph.Edge, val edgeAction: EdgeAction) : NodeMessage() + +class NodeExecuteMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() + +class NodeRestartMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() + +class NodeSkipMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() + +class NodeCancelMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() + +enum class EdgeAction(val id: String) { + EXECUTE("execute"), + SKIP("skip") +} + +/** Abstract workflow service implementation */ +abstract class AbstractBluePrintWorkFlowService : CoroutineScope, BluePrintWorkFlowService { + + lateinit var graph: Graph + + private val log = logger(AbstractBluePrintWorkFlowService::class) + + private val job = Job() + + lateinit var workflowId: String + + var exceptions: MutableList = arrayListOf() + + override val coroutineContext: CoroutineContext + get() = job + CoroutineName("Wf") + + fun cancel() { + log.info("Received workflow($workflowId) cancel request") + job.cancel() + throw CancellationException("Workflow($workflowId) cancelled as requested") + } + + suspend fun workflowActor() = actor>(coroutineContext, Channel.UNLIMITED) { + /** Process the workflow execution message */ + suspend fun executeMessageActor(workflowExecuteMessage: WorkflowExecuteMessage) { + + val nodeActor = nodeActor() + // Prepare Workflow and Populate the Initial store + initializeWorkflow(workflowExecuteMessage.input) + + val startNode = graph.startNodes().first() + // Prepare first node message and Send NodeExecuteMessage + // Start node doesn't wait for any nodes, so we can pass Execute message directly + val nodeExecuteMessage = prepareNodeExecutionMessage(startNode) + /** Send message from workflow actor to node actor */ + launch { + nodeActor.send(nodeExecuteMessage) + } + // Wait for workflow completion or Error + nodeActor.invokeOnClose { exception -> + launch { + if (exception != null) exceptions.add(BluePrintProcessorException(exception)) + log.info("workflow($workflowId) nodes completed with (${exceptions.size})exceptions") + val workflowOutput = prepareWorkflowOutput() + workflowExecuteMessage.output.complete(workflowOutput) + channel.close() + } + } + } + + /** Process each actor message received based on type */ + consumeEach { message -> + when (message) { + is WorkflowExecuteMessage -> { + launch { + try { + executeMessageActor(message) + } catch (e: Exception) { + exceptions.add(e) + } + } + } + is WorkflowRestartMessage -> { + launch { + TODO("") + } + } + is WorkflowCancelMessage -> { + launch { + TODO("") + } + } + } + } + } + + private suspend fun nodeActor() = actor>(coroutineContext, Channel.UNLIMITED) { + + /** Send message to process from one state to other state */ + fun sendNodeMessage(nodeMessage: NodeMessage) = launch { + channel.send(nodeMessage) + } + + /** Process the cascade node processing, based on the previous state of the node */ + fun processNextNodes(node: Graph.Node, nodeState: EdgeLabel) { + // Process only Next Success Node + val stateEdges = graph.outgoingEdges(node.id, arrayListOf(nodeState)) + if (stateEdges.isNotEmpty()) { + stateEdges.forEach { stateEdge -> + // Prepare next node ready message and Send NodeReadyMessage + val nodeReadyMessage = NodeReadyMessage(stateEdge, EdgeAction.EXECUTE) + sendNodeMessage(nodeReadyMessage) + } + } + } + + suspend fun triggerToExecuteOrSkip(message: NodeReadyMessage) { + val edge = message.fromEdge + val node = edge.target + // Check if current edge action is Skip or Execute + when (message.edgeAction) { + EdgeAction.SKIP -> { + val skipMessage = prepareNodeSkipMessage(node) + sendNodeMessage(skipMessage) + } + EdgeAction.EXECUTE -> { + val nodeExecuteMessage = prepareNodeExecutionMessage(node) + sendNodeMessage(nodeExecuteMessage) + } + } + } + + suspend fun readyNodeWorker(message: NodeReadyMessage) { + val edge = message.fromEdge + val node = edge.target + log.debug("@@@@@ Ready workflow($workflowId), node($node) from edge($edge) for action(${message.edgeAction}) @@@@@") + // Update the current incoming edge status to executed or skipped + when (message.edgeAction) { + EdgeAction.SKIP -> message.fromEdge.status = EdgeStatus.SKIPPED + EdgeAction.EXECUTE -> message.fromEdge.status = EdgeStatus.EXECUTED + } + val incomingEdges = graph.incomingEdges(node.id) + if (incomingEdges.size > 1) { + // Check all incoming edges executed or skipped + val notCompletedEdges = incomingEdges.filter { it.status == EdgeStatus.NOT_STARTED } + if (notCompletedEdges.isEmpty()) { + // Possibility of skip edge action performed at last, but other edges have execute action. + val executePresent = incomingEdges.filter { it.status == EdgeStatus.EXECUTED } + val newMessage = if (executePresent.isNotEmpty()) { + NodeReadyMessage(message.fromEdge, EdgeAction.EXECUTE) + } else { + message + } + triggerToExecuteOrSkip(newMessage) + } else { + log.info("node(${node.id}) is waiting for incoming edges($notCompletedEdges)") + } + } else { + triggerToExecuteOrSkip(message) + } + } + + suspend fun executeNodeWorker(message: NodeExecuteMessage) { + val node = message.node + node.status = NodeStatus.EXECUTING + val nodeState = if (node.id == BluePrintConstants.GRAPH_START_NODE_NAME || + node.id == BluePrintConstants.GRAPH_END_NODE_NAME + ) { + EdgeLabel.SUCCESS + } else { + log.debug("##### Processing workflow($workflowId) node($node) #####") + // Call the Extension function and get the next Edge state. + executeNode(node, message.nodeInput, message.nodeOutput) + } + // Update Node Completed + node.status = NodeStatus.EXECUTED + log.info("Execute node(${node.id}) -> executed state($nodeState)") + // Check if the Node status edge is there, If not close processing + val edgePresent = graph.outgoingEdges(node.id, nodeState).isNotEmpty() + + // If End Node, Send End Message + if (graph.isEndNode(node)) { + // Close the current channel + channel.close() + } else if (!edgePresent) { + throw BluePrintProcessorException("node(${node.id}) outgoing edge($nodeState) is missing.") + } else { + val skippingEdges = graph.outgoingEdgesNotInLabels(node.id, arrayListOf(nodeState)) + log.debug("Skipping node($node)'s outgoing edges($skippingEdges)") + // Process Skip Edges + skippingEdges.forEach { skippingEdge -> + // Prepare next node ready message and Send NodeReadyMessage + val nodeReadyMessage = NodeReadyMessage(skippingEdge, EdgeAction.SKIP) + sendNodeMessage(nodeReadyMessage) + } + // Process Success Node + processNextNodes(node, nodeState) + } + } + + suspend fun skipNodeWorker(message: NodeSkipMessage) { + val node = message.node + val incomingEdges = graph.incomingEdges(node.id) + // Check All Incoming Nodes Skipped + val nonSkippedEdges = incomingEdges.filter { + it.status == EdgeStatus.NOT_STARTED + } + log.debug("Node($node) incoming edges ($incomingEdges), not skipped incoming edges ($nonSkippedEdges)") + + if (nonSkippedEdges.isEmpty()) { + log.debug("$$$$$ Skipping workflow($workflowId) node($node) $$$$$") + // Call the Extension Function + val nodeState = skipNode(node, message.nodeInput, message.nodeOutput) + log.info("Skip node(${node.id}) -> executed state($nodeState)") + // Mark the Current node as Skipped + node.status = NodeStatus.SKIPPED + // Look for next possible skip nodes + graph.outgoingEdges(node.id).forEach { outgoingEdge -> + val nodeReadyMessage = NodeReadyMessage(outgoingEdge, EdgeAction.SKIP) + sendNodeMessage(nodeReadyMessage) + } + } + } + + fun restartNodeWorker(message: NodeRestartMessage) = launch { + TODO() + } + + fun cancelNodeWorker(messageWorkflow: WorkflowCancelMessage) = launch { + channel.close() + throw CancellationException("Workflow($workflowId) actor cancelled as requested.") + } + + /** Process each actor message received based on type **/ + consumeEach { nodeMessage -> + when (nodeMessage) { + is NodeReadyMessage -> { + // Blocking call + try { + readyNodeWorker(nodeMessage) + } catch (e: Exception) { + exceptions.add(e) + channel.close() + } + } + is NodeExecuteMessage -> { + launch { + try { + executeNodeWorker(nodeMessage) + } catch (e: Exception) { + nodeMessage.node.status = NodeStatus.TERMINATED + exceptions.add(e) + channel.close() + } + } + } + is NodeSkipMessage -> { + launch { + try { + skipNodeWorker(nodeMessage) + } catch (e: Exception) { + nodeMessage.node.status = NodeStatus.TERMINATED + exceptions.add(e) + channel.close() + } + } + } + is NodeRestartMessage -> { + launch { + try { + restartNodeWorker(nodeMessage) + } catch (e: Exception) { + exceptions.add(e) + channel.close() + } + } + } + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintChainedService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintChainedService.kt deleted file mode 100644 index e0a0f170b..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintChainedService.kt +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition - -/** - * - * - * @author Brinda Santh - */ -internal class BlueprintChainedService { - - var bpc: BlueprintContext - - constructor(bpc: BlueprintContext) { - this.bpc = bpc - } - - fun nodeTypeChained(nodeTypeName: String): NodeType { - - val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) - val attributes = hashMapOf() - val properties = hashMapOf() - val requirements = hashMapOf() - val capabilities = hashMapOf() - val interfaces = hashMapOf() - val artifacts = hashMapOf() - - recNodeTypesChained(nodeTypeName).forEach { nodeType -> - - val subAttributes = bpc.nodeTypeByName(nodeType.id!!).attributes - if (subAttributes != null) { - attributes.putAll(subAttributes) - } - - val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties - if (subProperties != null) { - properties.putAll(subProperties) - } - - val subRequirements = bpc.nodeTypeByName(nodeType.id!!).requirements - if (subRequirements != null) { - requirements.putAll(subRequirements) - } - val subCapabilities = bpc.nodeTypeByName(nodeType.id!!).capabilities - if (subCapabilities != null) { - capabilities.putAll(subCapabilities) - } - val subInterfaces = bpc.nodeTypeByName(nodeType.id!!).interfaces - if (subInterfaces != null) { - interfaces.putAll(subInterfaces) - } - - val subArtifacts = bpc.nodeTypeByName(nodeType.id!!).artifacts - if (subArtifacts != null) { - artifacts.putAll(subArtifacts) - } - } - nodeType.attributes = attributes - nodeType.properties = properties - nodeType.requirements = requirements - nodeType.capabilities = capabilities - nodeType.interfaces = interfaces - nodeType.artifacts = artifacts - return nodeType - } - - fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap? { - val nodeType = bpc.nodeTypeByName(nodeTypeName) - val properties = hashMapOf() - - recNodeTypesChained(nodeTypeName).forEach { nodeType -> - val subProperties = bpc.nodeTypeByName(nodeType.id!!).properties - if (subProperties != null) { - properties.putAll(subProperties) - } - } - return properties - } - - private fun recNodeTypesChained(nodeTypeName: String, nodeTypes: MutableList? = arrayListOf()): MutableList { - val nodeType: NodeType = bpc.nodeTypeByName(nodeTypeName) - nodeType.id = nodeTypeName - val derivedFrom: String = nodeType.derivedFrom - if (!BlueprintTypes.rootNodeTypes().contains(derivedFrom)) { - recNodeTypesChained(derivedFrom, nodeTypes) - } - nodeTypes!!.add(nodeType) - return nodeTypes - } - - private fun recDataTypesChained(dataTypeName: String, dataTypes: MutableList? = arrayListOf()): MutableList { - val dataType: DataType = bpc.dataTypeByName(dataTypeName)!! - dataType.id = dataTypeName - val derivedFrom: String = dataType.derivedFrom - if (!BlueprintTypes.rootDataTypes().contains(derivedFrom)) { - recDataTypesChained(derivedFrom, dataTypes) - } - dataTypes!!.add(dataType) - return dataTypes - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContext.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContext.kt deleted file mode 100644 index 62026be88..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContext.kt +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@file:Suppress("unused") - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory - -/** - * - * - * @author Brinda Santh - */ -class BlueprintContext(val serviceTemplate: ServiceTemplate) { - - private val log = LoggerFactory.getLogger(this::class.toString()) - - /** - * Blueprint CBA extracted file location - */ - var rootPath = "." - - /** - * Root Definition file path - */ - var entryDefinition = "" - - /** Other definitions along with model, It may Resource Definition, Resource Assignments, Configurations etc..*/ - var otherDefinitions: MutableMap = hashMapOf() - - fun otherDefinition(key: String) = otherDefinitions[key] as T - - fun checkOtherDefinition(key: String) = otherDefinitions.containsKey(key) - - fun imports(): List? = serviceTemplate.imports - - fun dslDefinitions() = serviceTemplate.dslDefinitions - - val metadata: MutableMap? = serviceTemplate.metadata - - fun dataTypes(): MutableMap? = serviceTemplate.dataTypes - - fun inputs(): MutableMap? = serviceTemplate.topologyTemplate?.inputs - - fun blueprintJson(pretty: Boolean = false): String = print("json", pretty) - - private fun print(type: String? = "json", pretty: Boolean = false): String { - return JacksonUtils.getJson(serviceTemplate, pretty) - } - - fun name(): String = metadata?.get(BlueprintConstants.METADATA_TEMPLATE_NAME) - ?: throw BlueprintException("could't get template name from meta data") - - fun version(): String = metadata?.get(BlueprintConstants.METADATA_TEMPLATE_VERSION) - ?: throw BlueprintException("could't get template version from meta data") - - fun author(): String = metadata?.get(BlueprintConstants.METADATA_TEMPLATE_AUTHOR) - ?: throw BlueprintException("could't get template author from meta data") - - // Workflow - fun workflows(): MutableMap? = serviceTemplate.topologyTemplate?.workflows - - fun workflowByName(workFlowName: String): Workflow = workflows()?.get(workFlowName) - ?: throw BlueprintException("could't get workflow($workFlowName)") - - fun workflowInputs(workFlowName: String) = workflowByName(workFlowName).inputs - - fun workflowSteps(workFlowName: String) = - workflowByName(workFlowName).steps ?: throw BlueprintException("could't get steps for workflow($workFlowName)") - - fun workflowStepByName(workFlowName: String, stepName: String): Step { - return workflowSteps(workFlowName)[stepName] - ?: throw BlueprintException("could't get step($stepName) for workflow($workFlowName)") - } - - fun workflowStepNodeTemplate(workFlowName: String, stepName: String): String { - return workflowStepByName(workFlowName, stepName).target - ?: throw BlueprintException("could't get node template name for workflow($workFlowName)'s step($stepName)") - } - - fun workflowFirstStepNodeTemplate(workFlowName: String): String { - val firstStepName = workflowSteps(workFlowName).keys.ifEmpty { - throw BlueprintException("could't get first step for workflow($workFlowName)") - }.first() - return workflowStepNodeTemplate(workFlowName, firstStepName) - } - - fun workflowStepFirstCallOperation(workFlowName: String, stepName: String): String { - return workflowStepByName( - workFlowName, - stepName - ).activities?.filter { it.callOperation != null }?.single()?.callOperation - ?: throw BlueprintException("couldn't get first callOperation for WorkFlow($workFlowName) ") - } - - // DSL - fun dslPropertiesByName(name: String): JsonNode = dslDefinitions()?.get(name) - ?: throw BlueprintException("couldn't get policy type for the dsl($name)") - - // Data Type - fun dataTypeByName(name: String): DataType? = dataTypes()?.get(name) - - // Artifact Type - fun artifactTypes(): MutableMap? = serviceTemplate.artifactTypes - - // Policy Types - fun policyTypes(): MutableMap? = serviceTemplate.policyTypes - - fun policyTypeByName(policyName: String) = policyTypes()?.get(policyName) - ?: throw BlueprintException("could't get policy type for the name($policyName)") - - fun policyTypesDerivedFrom(name: String): MutableMap? { - return policyTypes()?.filterValues { policyType -> policyType.derivedFrom == name }?.toMutableMap() - } - - fun policyTypesTarget(target: String): MutableMap? { - return policyTypes()?.filterValues { it.targets.contains(target) }?.toMutableMap() - } - - fun policyTypesTargetNDerivedFrom(target: String, derivedFrom: String): MutableMap? { - return policyTypesDerivedFrom(derivedFrom)?.filterValues { - it.targets.contains(target) - }?.toMutableMap() - } - - // Node Type Methods - fun nodeTypes(): MutableMap? = serviceTemplate.nodeTypes - - fun nodeTypeByName(name: String): NodeType = - nodeTypes()?.get(name) - ?: throw BlueprintException("could't get node type for the name($name)") - - fun nodeTypeDerivedFrom(name: String): MutableMap? { - return nodeTypes()?.filterValues { nodeType -> nodeType.derivedFrom == name }?.toMutableMap() - } - - fun nodeTypeInterface(nodeTypeName: String, interfaceName: String): InterfaceDefinition { - return nodeTypeByName(nodeTypeName).interfaces?.get(interfaceName) - ?: throw BlueprintException("could't get node type($nodeTypeName)'s interface definition($interfaceName)") - } - - fun nodeTypeInterfaceOperation( - nodeTypeName: String, - interfaceName: String, - operationName: String - ): OperationDefinition { - return nodeTypeInterface(nodeTypeName, interfaceName).operations?.get(operationName) - ?: throw BlueprintException("could't get node type($nodeTypeName)'s interface definition($interfaceName) operation definition($operationName)") - } - - fun interfaceNameForNodeType(nodeTypeName: String): String { - return nodeTypeByName(nodeTypeName).interfaces?.keys?.first() - ?: throw BlueprintException("could't get NodeType($nodeTypeName)'s first InterfaceDefinition name") - } - - fun nodeTypeInterfaceOperationInputs( - nodeTypeName: String, - interfaceName: String, - operationName: String - ): MutableMap? { - return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).inputs - } - - fun nodeTypeInterfaceOperationOutputs( - nodeTypeName: String, - interfaceName: String, - operationName: String - ): MutableMap? { - return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).outputs - } - - // Relationship Type Methods - fun relationshipTypes(): MutableMap? = serviceTemplate.relationshipTypes - - fun relationshipTypeByName(name: String): RelationshipType = relationshipTypes()?.get(name) - ?: throw BlueprintException("could't get relationship type for the name($name)") - - // Node Template Methods - fun nodeTemplates(): MutableMap? = serviceTemplate.topologyTemplate?.nodeTemplates - - fun nodeTemplateByName(name: String): NodeTemplate = - nodeTemplates()?.get(name) ?: throw BlueprintException("could't get node template for the name($name)") - - fun nodeTemplateForNodeType(name: String): MutableMap? { - return nodeTemplates()?.filterValues { nodeTemplate -> nodeTemplate.type == name }?.toMutableMap() - } - - fun nodeTemplateNodeType(nodeTemplateName: String): NodeType { - val nodeTemplateType: String = nodeTemplateByName(nodeTemplateName).type - return nodeTypeByName(nodeTemplateType) - } - - fun nodeTemplateProperty(nodeTemplateName: String, propertyName: String): Any? { - return nodeTemplateByName(nodeTemplateName).properties?.get(propertyName) - } - - fun nodeTemplateArtifacts(nodeTemplateName: String): MutableMap? { - return nodeTemplateByName(nodeTemplateName).artifacts - } - - fun checkNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition? { - return nodeTemplateArtifacts(nodeTemplateName)?.get(artifactName) - } - - fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition { - return checkNodeTemplateArtifact(nodeTemplateName, artifactName) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s ArtifactDefinition($artifactName)") - } - - fun nodeTemplateArtifactForArtifactType(nodeTemplateName: String, artifactType: String): ArtifactDefinition { - return nodeTemplateArtifacts(nodeTemplateName)?.filter { it.value.type == artifactType }?.map { it.value }?.get(0) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s Artifact Type($artifactType)") - } - - fun nodeTemplateFirstInterface(nodeTemplateName: String): InterfaceAssignment { - return nodeTemplateByName(nodeTemplateName).interfaces?.values?.first() - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment") - } - - fun nodeTemplateFirstInterfaceName(nodeTemplateName: String): String { - return nodeTemplateByName(nodeTemplateName).interfaces?.keys?.first() - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment name") - } - - fun nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName: String): String { - return nodeTemplateFirstInterface(nodeTemplateName).operations?.keys?.first() - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s first InterfaceAssignment's first OperationAssignment name") - } - - fun nodeTemplateOperationImplementation(nodeTemplateName: String, interfaceName: String, operationName: String): - Implementation? { - return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).implementation - } - - fun nodeTemplateInterfaceOperationInputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap? { - return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).inputs - } - - fun nodeTemplateInterfaceOperationOutputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap? { - return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).outputs - } - - fun nodeTemplateInterface(nodeTemplateName: String, interfaceName: String): InterfaceAssignment { - return nodeTemplateByName(nodeTemplateName).interfaces?.get(interfaceName) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName)") - } - - fun nodeTemplateInterfaceOperation( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): OperationAssignment { - return nodeTemplateInterface(nodeTemplateName, interfaceName).operations?.get(operationName) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s InterfaceAssignment($interfaceName) OperationAssignment($operationName)") - } - - fun nodeTemplateCapability(nodeTemplateName: String, capabilityName: String): CapabilityAssignment { - return nodeTemplateByName(nodeTemplateName).capabilities?.get(capabilityName) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s CapabilityAssignment($capabilityName)") - } - - fun nodeTemplateRequirement(nodeTemplateName: String, requirementName: String): RequirementAssignment { - return nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName) - ?: throw BlueprintException("could't get NodeTemplate($nodeTemplateName)'s first RequirementAssignment($requirementName)") - } - - fun nodeTemplateRequirementNode(nodeTemplateName: String, requirementName: String): NodeTemplate { - val filteredNodeTemplateName: String = - nodeTemplateByName(nodeTemplateName).requirements?.get(requirementName)?.node - ?: throw BlueprintException("could't NodeTemplate for NodeTemplate's($nodeTemplateName) requirement's ($requirementName) ") - return nodeTemplateByName(filteredNodeTemplateName) - } - - fun nodeTemplateCapabilityProperty(nodeTemplateName: String, capabilityName: String, propertyName: String): Any? { - return nodeTemplateCapability(nodeTemplateName, capabilityName).properties?.get(propertyName) - } - - // Relationship Template Methods - fun relationshipTemplates(): MutableMap? = - serviceTemplate.topologyTemplate?.relationshipTemplates - - fun relationshipTemplateByName(name: String): RelationshipTemplate = relationshipTemplates()?.get(name) - ?: throw BlueprintException("could't get relationship template for the name($name)") - - fun relationshipTemplateProperty(relationshipTemplateName: String, propertyName: String): Any? { - return nodeTemplateByName(relationshipTemplateName).properties?.get(propertyName) - } - - fun relationshipTemplateForRelationshipType(name: String): MutableMap? { - return relationshipTemplates()?.filterValues { relationshipTemplate -> relationshipTemplate.type == name } - ?.toMutableMap() - } - - fun relationshipTemplateRelationshipType(relationshipName: String): RelationshipType { - val relationshipTemplateType: String = relationshipTemplateByName(relationshipName).type - return relationshipTypeByName(relationshipTemplateType) - } - - // Chained Functions - - fun nodeTypeChained(nodeTypeName: String): NodeType { - return BlueprintChainedService(this).nodeTypeChained(nodeTypeName) - } - - fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap? { - return BlueprintChainedService(this).nodeTypeChainedProperties(nodeTypeName) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintDependencyService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintDependencyService.kt deleted file mode 100644 index 8f3308568..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintDependencyService.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.springframework.context.ApplicationContext -import org.springframework.context.ConfigurableApplicationContext -import kotlin.reflect.KClass - -/** - * Generic Bluepring Dependency Service, which will be used mainly in scripts. - * This will be initialised only once during the Application startup. - * Function modules, shall add their own dependency function names as an extension function. - * - * @author Brinda Santh - */ - -object BlueprintDependencyService { - - lateinit var applicationContext: ApplicationContext - - fun inject(applicationContext: ApplicationContext) { - BlueprintDependencyService.applicationContext = applicationContext - } - - /** Used to inject [instance] into spring application context for the [key], - * Use this method only for testing - * */ - fun registerSingleton(key: String, instance: Any) { - val configurableApplicationContext = applicationContext as ConfigurableApplicationContext - configurableApplicationContext.beanFactory.registerSingleton(key, instance) - } - - inline fun instance(name: String): T { - return applicationContext.getBean(name) as? T - ?: throw BlueprintProcessorException("failed to get instance($name)") - } - - inline fun instance(type: Class): T { - return applicationContext.getBean(type) - ?: throw BlueprintProcessorException("failed to get instance($type)") - } - - inline fun instance(type: KClass<*>): T { - return applicationContext.getBean(type.java) as? T - ?: throw BlueprintProcessorException("failed to get instance($type)") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionService.kt deleted file mode 100644 index ac90705a1..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionService.kt +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 - 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ArrayNode -import com.fasterxml.jackson.databind.node.ObjectNode -import com.fasterxml.jackson.databind.node.TextNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.DSLExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData -import org.onap.ccsdk.cds.controllerblueprints.core.data.InputExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression -import org.slf4j.LoggerFactory - -/** - * - * - * @author Brinda Santh - */ -object BlueprintExpressionService { - - val log = LoggerFactory.getLogger(this::class.toString()) - - @JvmStatic - fun checkContainsExpression(propertyAssignmentNode: JsonNode): Boolean { - val json = propertyAssignmentNode.toString() - // FIXME("Check if any Optimisation needed") - return ( - json.contains(BlueprintConstants.EXPRESSION_GET_INPUT) || - json.contains(BlueprintConstants.EXPRESSION_GET_ATTRIBUTE) || - json.contains(BlueprintConstants.EXPRESSION_GET_PROPERTY) - ) - } - - @JvmStatic - fun getExpressionData(propertyAssignmentNode: JsonNode): ExpressionData { - log.trace("Assignment Data/Expression : {}", propertyAssignmentNode) - val expressionData = ExpressionData(valueNode = propertyAssignmentNode) - if (propertyAssignmentNode is ObjectNode) { - val commands: Set = propertyAssignmentNode.fieldNames().asSequence().toList().intersect(BlueprintTypes.validCommands()) - if (commands.isNotEmpty()) { - expressionData.isExpression = true - expressionData.command = commands.first() - expressionData.expressionNode = propertyAssignmentNode - - when (expressionData.command) { - BlueprintConstants.EXPRESSION_GET_INPUT -> { - expressionData.inputExpression = populateInputExpression(propertyAssignmentNode) - } - BlueprintConstants.EXPRESSION_GET_ATTRIBUTE -> { - expressionData.attributeExpression = populateAttributeExpression(propertyAssignmentNode) - } - BlueprintConstants.EXPRESSION_GET_PROPERTY -> { - expressionData.propertyExpression = populatePropertyExpression(propertyAssignmentNode) - } - BlueprintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { - expressionData.operationOutputExpression = populateOperationOutputExpression(propertyAssignmentNode) - } - BlueprintConstants.EXPRESSION_GET_ARTIFACT -> { - expressionData.artifactExpression = populateArtifactExpression(propertyAssignmentNode) - } - } - } - } else if (propertyAssignmentNode is TextNode && - propertyAssignmentNode.textValue().startsWith(BlueprintConstants.EXPRESSION_DSL_REFERENCE) - ) { - expressionData.isExpression = true - expressionData.command = BlueprintConstants.EXPRESSION_DSL_REFERENCE - expressionData.dslExpression = populateDSLExpression(propertyAssignmentNode) - } - return expressionData - } - - @JvmStatic - fun populateDSLExpression(jsonNode: TextNode): DSLExpression { - return DSLExpression( - propertyName = jsonNode.textValue() - .removePrefix(BlueprintConstants.EXPRESSION_DSL_REFERENCE) - ) - } - - @JvmStatic - fun populateInputExpression(jsonNode: JsonNode): InputExpression { - return InputExpression(propertyName = jsonNode.first().textValue()) - } - - @JvmStatic - fun populatePropertyExpression(jsonNode: JsonNode): PropertyExpression { - val arrayNode: ArrayNode = jsonNode.first() as ArrayNode - check(arrayNode.size() >= 2) { - throw BlueprintException( - String.format( - "missing property expression, " + - "it should be [ , , , " + - ", ..., ] , but present {}", - jsonNode - ) - ) - } - var reqOrCapEntityName: String? = null - var propertyName = "" - var subProperty: String? = null - when { - arrayNode.size() == 2 -> propertyName = arrayNode[1].textValue() - arrayNode.size() == 3 -> { - reqOrCapEntityName = arrayNode[1].textValue() - propertyName = arrayNode[2].textValue() - } - arrayNode.size() > 3 -> { - reqOrCapEntityName = arrayNode[1].textValue() - propertyName = arrayNode[2].textValue() - val propertyPaths: List = arrayNode.filterIndexed { index, _ -> - index >= 3 - }.map { it.textValue() } - subProperty = propertyPaths.joinToString(".") - } - } - - return PropertyExpression( - modelableEntityName = arrayNode[0].asText(), - reqOrCapEntityName = reqOrCapEntityName, - propertyName = propertyName, - subPropertyName = subProperty - ) - } - - @JvmStatic - fun populateAttributeExpression(jsonNode: JsonNode): AttributeExpression { - val arrayNode: ArrayNode = jsonNode.first() as ArrayNode - check(arrayNode.size() >= 2) { - throw BlueprintException( - String.format( - "missing attribute expression, " + - "it should be [ , , ," + - " , ..., ] , but present {}", - jsonNode - ) - ) - } - - var reqOrCapEntityName: String? = null - var attributeName = "" - var subAttributeName: String? = null - when { - arrayNode.size() == 2 -> attributeName = arrayNode[1].textValue() - arrayNode.size() == 3 -> { - reqOrCapEntityName = arrayNode[1].textValue() - attributeName = arrayNode[2].textValue() - } - arrayNode.size() > 3 -> { - reqOrCapEntityName = arrayNode[1].textValue() - attributeName = arrayNode[2].textValue() - val propertyPaths: List = arrayNode.filterIndexed { index, _ -> - index >= 3 - }.map { it.textValue() } - subAttributeName = propertyPaths.joinToString(".") - } - } - return AttributeExpression( - modelableEntityName = arrayNode[0].asText(), - reqOrCapEntityName = reqOrCapEntityName, - attributeName = attributeName, - subAttributeName = subAttributeName - ) - } - - @JvmStatic - fun populateOperationOutputExpression(jsonNode: JsonNode): OperationOutputExpression { - val arrayNode: ArrayNode = jsonNode.first() as ArrayNode - - check(arrayNode.size() >= 4) { - throw BlueprintException( - String.format( - "missing operation output expression, " + - "it should be (, , , ) , but present {}", - jsonNode - ) - ) - } - - var subPropertyName: String? = null - if (arrayNode.size() == 5) - subPropertyName = arrayNode[4].asText() - - return OperationOutputExpression( - modelableEntityName = arrayNode[0].asText(), - interfaceName = arrayNode[1].asText(), - operationName = arrayNode[2].asText(), - propertyName = arrayNode[3].asText(), - subPropertyName = subPropertyName - ) - } - - @JvmStatic - fun populateArtifactExpression(jsonNode: JsonNode): ArtifactExpression { - val arrayNode: ArrayNode = jsonNode.first() as ArrayNode - - check(arrayNode.size() >= 2) { - throw BlueprintException( - String.format( - "missing artifact expression, " + - "it should be [ , , , ] , but present {}", - jsonNode - ) - ) - } - return ArtifactExpression( - modelableEntityName = arrayNode[0].asText(), - artifactName = arrayNode[1].asText(), - location = arrayNode[2]?.asText() ?: "LOCAL_FILE", - remove = arrayNode[3]?.asBoolean() ?: false - ) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintImportService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintImportService.kt deleted file mode 100644 index 6dbacd199..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintImportService.kt +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.utils.ServiceTemplateUtils -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import java.io.File -import java.net.URL -import java.net.URLDecoder -import java.nio.charset.Charset - -class BlueprintImportService(private val parentServiceTemplate: ServiceTemplate, private val blueprintBasePath: String) { - companion object { - - private const val PARENT_SERVICE_TEMPLATE: String = "parent" - } - - private val log: Logger = LoggerFactory.getLogger(this::class.toString()) - - private var importServiceTemplateMap: MutableMap = hashMapOf() - - suspend fun getImportResolvedServiceTemplate(): ServiceTemplate { - // Populate Imported Service Templates - traverseSchema(PARENT_SERVICE_TEMPLATE, parentServiceTemplate) - - importServiceTemplateMap.forEach { key, serviceTemplate -> - ServiceTemplateUtils.merge(parentServiceTemplate, serviceTemplate) - log.debug("merged service template $key") - } - return parentServiceTemplate - } - - private suspend fun traverseSchema(key: String, serviceTemplate: ServiceTemplate) { - if (key != PARENT_SERVICE_TEMPLATE) { - importServiceTemplateMap[key] = serviceTemplate - } - val imports: List? = serviceTemplate.imports - - imports?.let { - serviceTemplate.imports?.forEach { importDefinition -> - val childServiceTemplate = resolveImportDefinition(importDefinition) - val keyName: String = importDefinition.file - traverseSchema(keyName, childServiceTemplate) - } - } - } - - private suspend fun resolveImportDefinition(importDefinition: ImportDefinition): ServiceTemplate { - var serviceTemplate: ServiceTemplate? = null - val file: String = importDefinition.file - val decodedSystemId: String = URLDecoder.decode(file, Charset.defaultCharset().toString()) - log.trace("file ({}), decodedSystemId ({}) ", file, decodedSystemId) - try { - if (decodedSystemId.startsWith("http", true) || - decodedSystemId.startsWith("https", true) - ) { - val givenUrl: String = URL(decodedSystemId).toString() - val systemUrl: String = File(".").toURI().toURL().toString() - log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl) - if (givenUrl.startsWith(systemUrl)) { - } - } else { - if (!decodedSystemId.startsWith("/")) { - importDefinition.file = StringBuilder().append(blueprintBasePath).append(File.separator).append(file).toString() - } - serviceTemplate = ServiceTemplateUtils.getServiceTemplate(importDefinition.file) - } - } catch (e: Exception) { - throw BlueprintException("failed to populate service template for ${importDefinition.file} original error: ${e.message}", e) - } - if (serviceTemplate == null) { - throw BlueprintException("failed to populate service template for : ${importDefinition.file}") - } - return serviceTemplate - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintJinjaTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintJinjaTemplateService.kt deleted file mode 100644 index ac85cb3e8..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintJinjaTemplateService.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import com.hubspot.jinjava.Jinjava -import com.hubspot.jinjava.JinjavaConfig -import com.hubspot.jinjava.interpret.JinjavaInterpreter -import com.hubspot.jinjava.loader.ResourceLocator -import com.hubspot.jinjava.loader.ResourceNotFoundException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintJsonNodeFactory -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode -import java.io.IOException -import java.nio.charset.Charset -import java.nio.file.Files.readAllBytes -import java.nio.file.Paths - -object BlueprintJinjaTemplateService { - - /** - * To enable inheritance within CBA, we need Jinja runtime to know where to load the templates. - */ - class BlueprintRelatedTemplateLocator( - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val artifactName: String, - private val artifactVersion: String - ) : ResourceLocator { - - @Throws(IOException::class) - override fun getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter): String { - try { - val deployFile = - normalizedPathName( - bluePrintLoadConfiguration.blueprintDeployPath, - artifactName, - artifactVersion, - fullName - ) - - return String(readAllBytes(Paths.get(deployFile))) - } catch (var5: IllegalArgumentException) { - throw ResourceNotFoundException("Couldn't find resource: $fullName") - } - } - } - - fun generateContent( - template: String, - json: String, - ignoreJsonNull: Boolean, - additionalContext: MutableMap, - bluePrintLoadConfiguration: BlueprintLoadConfiguration, - artifactName: String, - artifactVersion: String - ): String { - - return generateContent( - template, - json, - ignoreJsonNull, - additionalContext, - BlueprintRelatedTemplateLocator(bluePrintLoadConfiguration, artifactName, artifactVersion) - ) - } - - fun generateContent( - template: String, - json: String, - ignoreJsonNull: Boolean, - additionalContext: MutableMap, - resourceLocator: ResourceLocator? = null - ): String { - val jinJava = Jinjava(JinjavaConfig()) - if (resourceLocator != null) { - jinJava.resourceLocator = resourceLocator - } - - val mapper = ObjectMapper() - val nodeFactory = BlueprintJsonNodeFactory() - mapper.nodeFactory = nodeFactory - - // Add the JSON Data to the context - if (json.isNotEmpty()) { - val jsonNode = mapper.readValue(json, JsonNode::class.java) - ?: throw BlueprintProcessorException("couldn't get json node from json") - if (ignoreJsonNull) { - jsonNode.removeNullNode() - } - - val jsonMap: Map = mapper.readValue(json, object : TypeReference>() {}) - additionalContext.putAll(jsonMap) - } - - return jinJava.render(template, additionalContext) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileService.kt deleted file mode 100644 index dd07bade2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileService.kt +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory - -open class BlueprintRepoFileService(modelTypePath: String) : BlueprintRepoService { - - private val log = LoggerFactory.getLogger(BlueprintRepoFileService::class.toString()) - - private val dataTypePath = modelTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) - private val nodeTypePath = modelTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE) - private val artifactTypePath = modelTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE) - private val capabilityTypePath = - modelTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(BlueprintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE) - private val relationshipTypePath = - modelTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE) - private val extension = ".json" - - override fun getDataType(dataTypeName: String): DataType { - val fileName = dataTypePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(dataTypeName).plus(extension) - return getModelType(fileName, DataType::class.java) - } - - override fun getNodeType(nodeTypeName: String): NodeType { - val fileName = nodeTypePath.plus(BlueprintConstants.PATH_DIVIDER).plus(nodeTypeName).plus(extension) - return getModelType(fileName, NodeType::class.java) - } - - override fun getArtifactType(artifactTypeName: String): ArtifactType { - val fileName = artifactTypePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(artifactTypeName).plus(extension) - return getModelType(fileName, ArtifactType::class.java) - } - - override fun getRelationshipType(relationshipTypeName: String): RelationshipType { - val fileName = relationshipTypePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(relationshipTypeName).plus(extension) - return getModelType(fileName, RelationshipType::class.java) - } - - override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { - val fileName = capabilityTypePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(capabilityDefinitionName).plus(extension) - return getModelType(fileName, CapabilityDefinition::class.java) - } - - private fun getModelType(fileName: String, valueType: Class): T { - return JacksonUtils.readValueFromFile(fileName, valueType) - ?: throw BlueprintException("couldn't get file($fileName) for type(${valueType.name}") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeService.kt deleted file mode 100644 index c05b94260..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeService.kt +++ /dev/null @@ -1,799 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018-2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.NullNode -import com.fasterxml.jackson.databind.node.ObjectNode -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants.LOG_REDACTED -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.rootFieldsToMap -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect -import org.slf4j.LoggerFactory -import java.io.File - -interface BlueprintRuntimeService { - - fun id(): String - - fun bluePrintContext(): BlueprintContext - - fun getExecutionContext(): T - - fun setExecutionContext(executionContext: T) - - fun put(key: String, value: JsonNode) - - fun get(key: String): JsonNode? - - fun check(key: String): Boolean - - fun cleanRuntime() - - fun getAsString(key: String): String? - - fun getAsBoolean(key: String): Boolean? - - fun getAsInt(key: String): Int? - - fun getAsDouble(key: String): Double? - - fun getBlueprintError(): BlueprintError - - fun setBlueprintError(bluePrintError: BlueprintError) - - fun loadEnvironments(type: String, fileName: String) - - fun resolveWorkflowOutputs(workflowName: String): MutableMap - - fun resolveDSLExpression(dslPropertyName: String): JsonNode - - /** Resolve Property Definition [definitionName] for type [definitionType] with [propertyDefinitions] - * Definition Type may be : node_template, relationship_template, dsl, workflow - * Assumption is Definition holds the expressions or value assigned in it. Mainly used for workflow outputs. - */ - fun resolvePropertyDefinitions( - definitionType: String, - definitionName: String, - propertyDefinitions: MutableMap - ): MutableMap - - /** Resolve Property Assignments [definitionName] for type [definitionType] with [propertyDefinitions] - * and [propertyAssignments] - * Definition Type may be : node_template, relationship_template, dsl, workflow - */ - fun resolvePropertyAssignments( - definitionType: String, - definitionName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap - - /** Resolve Property Assignments [definitionName] for type [definitionType] with [propertyAssignments] - * Definition Type may be : node_template, relationship_template, dsl, workflow - */ - fun resolvePropertyAssignments( - definitionType: String, - definitionName: String, - propertyAssignments: MutableMap - ): MutableMap - - /** Resolve Node Template [nodeTemplateName] Property Assignments */ - fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap - - /** Resolve Node Template [nodeTemplateName] Property Assignments with [propertyDefinitions] and [propertyAssignments]*/ - fun resolveNodeTemplatePropertyAssignments( - nodeTemplateName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap - - fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): MutableMap - - fun resolveNodeTemplateInterfaceOperationInputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap - - fun resolveNodeTemplateInterfaceOperationOutputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap - - suspend fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String - - fun resolveNodeTemplateArtifactDefinition(nodeTemplateName: String, artifactName: String): ArtifactDefinition - - /** Resolve Node Template [relationshipTemplateName] Property Assignments */ - fun resolveRelationshipTemplateProperties(relationshipTemplateName: String): MutableMap - - /** Resolve Relationship Template [relationshipTemplateName] Property Assignments with - * [propertyDefinitions] and [propertyAssignments] */ - fun resolveRelationshipTemplatePropertyAssignments( - relationshipTemplateName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap - - fun setInputValue(propertyName: String, value: JsonNode) - - fun setWorkflowInputValue( - workflowName: String, - propertyName: String, - propertyDefinition: PropertyDefinition, - value: JsonNode - ) - - fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) - - fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) - - fun setNodeTemplateOperationPropertyValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) - - fun setNodeTemplateOperationInputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) - - fun setNodeTemplateOperationOutputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) - - fun getInputValue(propertyName: String): JsonNode - - fun getNodeTemplateOperationOutputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String - ): JsonNode - - fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode? - - fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode? - - fun getRelationshipTemplatePropertyValue(relationshipTemplateName: String, propertyName: String): JsonNode? - - fun getRelationshipTemplateAttributeValue(relationshipTemplateName: String, attributeName: String): JsonNode? - - fun assignInputs(jsonNode: JsonNode) - - fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) - - fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List): JsonNode - - suspend fun close() -} - -/** - * - * - * @author Brinda Santh - */ -open class DefaultBlueprintRuntimeService(private var id: String, private var bluePrintContext: BlueprintContext) : - BlueprintRuntimeService> { - - @Transient - private val log = LoggerFactory.getLogger(BlueprintRuntimeService::class.toString()) - - private var store: MutableMap = hashMapOf() - - private var bluePrintError = BlueprintError() - - init { - /** - * Load Blueprint Environments Properties - */ - val absoluteEnvFilePath = bluePrintContext.rootPath.plus(File.separator) - .plus(BlueprintConstants.TOSCA_ENVIRONMENTS_DIR) - loadEnvironments(BlueprintConstants.PROPERTY_BPP, absoluteEnvFilePath) - } - - override fun id(): String { - return id - } - - override fun bluePrintContext(): BlueprintContext { - return bluePrintContext - } - - override fun getExecutionContext(): MutableMap { - return store - } - - @Suppress("UNCHECKED_CAST") - override fun setExecutionContext(executionContext: MutableMap) { - this.store = executionContext - } - - override fun put(key: String, value: JsonNode) { - store[key] = value - } - - override fun get(key: String): JsonNode { - return store[key] ?: throw BlueprintProcessorException("failed to get execution property($key)") - } - - override fun check(key: String): Boolean { - return store.containsKey(key) - } - - override fun cleanRuntime() { - store.clear() - } - - private fun getJsonNode(key: String): JsonNode { - return get(key) - } - - override fun getAsString(key: String): String? { - return get(key).asText() - } - - override fun getAsBoolean(key: String): Boolean? { - return get(key).asBoolean() - } - - override fun getAsInt(key: String): Int? { - return get(key).asInt() - } - - override fun getAsDouble(key: String): Double? { - return get(key).asDouble() - } - - override fun getBlueprintError(): BlueprintError { - return this.bluePrintError - } - - override fun setBlueprintError(bluePrintError: BlueprintError) { - this.bluePrintError = bluePrintError - } - - override fun loadEnvironments(type: String, fileName: String) { - BlueprintMetadataUtils.environmentFileProperties(fileName).forEach { key, value -> - setNodeTemplateAttributeValue(type, key.toString(), value.asJsonType()) - } - } - - override fun resolveWorkflowOutputs(workflowName: String): MutableMap { - log.info("resolveWorkflowOutputs for workflow($workflowName)") - val outputs = bluePrintContext.workflowByName(workflowName).outputs ?: mutableMapOf() - return resolvePropertyDefinitions(BlueprintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, "WORKFLOW", outputs) - } - - /** - * Read the DSL Property reference, If there is any expression, then resolve those expression and return as Json - * Type - */ - override fun resolveDSLExpression(dslPropertyName: String): JsonNode { - val propertyAssignments = bluePrintContext.dslPropertiesByName(dslPropertyName) - return if (BlueprintExpressionService.checkContainsExpression(propertyAssignments) && - propertyAssignments is ObjectNode - ) { - val rootKeyMap = propertyAssignments.rootFieldsToMap() - val propertyAssignmentValue: MutableMap = hashMapOf() - rootKeyMap.forEach { (propertyName, propertyValue) -> - val propertyAssignmentExpression = PropertyAssignmentService(this) - propertyAssignmentValue[propertyName] = propertyAssignmentExpression - .resolveAssignmentExpression( - BlueprintConstants.MODEL_DEFINITION_TYPE_DSL, - "DSL", - propertyName, - propertyValue - ) - } - propertyAssignmentValue.asJsonNode() - } else { - propertyAssignments - } - } - - override fun resolvePropertyDefinitions( - definitionType: String, - definitionName: String, - propertyDefinitions: MutableMap - ): MutableMap { - val propertyAssignmentValue: MutableMap = hashMapOf() - - propertyDefinitions.forEach { (propertyName, propertyDefinition) -> - val propertyAssignmentExpression = PropertyAssignmentService(this) - val expression = propertyDefinition.value ?: propertyDefinition.defaultValue - if (expression != null) { - propertyAssignmentValue[propertyName] = - propertyAssignmentExpression.resolveAssignmentExpression( - definitionType, - definitionName, - propertyName, - expression - ) - } - } - return propertyAssignmentValue - } - - override fun resolvePropertyAssignments( - definitionType: String, - definitionName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap { - - val propertyAssignmentValue: MutableMap = hashMapOf() - - propertyDefinitions.forEach { (nodeTypePropertyName, nodeTypeProperty) -> - // Get the Express or Value for the Node Template - val propertyAssignment: JsonNode? = propertyAssignments[nodeTypePropertyName] - - var resolvedValue: JsonNode = NullNode.getInstance() - if (propertyAssignment != null) { - // Resolve the Expressing - val propertyAssignmentExpression = PropertyAssignmentService(this) - resolvedValue = propertyAssignmentExpression.resolveAssignmentExpression( - definitionType, definitionName, nodeTypePropertyName, propertyAssignment - ) - } - - // Set default value if null - if (resolvedValue is NullNode) { - nodeTypeProperty.defaultValue?.let { resolvedValue = nodeTypeProperty.defaultValue!! } - } - - /** If property is Map type, then resolve the property value, It may have expressions */ - if (nodeTypeProperty.type == BlueprintConstants.DATA_TYPE_MAP && - resolvedValue.returnNullIfMissing() != null - ) { - val mapResolvedValue = resolvePropertyAssignments( - definitionType, definitionName, resolvedValue.rootFieldsToMap() - ) - resolvedValue = mapResolvedValue.asJsonNode() - } - - // Set for Return of method - propertyAssignmentValue[nodeTypePropertyName] = resolvedValue - } - return propertyAssignmentValue - } - - override fun resolvePropertyAssignments( - definitionType: String, - definitionName: String, - propertyAssignments: MutableMap - ): MutableMap { - val propertyAssignmentValue: MutableMap = hashMapOf() - - propertyAssignments.forEach { (propertyName, propertyExpression) -> - val propertyAssignmentExpression = PropertyAssignmentService(this) - propertyAssignmentValue[propertyName] = - propertyAssignmentExpression.resolveAssignmentExpression( - definitionType, definitionName, propertyName, propertyExpression - ) - } - return propertyAssignmentValue - } - - override fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap { - log.info("resolveNodeTemplatePropertyValues for node template ({})", nodeTemplateName) - - val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) - - val propertyAssignments: MutableMap = nodeTemplate.properties!! - - // Get the Node Type Definitions - val nodeTypePropertiesDefinitions: MutableMap = bluePrintContext - .nodeTypeChainedProperties(nodeTemplate.type)!! - - /** - * Resolve the NodeTemplate Property Assignment Values. - */ - return resolveNodeTemplatePropertyAssignments( - nodeTemplateName, - nodeTypePropertiesDefinitions, - propertyAssignments - ) - } - - /** - * Resolve any property assignments for the node - */ - override fun resolveNodeTemplatePropertyAssignments( - nodeTemplateName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap { - return resolvePropertyAssignments( - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, - nodeTemplateName, propertyDefinitions, propertyAssignments - ) - } - - override fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): - MutableMap { - log.info("resolveNodeTemplateCapabilityProperties for node template($nodeTemplateName) capability($capabilityName)") - val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) - - val propertyAssignments = nodeTemplate.capabilities?.get(capabilityName)?.properties ?: hashMapOf() - - val propertyDefinitions = bluePrintContext.nodeTemplateNodeType(nodeTemplateName) - .capabilities?.get(capabilityName)?.properties ?: hashMapOf() - - /** - * Resolve the Capability Property Assignment Values. - */ - return resolveNodeTemplatePropertyAssignments(nodeTemplateName, propertyDefinitions, propertyAssignments) - } - - override fun resolveNodeTemplateInterfaceOperationInputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap { - log.info( - "resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " + - "interface name($interfaceName), operationName($operationName)" - ) - - val propertyAssignments: MutableMap = - bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) - ?: hashMapOf() - - val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type - - val nodeTypeInterfaceOperationInputs: MutableMap = - bluePrintContext.nodeTypeInterfaceOperationInputs(nodeTypeName, interfaceName, operationName) - ?: hashMapOf() - - log.info("input definition for node template ($nodeTemplateName), values ($propertyAssignments)") - - /** - * Resolve the Property Input Assignment Values. - */ - return resolveNodeTemplatePropertyAssignments( - nodeTemplateName, - nodeTypeInterfaceOperationInputs, - propertyAssignments - ) - } - - override fun resolveNodeTemplateInterfaceOperationOutputs( - nodeTemplateName: String, - interfaceName: String, - operationName: String - ): MutableMap { - log.info( - "resolveNodeTemplateInterfaceOperationOutputs for node template ($nodeTemplateName),interface name " + - "($interfaceName), operationName($operationName)" - ) - - val propertyAssignments: MutableMap = - bluePrintContext.nodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName) - ?: hashMapOf() - - val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type - - val nodeTypeInterfaceOperationOutputs: MutableMap = - bluePrintContext.nodeTypeInterfaceOperationOutputs(nodeTypeName, interfaceName, operationName) - ?: hashMapOf() - - /** - * Resolve the Property Output Assignment Values. - */ - val propertyAssignmentValue = - resolveNodeTemplatePropertyAssignments( - nodeTemplateName, - nodeTypeInterfaceOperationOutputs, - propertyAssignments - ) - - // Store operation output values into context - propertyAssignmentValue.forEach { (key, value) -> - setNodeTemplateOperationOutputValue(nodeTemplateName, interfaceName, operationName, key, value) - } - return propertyAssignmentValue - } - - override suspend fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String { - val artifactDefinition: ArtifactDefinition = - resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) - val propertyAssignmentExpression = PropertyAssignmentService(this) - return propertyAssignmentExpression.artifactContent(artifactDefinition) - } - - override fun resolveNodeTemplateArtifactDefinition( - nodeTemplateName: String, - artifactName: String - ): ArtifactDefinition { - val nodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) - - return nodeTemplate.artifacts?.get(artifactName) - ?: throw BlueprintProcessorException( - "failed to get artifact definition($artifactName) from the node template" - ) - } - - override fun resolveRelationshipTemplateProperties(relationshipTemplateName: String): MutableMap { - log.info("resolveRelationshipTemplateProperties for relationship template ({})", relationshipTemplateName) - - val relationshipTemplate = bluePrintContext.relationshipTemplateByName(relationshipTemplateName) - - val propertyAssignments = relationshipTemplate.properties!! - - // Get the Relationship Type Definitions - val propertiesDefinitions = bluePrintContext.relationshipTypeByName(relationshipTemplate.type).properties - ?: throw BlueprintProcessorException("failed to get ${relationshipTemplate.type} properties.") - - /** - * Resolve the RelationshipTemplate Property Assignment Values. - */ - return resolveRelationshipTemplatePropertyAssignments( - relationshipTemplateName, - propertiesDefinitions, - propertyAssignments - ) - } - - override fun resolveRelationshipTemplatePropertyAssignments( - relationshipTemplateName: String, - propertyDefinitions: MutableMap, - propertyAssignments: MutableMap - ): MutableMap { - return resolvePropertyAssignments( - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE, - relationshipTemplateName, propertyDefinitions, propertyAssignments - ) - } - - override fun setInputValue(propertyName: String, value: JsonNode) { - val path = """${BlueprintConstants.PATH_INPUTS}${BlueprintConstants.PATH_DIVIDER}$propertyName""" - put(path, value) - } - - override fun setWorkflowInputValue( - workflowName: String, - propertyName: String, - propertyDefinition: PropertyDefinition, - value: JsonNode - ) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_WORKFLOWS) - .append(BlueprintConstants.PATH_DIVIDER).append(workflowName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - put(path, value) - } - - override fun setNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String, value: JsonNode) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - put(path, value) - } - - override fun setNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String, value: JsonNode) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_ATTRIBUTES) - .append(BlueprintConstants.PATH_DIVIDER).append(attributeName).toString() - put(path, value) - } - - override fun setNodeTemplateOperationPropertyValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INTERFACES) - .append(BlueprintConstants.PATH_DIVIDER).append(interfaceName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OPERATIONS) - .append(BlueprintConstants.PATH_DIVIDER).append(operationName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - log.trace("setting operation property path ({}), values ({})", path, value) - put(path, value) - } - - override fun setNodeTemplateOperationInputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INTERFACES) - .append(BlueprintConstants.PATH_DIVIDER).append(interfaceName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OPERATIONS) - .append(BlueprintConstants.PATH_DIVIDER).append(operationName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - put(path, value) - } - - override fun setNodeTemplateOperationOutputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String, - value: JsonNode - ) { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INTERFACES) - .append(BlueprintConstants.PATH_DIVIDER).append(interfaceName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OPERATIONS) - .append(BlueprintConstants.PATH_DIVIDER).append(operationName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OUTPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - put(path, value) - } - - override fun getInputValue(propertyName: String): JsonNode { - val path = StringBuilder(BlueprintConstants.PATH_INPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - return getJsonNode(path) - } - - override fun getNodeTemplateOperationOutputValue( - nodeTemplateName: String, - interfaceName: String, - operationName: String, - propertyName: String - ): JsonNode { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_INTERFACES) - .append(BlueprintConstants.PATH_DIVIDER).append(interfaceName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OPERATIONS) - .append(BlueprintConstants.PATH_DIVIDER).append(operationName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_OUTPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - return getJsonNode(path) - } - - override fun getNodeTemplatePropertyValue(nodeTemplateName: String, propertyName: String): JsonNode { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - return getJsonNode(path) - } - - override fun getNodeTemplateAttributeValue(nodeTemplateName: String, attributeName: String): JsonNode { - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_ATTRIBUTES) - .append(BlueprintConstants.PATH_DIVIDER).append(attributeName).toString() - return getJsonNode(path) - } - - override fun getRelationshipTemplatePropertyValue( - relationshipTemplateName: String, - propertyName: String - ): JsonNode? { - val path: String = StringBuilder(BlueprintConstants.PATH_RELATIONSHIP_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(relationshipTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_PROPERTIES) - .append(BlueprintConstants.PATH_DIVIDER).append(propertyName).toString() - return getJsonNode(path) - } - - override fun getRelationshipTemplateAttributeValue( - relationshipTemplateName: String, - attributeName: String - ): JsonNode? { - val path: String = StringBuilder(BlueprintConstants.PATH_RELATIONSHIP_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(relationshipTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_ATTRIBUTES) - .append(BlueprintConstants.PATH_DIVIDER).append(attributeName).toString() - return getJsonNode(path) - } - - override fun assignInputs(jsonNode: JsonNode) { - log.info("assignInputs from input JSON ({})", jsonNode.toString()) - bluePrintContext.inputs()?.forEach { propertyName, property -> - val valueNode: JsonNode = jsonNode.at(BlueprintConstants.PATH_DIVIDER + propertyName) - ?: property.defaultValue - ?: NullNode.getInstance() - setInputValue(propertyName, valueNode) - } - } - - override fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode) { - log.info("Deriving input data for workflow: ($workflowName)") - - val dynamicInputPropertiesName = "$workflowName-properties" - - bluePrintContext.workflowByName(workflowName).inputs - ?.filter { (propertyName, property) -> propertyName != dynamicInputPropertiesName } - ?.forEach { propertyName, property -> findAndSetInputValue(propertyName, property, jsonNode) } - // Load Dynamic data Types - jsonNode.get(dynamicInputPropertiesName)?.let { - bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName") - ?.properties - ?.forEach { propertyName, property -> findAndSetInputValue(propertyName, property, it) } - } - } - - private fun findAndSetInputValue(propertyName: String, property: PropertyDefinition, jsonNode: JsonNode) { - val valueNode = jsonNode.at(BlueprintConstants.PATH_DIVIDER + propertyName) - .returnNullIfMissing() - ?: property.defaultValue - ?: NullNode.getInstance() - val loggableValue = if (hasLogProtect(property)) LOG_REDACTED else valueNode.toString() - log.trace("Setting input data - attribute:($propertyName) value:($loggableValue)") - setInputValue(propertyName, valueNode) - } - - override fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List): JsonNode { - - val jsonNode: ObjectNode = jacksonObjectMapper().createObjectNode() - val path: String = StringBuilder(BlueprintConstants.PATH_NODE_TEMPLATES) - .append(BlueprintConstants.PATH_DIVIDER).append(nodeTemplateName) - .append(BlueprintConstants.PATH_DIVIDER).append(BlueprintConstants.PATH_ATTRIBUTES) - .append(BlueprintConstants.PATH_DIVIDER).toString() - store.keys.filter { - it.startsWith(path) - }.map { - val key = it.replace(path, "") - if (keys.contains(key)) { - val value = store[it] as JsonNode - jsonNode.set(key, value) - } - } - return jsonNode - } - - override suspend fun close() { - store.clear() - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt deleted file mode 100644 index d953bd54f..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateService.kt +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTemplateService -import org.springframework.stereotype.Service - -@Service -class BlueprintTemplateService(private val bluePrintLoadConfiguration: BlueprintLoadConfiguration) : - BlueprintTemplateService { - - override suspend fun generateContent( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - nodeTemplateName: String, - artifactName: String, - jsonData: String, - ignoreJsonNull: Boolean, - additionalContext: MutableMap - ): String { - - val artifactDefinition = - bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) - val templateType = artifactDefinition.type - val template = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - - return when (templateType) { - BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA -> { - BlueprintJinjaTemplateService.generateContent( - template, - jsonData, - ignoreJsonNull, - additionalContext, - bluePrintLoadConfiguration, - bluePrintRuntimeService.bluePrintContext().name(), - bluePrintRuntimeService.bluePrintContext().version() - ) - } - BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY -> { - BlueprintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext) - } - else -> { - throw BlueprintProcessorException( - "Unknown Artifact type, expecting ${BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_JINJA}" + - "or ${BlueprintConstants.MODEL_TYPE_ARTIFACT_TEMPLATE_VELOCITY}" - ) - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintValidatorService.kt deleted file mode 100644 index 888c5c0c6..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintValidatorService.kt +++ /dev/null @@ -1,711 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.google.common.base.Preconditions -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.format -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import java.io.Serializable - -/** - * - * - * @author Brinda Santh - */ -interface BlueprintValidatorService : Serializable { - - @Throws(BlueprintException::class) - fun validateBlueprint(bluePrintContext: BlueprintContext, properties: MutableMap) - - @Throws(BlueprintException::class) - fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap) -} - -@Deprecated("Decomposed implementation moved to blueprint-validation module") -open class BlueprintValidatorDefaultService : BlueprintValidatorService { - - val log = LoggerFactory.getLogger(BlueprintValidatorDefaultService::class.toString()) - - lateinit var bluePrintContext: BlueprintContext - lateinit var serviceTemplate: ServiceTemplate - lateinit var properties: MutableMap - var message: StringBuilder = StringBuilder() - private val separator: String = BlueprintConstants.PATH_DIVIDER - var paths: MutableList = arrayListOf() - - @Throws(BlueprintException::class) - override fun validateBlueprint(bluePrintContext: BlueprintContext, properties: MutableMap) { - validateBlueprint(bluePrintContext.serviceTemplate, properties) - } - - @Throws(BlueprintException::class) - override fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap) { - this.bluePrintContext = BlueprintContext(serviceTemplate) - this.serviceTemplate = serviceTemplate - this.properties = properties - try { - message.appendln("-> Config Blueprint") - serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) } - serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) } - serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) } - serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) } - serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) } - } catch (e: Exception) { - log.error("validation failed in the path : {}", paths.joinToString(separator), e) - log.error("validation trace message :{} ", message) - throw BlueprintException( - e, - format("failed to validate blueprint on path ({}) with message {}", paths.joinToString(separator), e.message) - ) - } - } - - @Throws(BlueprintException::class) - open fun validateMetadata(metaDataMap: MutableMap) { - paths.add("metadata") - - val templateName = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_NAME] - val templateVersion = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_VERSION] - val templateTags = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_TAGS] - val templateAuthor = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_AUTHOR] - - Preconditions.checkArgument(StringUtils.isNotBlank(templateName), "failed to get template name metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateVersion), "failed to get template version metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateTags), "failed to get template tags metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateAuthor), "failed to get template author metadata") - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateArtifactTypes(artifactTypes: MutableMap) { - paths.add("artifact_types") - artifactTypes.forEach { artifactName, artifactType -> - paths.add(artifactName) - message.appendln("--> Artifact Type :" + paths.joinToString(separator)) - artifactType.properties?.let { validatePropertyDefinitions(artifactType.properties!!) } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateDataTypes(dataTypes: MutableMap) { - paths.add("dataTypes") - dataTypes.forEach { dataTypeName, dataType -> - paths.add(dataTypeName) - message.appendln("--> DataType :" + paths.joinToString(separator)) - dataType.properties?.let { validatePropertyDefinitions(dataType.properties!!) } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateNodeTypes(nodeTypes: MutableMap) { - paths.add("nodeTypes") - nodeTypes.forEach { nodeTypeName, nodeType -> - // Validate Single Node Type - validateNodeType(nodeTypeName, nodeType) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateNodeType(nodeTypeName: String, nodeType: NodeType) { - paths.add(nodeTypeName) - message.appendln("--> Node Type :" + paths.joinToString(separator)) - val derivedFrom: String = nodeType.derivedFrom - // Check Derived From - checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom) - - if (!BlueprintTypes.rootNodeTypes().contains(derivedFrom)) { - serviceTemplate.nodeTypes?.get(derivedFrom) - ?: throw BlueprintException( - format( - "Failed to get derivedFrom NodeType({})'s for NodeType({}) ", - derivedFrom, nodeTypeName - ) - ) - } - - nodeType.properties?.let { validatePropertyDefinitions(nodeType.properties!!) } - nodeType.capabilities?.let { validateCapabilityDefinitions(nodeTypeName, nodeType) } - nodeType.requirements?.let { validateRequirementDefinitions(nodeTypeName, nodeType) } - nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun checkValidNodeTypesDerivedFrom(nodeTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validNodeTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException(format("Failed to get node type ({})'s derivedFrom({}) definition ", nodeTypeName, derivedFrom)) - } - } - - @Throws(BlueprintException::class) - open fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) { - paths.add("topology") - message.appendln("--> Topology Template") - topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) } - topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) } - topologyTemplate.workflows?.let { validateWorkFlows(topologyTemplate.workflows!!) } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateInputs(inputs: MutableMap) { - paths.add("inputs") - message.appendln("---> Input :" + paths.joinToString(separator)) - validatePropertyDefinitions(inputs) - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateNodeTemplates(nodeTemplates: MutableMap) { - paths.add("nodeTemplates") - nodeTemplates.forEach { nodeTemplateName, nodeTemplate -> - validateNodeTemplate(nodeTemplateName, nodeTemplate) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateNodeTemplate(nodeTemplateName: String, nodeTemplate: NodeTemplate) { - paths.add(nodeTemplateName) - message.appendln("---> NodeTemplate :" + paths.joinToString(separator)) - val type: String = nodeTemplate.type - - val nodeType: NodeType = serviceTemplate.nodeTypes?.get(type) - ?: throw BlueprintException(format("Failed to get NodeType({}) definition for NodeTemplate({})", type, nodeTemplateName)) - - nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) } - nodeTemplate.properties?.let { validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) } - nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, nodeTemplateName, nodeTemplate) } - nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, nodeTemplateName, nodeTemplate) } - nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeType, nodeTemplateName, nodeTemplate) } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateArtifactDefinitions(artifacts: MutableMap) { - paths.add("artifacts") - artifacts.forEach { artifactDefinitionName, artifactDefinition -> - paths.add(artifactDefinitionName) - message.appendln("Validating artifact " + paths.joinToString(separator)) - val type: String = artifactDefinition.type - ?: throw BlueprintException(format("type is missing for ArtifactDefinition({})", artifactDefinitionName)) - // Check Artifact Type - checkValidArtifactType(artifactDefinitionName, type) - - val file: String = artifactDefinition.file - ?: throw BlueprintException(format("file is missing for ArtifactDefinition({})", artifactDefinitionName)) - - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateWorkFlows(workflows: MutableMap) { - paths.add("workflows") - workflows.forEach { workflowName, workflow -> - - // Validate Single workflow - validateWorkFlow(workflowName, workflow) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateWorkFlow(workflowName: String, workflow: Workflow) { - paths.add(workflowName) - message.appendln("---> Workflow :" + paths.joinToString(separator)) - // Step Validation Start - paths.add("steps") - workflow.steps?.forEach { stepName, _ -> - paths.add(stepName) - message.appendln("----> Steps :" + paths.joinToString(separator)) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - // Step Validation Ends - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validatePropertyDefinitions(properties: MutableMap) { - paths.add("properties") - properties.forEach { propertyName, propertyDefinition -> - paths.add(propertyName) - val dataType: String = propertyDefinition.type - when { - BlueprintTypes.validPrimitiveTypes().contains(dataType) -> { - // Do Nothing - } - BlueprintTypes.validCollectionTypes().contains(dataType) -> { - val entrySchemaType: String = propertyDefinition.entrySchema?.type - ?: throw BlueprintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, propertyName)) - checkPrimitiveOrComplex(entrySchemaType, propertyName) - } - else -> checkPropertyDataType(dataType, propertyName) - } - message.appendln("property " + paths.joinToString(separator) + " of type " + dataType) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validatePropertyAssignments( - nodeTypeProperties: MutableMap, - properties: MutableMap - ) { - properties.forEach { propertyName, propertyAssignment -> - val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName] - ?: throw BlueprintException(format("failed to get definition for the property ({})", propertyName)) - - validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) - } - } - - @Throws(BlueprintException::class) - open fun validatePropertyAssignment( - propertyName: String, - propertyDefinition: PropertyDefinition, - propertyAssignment: JsonNode - ) { - // Check and Validate if Expression Node - val expressionData = BlueprintExpressionService.getExpressionData(propertyAssignment) - if (!expressionData.isExpression) { - checkPropertyValue(propertyName, propertyDefinition, propertyAssignment) - } - } - - @Throws(BlueprintException::class) - open fun validateCapabilityAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - val capabilities = nodeTemplate.capabilities - paths.add("capabilities") - capabilities?.forEach { capabilityName, capabilityAssignment -> - paths.add(capabilityName) - - val capabilityDefinition = nodeType.capabilities?.get(capabilityName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) capability definition ({}) " + - "from NodeType({}) ", - nodeTemplateName, capabilityName, nodeTemplate.type - ) - ) - - validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment) - - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateCapabilityAssignment( - nodeTemplateName: String, - capabilityName: String, - capabilityDefinition: CapabilityDefinition, - capabilityAssignment: CapabilityAssignment - ) { - - capabilityAssignment.properties?.let { validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) } - } - - @Throws(BlueprintException::class) - open fun validateRequirementAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - val requirements = nodeTemplate.requirements - paths.add("requirements") - requirements?.forEach { requirementName, requirementAssignment -> - paths.add(requirementName) - val requirementDefinition = nodeType.requirements?.get(requirementName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) requirement definition ({}) from" + - " NodeType({}) ", - nodeTemplateName, requirementName, nodeTemplate.type - ) - ) - // Validate Requirement Assignment - validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateRequirementAssignment( - nodeTemplateName: String, - requirementAssignmentName: String, - requirementDefinition: RequirementDefinition, - requirementAssignment: RequirementAssignment - ) { - log.info("Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, requirementAssignmentName) - val requirementNodeTemplateName = requirementAssignment.node!! - val capabilityName = requirementAssignment.capability - val relationship = requirementAssignment.relationship!! - - check(BlueprintTypes.validRelationShipDerivedFroms.contains(relationship)) { - throw BlueprintException( - format( - "Failed to get relationship type ({}) for NodeTemplate({})'s requirement({}) ", - relationship, nodeTemplateName, requirementAssignmentName - ) - ) - } - - val relationShipNodeTemplate = serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName) - ?: throw BlueprintException( - format( - "Failed to get requirement NodeTemplate({})'s for NodeTemplate({}) requirement({}) ", - requirementNodeTemplateName, nodeTemplateName, requirementAssignmentName - ) - ) - - relationShipNodeTemplate.capabilities?.get(capabilityName) - ?: throw BlueprintException( - format( - "Failed to get requirement NodeTemplate({})'s capability({}) for NodeTemplate ({})'s requirement({}) ", - requirementNodeTemplateName, capabilityName, nodeTemplateName, requirementAssignmentName - ) - ) - } - - @Throws(BlueprintException::class) - open fun validateInterfaceAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - - val interfaces = nodeTemplate.interfaces - paths.add("interfaces") - interfaces?.forEach { interfaceAssignmentName, interfaceAssignment -> - paths.add(interfaceAssignmentName) - val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) interface definition ({}) from" + - " NodeType({}) ", - nodeTemplateName, interfaceAssignmentName, nodeTemplate.type - ) - ) - - validateInterfaceAssignment( - nodeTemplateName, interfaceAssignmentName, interfaceDefinition, - interfaceAssignment - ) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateInterfaceAssignment( - nodeTemplateName: String, - interfaceAssignmentName: String, - interfaceDefinition: InterfaceDefinition, - interfaceAssignment: InterfaceAssignment - ) { - - val operations = interfaceAssignment.operations - operations?.let { - validateInterfaceOperationsAssignment( - nodeTemplateName, interfaceAssignmentName, interfaceDefinition, - interfaceAssignment - ) - } - } - - @Throws(BlueprintException::class) - open fun validateInterfaceOperationsAssignment( - nodeTemplateName: String, - interfaceAssignmentName: String, - interfaceDefinition: InterfaceDefinition, - interfaceAssignment: InterfaceAssignment - ) { - - val operations = interfaceAssignment.operations - operations?.let { - it.forEach { operationAssignmentName, operationAssignments -> - - val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) operation definition ({}) ", - nodeTemplateName, operationAssignmentName - ) - ) - - log.info( - "Validation NodeTemplate({}) Interface({}) Operation ({})", nodeTemplateName, - interfaceAssignmentName, operationAssignmentName - ) - - val inputs = operationAssignments.inputs - val outputs = operationAssignments.outputs - - inputs?.forEach { propertyName, propertyAssignment -> - val propertyDefinition = operationDefinition.inputs?.get(propertyName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) operation definition ({}) " + - "property definition({})", - nodeTemplateName, operationAssignmentName, propertyName - ) - ) - // Check the property values with property definition - validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) - } - - outputs?.forEach { propertyName, propertyAssignment -> - val propertyDefinition = operationDefinition.outputs?.get(propertyName) - ?: throw BlueprintException( - format( - "Failed to get NodeTemplate({}) operation definition ({}) " + - "output property definition({})", - nodeTemplateName, operationAssignmentName, - propertyName - ) - ) - // Check the property values with property definition - validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) - } - } - } - } - - @Throws(BlueprintException::class) - open fun validateCapabilityDefinitions(nodeTypeName: String, nodeType: NodeType) { - val capabilities = nodeType.capabilities - paths.add("capabilities") - capabilities?.forEach { capabilityName, capabilityDefinition -> - paths.add(capabilityName) - - validateCapabilityDefinition(nodeTypeName, nodeType, capabilityName, capabilityDefinition) - - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateCapabilityDefinition( - nodeTypeName: String, - nodeType: NodeType, - capabilityName: String, - capabilityDefinition: CapabilityDefinition - ) { - val capabilityType = capabilityDefinition.type - check(BlueprintTypes.validCapabilityTypes.contains(capabilityType)) { - throw BlueprintException( - format( - "Failed to get CapabilityType({}) for NodeType({})", - capabilityType, nodeTypeName - ) - ) - } - } - - @Throws(BlueprintException::class) - open fun validateRequirementDefinitions(nodeName: String, nodeType: NodeType) { - paths.add("requirements") - val requirements = nodeType.requirements - - requirements?.forEach { requirementDefinitionName, requirementDefinition -> - paths.add(requirementDefinitionName) - message.appendln("Validating : " + paths.joinToString(separator)) - validateRequirementDefinition(nodeName, nodeType, requirementDefinitionName, requirementDefinition) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateRequirementDefinition( - nodeTypeName: String, - nodeType: NodeType, - requirementDefinitionName: String, - requirementDefinition: RequirementDefinition - ) { - - log.info("Validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName) - val requirementNodeTypeName = requirementDefinition.node!! - val capabilityName = requirementDefinition.capability - val relationship = requirementDefinition.relationship!! - - check(BlueprintTypes.validRelationShipDerivedFroms.contains(relationship)) { - throw BlueprintException( - format( - "Failed to get relationship({}) for NodeType({})'s requirement({}) ", - relationship, nodeTypeName, requirementDefinitionName - ) - ) - } - - val relationShipNodeType = serviceTemplate.nodeTypes?.get(requirementNodeTypeName) - ?: throw BlueprintException( - format( - "Failed to get requirement NodeType({})'s for requirement({}) ", - requirementNodeTypeName, requirementDefinitionName - ) - ) - - relationShipNodeType.capabilities?.get(capabilityName) - ?: throw BlueprintException( - format( - "Failed to get requirement NodeType({})'s capability({}) for NodeType ({})'s requirement({}) ", - requirementNodeTypeName, capabilityName, nodeTypeName, requirementDefinitionName - ) - ) - } - - @Throws(BlueprintException::class) - open fun validateInterfaceDefinitions(interfaces: MutableMap) { - paths.add("interfaces") - interfaces.forEach { interfaceName, interfaceDefinition -> - paths.add(interfaceName) - message.appendln("Validating : " + paths.joinToString(separator)) - interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateOperationDefinitions(operations: MutableMap) { - paths.add("operations") - operations.forEach { opertaionName, operationDefinition -> - paths.add(opertaionName) - message.appendln("Validating : " + paths.joinToString(separator)) - operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) } - operationDefinition.inputs?.let { validatePropertyDefinitions(operationDefinition.inputs!!) } - operationDefinition.outputs?.let { validatePropertyDefinitions(operationDefinition.outputs!!) } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateImplementation(implementation: Implementation) { - checkNotEmpty(implementation.primary) { "couldn't get implementation" } - } - - @Throws(BlueprintException::class) - open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) { - - val artifactType = serviceTemplate.artifactTypes?.get(artifactTypeName) - ?: throw BlueprintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)") - - checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom) - } - - @Throws(BlueprintException::class) - open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition") - } - } - - @Throws(BlueprintException::class) - open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom)) - } - } - - @Throws(BlueprintException::class) - open fun checkValidRelationshipTypeDerivedFrom(relationshipTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validRelationShipDerivedFroms.contains(derivedFrom)) { - throw BlueprintException(format("Failed to get relationship type ({})'s derivedFrom({}) definition ", relationshipTypeName, derivedFrom)) - } - } - - open fun checkPropertyValue(propertyName: String, propertyDefinition: PropertyDefinition, propertyAssignment: JsonNode) { - val propertyType = propertyDefinition.type - val isValid: Boolean - - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType)) { - isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment) - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { - - val entrySchemaType = propertyDefinition.entrySchema?.type - ?: throw BlueprintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName)) - - if (!BlueprintTypes.validPropertyTypes().contains(entrySchemaType)) { - checkPropertyDataType(entrySchemaType, propertyName) - } - isValid = JacksonUtils.checkJsonNodeValueOfCollectionType(propertyType, propertyAssignment) - } else { - checkPropertyDataType(propertyType, propertyName) - isValid = true - } - - check(isValid) { - throw BlueprintException( - format( - "property({}) defined of type({}) is not comptable with the value ({})", - propertyName, propertyType, propertyAssignment - ) - ) - } - } - - private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { - - val dataType = serviceTemplate.dataTypes?.get(dataTypeName) - ?: throw BlueprintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) - - checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) - } - - private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { - if (BlueprintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { - return true - } else { - throw BlueprintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName)) - } - } - - private fun checkDataType(key: String): Boolean { - return serviceTemplate.dataTypes?.containsKey(key) ?: false - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintVelocityTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintVelocityTemplateService.kt deleted file mode 100644 index 1c4847900..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintVelocityTemplateService.kt +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import org.apache.commons.lang3.BooleanUtils -import org.apache.commons.lang3.StringUtils -import org.apache.velocity.VelocityContext -import org.apache.velocity.app.VelocityEngine -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintJsonNodeFactory -import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode -import java.io.StringWriter - -object BlueprintVelocityTemplateService { - - /** - * Generate Content from Velocity Template and JSON Content with injected API - */ - fun generateContent( - template: String, - json: String, - ignoreJsonNull: Boolean = false, - additionalContext: MutableMap = mutableMapOf() - ): String { - - // Customized Object Mapper to remove String double quotes - val mapper = ObjectMapper() - val nodeFactory = BlueprintJsonNodeFactory() - mapper.nodeFactory = nodeFactory - - val jsonNode: JsonNode? = if (json.isNotEmpty()) { - mapper.readValue(json, JsonNode::class.java) - ?: throw BlueprintProcessorException("couldn't get json node from json") - } else { - null - } - return generateContent(template, jsonNode, ignoreJsonNull, additionalContext) - } - - /** - * Generate Content from Velocity Template and JSON Node with injected API - */ - fun generateContent( - template: String, - jsonNode: JsonNode?, - ignoreJsonNull: Boolean = false, - additionalContext: MutableMap = mutableMapOf() - ): String { - - /* - * create a new instance of the velocity engine - */ - val velocity = VelocityEngine() - - /* - * initialize the engine - */ - velocity.init() - - val velocityContext = VelocityContext() - velocityContext.put("StringUtils", StringUtils::class.java) - velocityContext.put("BooleanUtils", BooleanUtils::class.java) - - // Add the Custom Velocity Context API - additionalContext.forEach { (name, value) -> velocityContext.put(name, value) } - - // Add the JSON Data to the context - if (jsonNode != null) { - if (ignoreJsonNull) - jsonNode.removeNullNode() - jsonNode.fields().forEach { entry -> - velocityContext.put(entry.key, entry.value) - } - } - - val stringWriter = StringWriter() - velocity.evaluate(velocityContext, stringWriter, "TemplateData", template) - stringWriter.flush() - return stringWriter.toString() - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowService.kt deleted file mode 100644 index b5121caac..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowService.kt +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.CoroutineName -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.channels.actor -import kotlinx.coroutines.channels.consumeEach -import kotlinx.coroutines.launch -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel -import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeStatus -import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeStatus -import org.onap.ccsdk.cds.controllerblueprints.core.incomingEdges -import org.onap.ccsdk.cds.controllerblueprints.core.isEndNode -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdges -import org.onap.ccsdk.cds.controllerblueprints.core.outgoingEdgesNotInLabels -import org.onap.ccsdk.cds.controllerblueprints.core.startNodes -import kotlin.coroutines.CoroutineContext - -interface BlueprintWorkFlowService { - - /** Executes imperative workflow graph [graph] for the bluePrintRuntimeService [bluePrintRuntimeService] - * and workflow input [input]*/ - suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BlueprintRuntimeService<*>, input: In): Out - - suspend fun initializeWorkflow(input: In): EdgeLabel - - suspend fun prepareWorkflowOutput(): Out - - /** Prepare the message for the Node */ - suspend fun prepareNodeExecutionMessage(node: Graph.Node): NodeExecuteMessage - - suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage - - suspend fun executeNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel - - suspend fun skipNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel - - suspend fun cancelNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel - - suspend fun restartNode(node: Graph.Node, nodeInput: In, nodeOutput: Out): EdgeLabel -} - -/** Workflow Message Types */ -sealed class WorkflowMessage - -class WorkflowExecuteMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() - -class WorkflowCancelMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() - -class WorkflowRestartMessage(val input: In, val output: CompletableDeferred) : WorkflowMessage() - -/** Node Message Types */ -sealed class NodeMessage - -class NodeReadyMessage(val fromEdge: Graph.Edge, val edgeAction: EdgeAction) : NodeMessage() - -class NodeExecuteMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() - -class NodeRestartMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() - -class NodeSkipMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() - -class NodeCancelMessage(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage() - -enum class EdgeAction(val id: String) { - EXECUTE("execute"), - SKIP("skip") -} - -/** Abstract workflow service implementation */ -abstract class AbstractBlueprintWorkFlowService : CoroutineScope, BlueprintWorkFlowService { - - lateinit var graph: Graph - - private val log = logger(AbstractBlueprintWorkFlowService::class) - - private val job = Job() - - lateinit var workflowId: String - - var exceptions: MutableList = arrayListOf() - - override val coroutineContext: CoroutineContext - get() = job + CoroutineName("Wf") - - fun cancel() { - log.info("Received workflow($workflowId) cancel request") - job.cancel() - throw CancellationException("Workflow($workflowId) cancelled as requested") - } - - suspend fun workflowActor() = actor>(coroutineContext, Channel.UNLIMITED) { - /** Process the workflow execution message */ - suspend fun executeMessageActor(workflowExecuteMessage: WorkflowExecuteMessage) { - - val nodeActor = nodeActor() - // Prepare Workflow and Populate the Initial store - initializeWorkflow(workflowExecuteMessage.input) - - val startNode = graph.startNodes().first() - // Prepare first node message and Send NodeExecuteMessage - // Start node doesn't wait for any nodes, so we can pass Execute message directly - val nodeExecuteMessage = prepareNodeExecutionMessage(startNode) - /** Send message from workflow actor to node actor */ - launch { - nodeActor.send(nodeExecuteMessage) - } - // Wait for workflow completion or Error - nodeActor.invokeOnClose { exception -> - launch { - if (exception != null) exceptions.add(BlueprintProcessorException(exception)) - log.info("workflow($workflowId) nodes completed with (${exceptions.size})exceptions") - val workflowOutput = prepareWorkflowOutput() - workflowExecuteMessage.output.complete(workflowOutput) - channel.close() - } - } - } - - /** Process each actor message received based on type */ - consumeEach { message -> - when (message) { - is WorkflowExecuteMessage -> { - launch { - try { - executeMessageActor(message) - } catch (e: Exception) { - exceptions.add(e) - } - } - } - is WorkflowRestartMessage -> { - launch { - TODO("") - } - } - is WorkflowCancelMessage -> { - launch { - TODO("") - } - } - } - } - } - - private suspend fun nodeActor() = actor>(coroutineContext, Channel.UNLIMITED) { - - /** Send message to process from one state to other state */ - fun sendNodeMessage(nodeMessage: NodeMessage) = launch { - channel.send(nodeMessage) - } - - /** Process the cascade node processing, based on the previous state of the node */ - fun processNextNodes(node: Graph.Node, nodeState: EdgeLabel) { - // Process only Next Success Node - val stateEdges = graph.outgoingEdges(node.id, arrayListOf(nodeState)) - if (stateEdges.isNotEmpty()) { - stateEdges.forEach { stateEdge -> - // Prepare next node ready message and Send NodeReadyMessage - val nodeReadyMessage = NodeReadyMessage(stateEdge, EdgeAction.EXECUTE) - sendNodeMessage(nodeReadyMessage) - } - } - } - - suspend fun triggerToExecuteOrSkip(message: NodeReadyMessage) { - val edge = message.fromEdge - val node = edge.target - // Check if current edge action is Skip or Execute - when (message.edgeAction) { - EdgeAction.SKIP -> { - val skipMessage = prepareNodeSkipMessage(node) - sendNodeMessage(skipMessage) - } - EdgeAction.EXECUTE -> { - val nodeExecuteMessage = prepareNodeExecutionMessage(node) - sendNodeMessage(nodeExecuteMessage) - } - } - } - - suspend fun readyNodeWorker(message: NodeReadyMessage) { - val edge = message.fromEdge - val node = edge.target - log.debug("@@@@@ Ready workflow($workflowId), node($node) from edge($edge) for action(${message.edgeAction}) @@@@@") - // Update the current incoming edge status to executed or skipped - when (message.edgeAction) { - EdgeAction.SKIP -> message.fromEdge.status = EdgeStatus.SKIPPED - EdgeAction.EXECUTE -> message.fromEdge.status = EdgeStatus.EXECUTED - } - val incomingEdges = graph.incomingEdges(node.id) - if (incomingEdges.size > 1) { - // Check all incoming edges executed or skipped - val notCompletedEdges = incomingEdges.filter { it.status == EdgeStatus.NOT_STARTED } - if (notCompletedEdges.isEmpty()) { - // Possibility of skip edge action performed at last, but other edges have execute action. - val executePresent = incomingEdges.filter { it.status == EdgeStatus.EXECUTED } - val newMessage = if (executePresent.isNotEmpty()) { - NodeReadyMessage(message.fromEdge, EdgeAction.EXECUTE) - } else { - message - } - triggerToExecuteOrSkip(newMessage) - } else { - log.info("node(${node.id}) is waiting for incoming edges($notCompletedEdges)") - } - } else { - triggerToExecuteOrSkip(message) - } - } - - suspend fun executeNodeWorker(message: NodeExecuteMessage) { - val node = message.node - node.status = NodeStatus.EXECUTING - val nodeState = if (node.id == BlueprintConstants.GRAPH_START_NODE_NAME || - node.id == BlueprintConstants.GRAPH_END_NODE_NAME - ) { - EdgeLabel.SUCCESS - } else { - log.debug("##### Processing workflow($workflowId) node($node) #####") - // Call the Extension function and get the next Edge state. - executeNode(node, message.nodeInput, message.nodeOutput) - } - // Update Node Completed - node.status = NodeStatus.EXECUTED - log.info("Execute node(${node.id}) -> executed state($nodeState)") - // Check if the Node status edge is there, If not close processing - val edgePresent = graph.outgoingEdges(node.id, nodeState).isNotEmpty() - - // If End Node, Send End Message - if (graph.isEndNode(node)) { - // Close the current channel - channel.close() - } else if (!edgePresent) { - throw BlueprintProcessorException("node(${node.id}) outgoing edge($nodeState) is missing.") - } else { - val skippingEdges = graph.outgoingEdgesNotInLabels(node.id, arrayListOf(nodeState)) - log.debug("Skipping node($node)'s outgoing edges($skippingEdges)") - // Process Skip Edges - skippingEdges.forEach { skippingEdge -> - // Prepare next node ready message and Send NodeReadyMessage - val nodeReadyMessage = NodeReadyMessage(skippingEdge, EdgeAction.SKIP) - sendNodeMessage(nodeReadyMessage) - } - // Process Success Node - processNextNodes(node, nodeState) - } - } - - suspend fun skipNodeWorker(message: NodeSkipMessage) { - val node = message.node - val incomingEdges = graph.incomingEdges(node.id) - // Check All Incoming Nodes Skipped - val nonSkippedEdges = incomingEdges.filter { - it.status == EdgeStatus.NOT_STARTED - } - log.debug("Node($node) incoming edges ($incomingEdges), not skipped incoming edges ($nonSkippedEdges)") - - if (nonSkippedEdges.isEmpty()) { - log.debug("$$$$$ Skipping workflow($workflowId) node($node) $$$$$") - // Call the Extension Function - val nodeState = skipNode(node, message.nodeInput, message.nodeOutput) - log.info("Skip node(${node.id}) -> executed state($nodeState)") - // Mark the Current node as Skipped - node.status = NodeStatus.SKIPPED - // Look for next possible skip nodes - graph.outgoingEdges(node.id).forEach { outgoingEdge -> - val nodeReadyMessage = NodeReadyMessage(outgoingEdge, EdgeAction.SKIP) - sendNodeMessage(nodeReadyMessage) - } - } - } - - fun restartNodeWorker(message: NodeRestartMessage) = launch { - TODO() - } - - fun cancelNodeWorker(messageWorkflow: WorkflowCancelMessage) = launch { - channel.close() - throw CancellationException("Workflow($workflowId) actor cancelled as requested.") - } - - /** Process each actor message received based on type **/ - consumeEach { nodeMessage -> - when (nodeMessage) { - is NodeReadyMessage -> { - // Blocking call - try { - readyNodeWorker(nodeMessage) - } catch (e: Exception) { - exceptions.add(e) - channel.close() - } - } - is NodeExecuteMessage -> { - launch { - try { - executeNodeWorker(nodeMessage) - } catch (e: Exception) { - nodeMessage.node.status = NodeStatus.TERMINATED - exceptions.add(e) - channel.close() - } - } - } - is NodeSkipMessage -> { - launch { - try { - skipNodeWorker(nodeMessage) - } catch (e: Exception) { - nodeMessage.node.status = NodeStatus.TERMINATED - exceptions.add(e) - channel.close() - } - } - } - is NodeRestartMessage -> { - launch { - try { - restartNodeWorker(nodeMessage) - } catch (e: Exception) { - exceptions.add(e) - channel.close() - } - } - } - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt index 7a5a2d58f..b246054e2 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt @@ -19,8 +19,8 @@ package org.onap.ccsdk.cds.controllerblueprints.core.service import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactExpression @@ -40,11 +40,11 @@ import org.slf4j.LoggerFactory * * @author Brinda Santh */ -open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRuntimeService>) { +open class PropertyAssignmentService(var bluePrintRuntimeService: BluePrintRuntimeService>) { private val log = LoggerFactory.getLogger(this::class.toString()) - private var bluePrintContext: BlueprintContext = bluePrintRuntimeService.bluePrintContext() + private var bluePrintContext: BluePrintContext = bluePrintRuntimeService.bluePrintContext() /* @@ -60,7 +60,7 @@ open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRunti assignment: JsonNode ): JsonNode { log.trace("Assignment ({})", assignment) - val expressionData = BlueprintExpressionService.getExpressionData(assignment) + val expressionData = BluePrintExpressionService.getExpressionData(assignment) return if (expressionData.isExpression) { resolveExpression(definitionType, definitionName, assignmentName, expressionData) @@ -82,32 +82,32 @@ open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRunti val command = expressionData.command!! when (command) { - BlueprintConstants.EXPRESSION_GET_INPUT -> { + BluePrintConstants.EXPRESSION_GET_INPUT -> { valueNode = bluePrintRuntimeService.getInputValue(expressionData.inputExpression?.propertyName!!) } - BlueprintConstants.EXPRESSION_GET_ATTRIBUTE -> { + BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> { valueNode = resolveAttributeExpression(definitionType, definitionName, expressionData.attributeExpression!!) } - BlueprintConstants.EXPRESSION_GET_PROPERTY -> { + BluePrintConstants.EXPRESSION_GET_PROPERTY -> { valueNode = resolvePropertyExpression(definitionType, definitionName, expressionData.propertyExpression!!) } - BlueprintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { + BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> { valueNode = resolveOperationOutputExpression(definitionName, expressionData.operationOutputExpression!!) } - BlueprintConstants.EXPRESSION_GET_ARTIFACT -> { + BluePrintConstants.EXPRESSION_GET_ARTIFACT -> { valueNode = resolveArtifactExpression(definitionName, expressionData.artifactExpression!!) } - BlueprintConstants.EXPRESSION_DSL_REFERENCE -> { + BluePrintConstants.EXPRESSION_DSL_REFERENCE -> { valueNode = bluePrintRuntimeService.resolveDSLExpression(expressionData.dslExpression!!.propertyName) } - BlueprintConstants.EXPRESSION_GET_NODE_OF_TYPE -> { + BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE -> { } else -> { - throw BlueprintException( + throw BluePrintException( "for $definitionType($definitionName) property ($propName), " + "command ($command) is not supported " ) @@ -140,53 +140,53 @@ open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRunti * SELF : Current Node Template properties. */ when (attributeExpression.modelableEntityName) { - BlueprintConstants.PROPERTY_ENV -> { + BluePrintConstants.PROPERTY_ENV -> { val environmentValue = System.getenv(attributeName) valueNode = environmentValue.asJsonPrimitive() } - BlueprintConstants.PROPERTY_APP -> { + BluePrintConstants.PROPERTY_APP -> { val environmentValue = System.getProperty(attributeName) valueNode = environmentValue.asJsonPrimitive() } - BlueprintConstants.PROPERTY_BPP -> { + BluePrintConstants.PROPERTY_BPP -> { valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue( - BlueprintConstants.PROPERTY_BPP, + BluePrintConstants.PROPERTY_BPP, attributeName - ) ?: throw BlueprintException("failed to get env attribute name ($attributeName) ") + ) ?: throw BluePrintException("failed to get env attribute name ($attributeName) ") } else -> { - if (!attributeExpression.modelableEntityName.equals(BlueprintConstants.PROPERTY_SELF, true)) { + if (!attributeExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) { attributeDefinitionName = attributeExpression.modelableEntityName } /** This block is to Validate, if Attribute definition is present */ when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, - BlueprintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, - BlueprintConstants.MODEL_DEFINITION_TYPE_DSL -> + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + BluePrintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, + BluePrintConstants.MODEL_DEFINITION_TYPE_DSL -> bluePrintContext.nodeTemplateNodeType(attributeDefinitionName).attributes - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> bluePrintContext.relationshipTemplateRelationshipType(attributeDefinitionName).attributes - else -> throw BlueprintException("failed to understand template type($definitionType), it is not supported") + else -> throw BluePrintException("failed to understand template type($definitionType), it is not supported") }?.get(attributeName) - ?: throw BlueprintException( + ?: throw BluePrintException( "failed to get attribute definitions for " + "$definitionType ($attributeDefinitionName)'s attribute name ($attributeName) " ) valueNode = when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, - BlueprintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, - BlueprintConstants.MODEL_DEFINITION_TYPE_DSL -> + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + BluePrintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, + BluePrintConstants.MODEL_DEFINITION_TYPE_DSL -> bluePrintRuntimeService.getNodeTemplateAttributeValue(attributeDefinitionName, attributeName) - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> bluePrintRuntimeService.getRelationshipTemplateAttributeValue( attributeDefinitionName, attributeName ) - else -> throw BlueprintException("failed to understand template type($definitionType), it is not supported") + else -> throw BluePrintException("failed to understand template type($definitionType), it is not supported") } - ?: throw BlueprintException("failed to get node template ($attributeDefinitionName)'s attribute name ($attributeName) ") + ?: throw BluePrintException("failed to get node template ($attributeDefinitionName)'s attribute name ($attributeName) ") } } if (subAttributeName != null) { @@ -212,32 +212,32 @@ open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRunti var propertyDefinitionName = definitionName - if (!propertyExpression.modelableEntityName.equals(BlueprintConstants.PROPERTY_SELF, true)) { + if (!propertyExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) { propertyDefinitionName = propertyExpression.modelableEntityName } val nodeTemplatePropertyExpression = when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, - BlueprintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, - BlueprintConstants.MODEL_DEFINITION_TYPE_DSL -> + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + BluePrintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, + BluePrintConstants.MODEL_DEFINITION_TYPE_DSL -> bluePrintContext.nodeTemplateByName(propertyDefinitionName).properties - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> bluePrintContext.relationshipTemplateByName(propertyDefinitionName).properties - else -> throw BlueprintException("failed to understand template type($definitionType), it is not supported") + else -> throw BluePrintException("failed to understand template type($definitionType), it is not supported") }?.get(propertyName) - ?: throw BlueprintException("failed to get property assignment for node template ($definitionName)'s property name ($propertyName).") + ?: throw BluePrintException("failed to get property assignment for node template ($definitionName)'s property name ($propertyName).") /** This block is to Validate, if Property definition is present */ when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, - BlueprintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, - BlueprintConstants.MODEL_DEFINITION_TYPE_DSL -> + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + BluePrintConstants.MODEL_DEFINITION_TYPE_WORKFLOW, + BluePrintConstants.MODEL_DEFINITION_TYPE_DSL -> bluePrintContext.nodeTemplateNodeType(propertyDefinitionName).properties - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TEMPLATE -> bluePrintContext.relationshipTemplateRelationshipType(propertyDefinitionName).properties - else -> throw BlueprintException("failed to understand template type($definitionType), it is not supported") + else -> throw BluePrintException("failed to understand template type($definitionType), it is not supported") }?.get(propertyName) - ?: throw BlueprintException("failed to get property definition for node template ($definitionName)'s property name ($propertyName).") + ?: throw BluePrintException("failed to get property definition for node template ($definitionName)'s property name ($propertyName).") log.info( "$definitionType($propertyDefinitionName), property($propertyName) resolved value ($nodeTemplatePropertyExpression)" @@ -295,7 +295,7 @@ open class PropertyAssignmentService(var bluePrintRuntimeService: BlueprintRunti } val artifactDefinition: ArtifactDefinition = bluePrintContext.nodeTemplateByName(artifactNodeTemplateName) .artifacts?.get(artifactExpression.artifactName) - ?: throw BlueprintException( + ?: throw BluePrintException( format( "failed to get artifact definitions for node template ({})'s " + "artifact name ({}) ", diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt new file mode 100755 index 000000000..1a7c23cf1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt @@ -0,0 +1,279 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 Nordix Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import com.google.common.base.Predicates +import org.apache.commons.compress.archivers.ArchiveEntry +import org.apache.commons.compress.archivers.ArchiveInputStream +import org.apache.commons.compress.archivers.ArchiveOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream +import org.apache.commons.compress.archivers.zip.ZipFile +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream +import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.slf4j.LoggerFactory +import java.io.BufferedInputStream +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.Closeable +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.InputStreamReader +import java.io.OutputStream +import java.nio.file.FileVisitResult +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.SimpleFileVisitor +import java.nio.file.attribute.BasicFileAttributes +import java.util.Enumeration +import java.util.function.Predicate +import java.util.zip.Deflater + +enum class ArchiveType { + TarGz, + Zip +} + +class BluePrintArchiveUtils { + + companion object { + + private val log = LoggerFactory.getLogger(BluePrintArchiveUtils::class.java) + + /** + * Create a new Zip from a root directory + * + * @param source the base directory + * @param destination the output filename + * @return True if OK + */ + fun compress(source: File, destination: File, archiveType: ArchiveType = ArchiveType.Zip): Boolean { + try { + if (!destination.parentFile.exists()) { + destination.parentFile.mkdirs() + } + destination.createNewFile() + val ignoreZipFiles = Predicate { path -> !path.endsWith(".zip") && !path.endsWith(".ZIP") } + FileOutputStream(destination).use { out -> + compressFolder(source.toPath(), out, archiveType, pathFilter = ignoreZipFiles) + } + } catch (e: Exception) { + log.error("Fail to compress folder($source) to path(${destination.path})", e) + return false + } + return true + } + + /** + * In-memory compress an entire folder. + */ + fun compressToBytes( + baseDir: Path, + archiveType: ArchiveType = ArchiveType.Zip, + compressionLevel: Int = Deflater.NO_COMPRESSION + ): ByteArray { + return compressFolder(baseDir, ByteArrayOutputStream(), archiveType, compressionLevel = compressionLevel) + .toByteArray() + } + + /** + * Compress an entire folder. + * + * @param baseDir path of base folder to be packaged. + * @param output the output stream + * @param pathFilter filter to ignore files based on its path. + * @param compressionLevel the wanted compression level. + * @param fixedModificationTime to force every entry to have this modification time. + * Useful for reproducible operations, like tests, for example. + */ + private fun compressFolder( + baseDir: Path, + output: T, + archiveType: ArchiveType, + pathFilter: Predicate = Predicates.alwaysTrue(), + compressionLevel: Int = Deflater.DEFAULT_COMPRESSION, + fixedModificationTime: Long? = null + ): T + where T : OutputStream { + val stream: ArchiveOutputStream = if (archiveType == ArchiveType.Zip) + ZipArchiveOutputStream(output).apply { setLevel(compressionLevel) } + else + TarArchiveOutputStream(GzipCompressorOutputStream(output)) + stream + .use { aos -> + Files.walkFileTree( + baseDir, + object : SimpleFileVisitor() { + @Throws(IOException::class) + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (pathFilter.test(file)) { + var archiveEntry: ArchiveEntry = aos.createArchiveEntry( + file.toFile(), + baseDir.relativize(file).toString() + ) + if (archiveType == ArchiveType.Zip) { + val entry = archiveEntry as ZipArchiveEntry + fixedModificationTime?.let { + entry.time = it + } + entry.time = 0 + } + aos.putArchiveEntry(archiveEntry) + Files.copy(file, aos) + aos.closeArchiveEntry() + } + return FileVisitResult.CONTINUE + } + + @Throws(IOException::class) + override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { + var archiveEntry: ArchiveEntry? + if (archiveType == ArchiveType.Zip) { + val entry = ZipArchiveEntry(baseDir.relativize(dir).toString() + "/") + fixedModificationTime?.let { + entry.time = it + } + archiveEntry = entry + } else + archiveEntry = TarArchiveEntry(baseDir.relativize(dir).toString() + "/") + aos.putArchiveEntry(archiveEntry) + aos.closeArchiveEntry() + return FileVisitResult.CONTINUE + } + } + ) + } + return output + } + + private fun getDefaultEncoding(): String? { + val bytes = byteArrayOf('D'.toByte()) + val inputStream: InputStream = ByteArrayInputStream(bytes) + val reader = InputStreamReader(inputStream) + return reader.encoding + } + + fun deCompress(archiveFile: File, targetPath: String, archiveType: ArchiveType = ArchiveType.Zip): File { + var enumeration: ArchiveEnumerator? = null + if (archiveType == ArchiveType.Zip) { + val zipArchive = ZipFile(archiveFile, getDefaultEncoding()) + enumeration = ArchiveEnumerator(zipArchive) + } else { // Tar Gz + var tarGzArchiveIs: InputStream = BufferedInputStream(archiveFile.inputStream()) + tarGzArchiveIs = GzipCompressorInputStream(tarGzArchiveIs) + val tarGzArchive: ArchiveInputStream = TarArchiveInputStream(tarGzArchiveIs) + enumeration = ArchiveEnumerator(tarGzArchive) + } + + enumeration.use { + while (enumeration!!.hasMoreElements()) { + val entry: ArchiveEntry? = enumeration.nextElement() + val destFilePath = File(targetPath, entry!!.name) + destFilePath.parentFile.mkdirs() + + if (entry!!.isDirectory) + continue + + val bufferedIs = BufferedInputStream(enumeration.getInputStream(entry)) + destFilePath.outputStream().buffered(1024).use { bos -> + bufferedIs.copyTo(bos) + } + + if (!enumeration.getHasSharedEntryInputStream()) + bufferedIs.close() + } + } + + val destinationDir = File(targetPath) + check(destinationDir.isDirectory && destinationDir.exists()) { + throw BluePrintProcessorException("failed to decompress blueprint(${archiveFile.absolutePath}) to ($targetPath) ") + } + + return destinationDir + } + } + + class ArchiveEnumerator : Enumeration, Closeable { + + private val zipArchive: ZipFile? + private val zipEnumeration: Enumeration? + private val archiveStream: ArchiveInputStream? + private var nextEntry: ArchiveEntry? = null + private val hasSharedEntryInputStream: Boolean + + constructor(zipFile: ZipFile) { + zipArchive = zipFile + zipEnumeration = zipFile.entries + archiveStream = null + hasSharedEntryInputStream = false + } + + constructor(archiveStream: ArchiveInputStream) { + this.archiveStream = archiveStream + zipArchive = null + zipEnumeration = null + hasSharedEntryInputStream = true + } + + fun getHasSharedEntryInputStream(): Boolean { + return hasSharedEntryInputStream + } + + fun getInputStream(entry: ArchiveEntry): InputStream? { + return if (zipArchive != null) + zipArchive?.getInputStream(entry as ZipArchiveEntry?) + else + archiveStream + } + + override fun hasMoreElements(): Boolean { + if (zipEnumeration != null) + return zipEnumeration?.hasMoreElements() + else if (archiveStream != null) { + nextEntry = archiveStream.nextEntry + if (nextEntry != null && !archiveStream.canReadEntryData(nextEntry)) + return hasMoreElements() + return nextEntry != null + } + return false + } + + override fun nextElement(): ArchiveEntry? { + if (zipEnumeration != null) + nextEntry = zipEnumeration.nextElement() + else if (archiveStream != null) { + if (nextEntry == null) + nextEntry = archiveStream.nextEntry + } + return nextEntry + } + + override fun close() { + if (zipArchive != null) + zipArchive.close() + else archiveStream?.close() + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt new file mode 100755 index 000000000..292eca92e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt @@ -0,0 +1,327 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import kotlinx.coroutines.runBlocking +import org.apache.commons.io.FileUtils +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode +import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.slf4j.LoggerFactory +import java.io.File +import java.io.FileFilter +import java.io.FileNotFoundException +import java.net.URL +import java.net.URLClassLoader +import java.nio.file.Files +import java.nio.file.NotDirectoryException +import java.nio.file.Path +import java.nio.file.Paths +import java.nio.file.StandardOpenOption + +class BluePrintFileUtils { + companion object { + + const val COMPILED_JAR_SUFFIX = "cba-kts.jar" + + private val log = LoggerFactory.getLogger(this::class.toString()) + + fun createEmptyBluePrint(basePath: String) { + + val blueprintDir = File(basePath) + FileUtils.deleteDirectory(blueprintDir) + + Files.createDirectories(blueprintDir.toPath()) + + val metaDataDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_METADATA_DIR)) + Files.createDirectories(metaDataDir.toPath()) + + val metaFile = File( + blueprintDir.absolutePath.plus(File.separator).plus( + BluePrintConstants + .TOSCA_METADATA_ENTRY_DEFINITION_FILE + ) + ) + Files.write(metaFile.toPath(), getMetaDataContent().toByteArray(), StandardOpenOption.CREATE_NEW) + + val definitionsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR)) + Files.createDirectories(definitionsDir.toPath()) + + val scriptsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_SCRIPTS_DIR)) + Files.createDirectories(scriptsDir.toPath()) + + val plansDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_PLANS_DIR)) + Files.createDirectories(plansDir.toPath()) + + val templatesDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BluePrintConstants.TOSCA_TEMPLATES_DIR)) + Files.createDirectories(templatesDir.toPath()) + } + + fun copyBluePrint(sourcePath: String, targetPath: String) { + val sourceFile = File(sourcePath) + val targetFile = File(targetPath) + sourceFile.copyRecursively(targetFile, true) + } + + fun deleteBluePrintTypes(basePath: String) { + val definitionPath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR) + log.info("deleting definition types under : $definitionPath") + + val definitionDir = File(definitionPath) + // Find the Type Definitions + val fileFilter = FileFilter { pathname -> pathname.absolutePath.endsWith("_types.json") } + // Delete the Type Files + definitionDir.listFiles(fileFilter).forEach { + Files.deleteIfExists(it.toPath()) + } + } + + fun writeEnhancedBluePrint(blueprintContext: BluePrintContext) { + + // Write Blueprint Types + writeBluePrintTypes(blueprintContext) + // Re Populate the Imports + populateDefaultImports(blueprintContext) + // Rewrite the Entry Definition Files + writeEntryDefinitionFile(blueprintContext) + } + + fun writeBluePrintTypes(blueprintContext: BluePrintContext) { + + val basePath = blueprintContext.rootPath + val definitionPath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR) + val definitionDir = File(definitionPath) + + check(definitionDir.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, + "couldn't get definition file under " + + "path(${definitionDir.absolutePath})" + ) + } + + blueprintContext.serviceTemplate.dataTypes?.let { + val dataTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_DATA_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_DATA_TYPES, dataTypesContent) + } + + blueprintContext.serviceTemplate.relationshipTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_RELATIONSHIP_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_RELATIONSHIP_TYPES, nodeTypesContent) + } + + blueprintContext.serviceTemplate.artifactTypes?.let { + val artifactTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_ARTIFACT_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_ARTIFACT_TYPES, artifactTypesContent) + } + + blueprintContext.serviceTemplate.nodeTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_NODE_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_NODE_TYPES, nodeTypesContent) + } + + blueprintContext.serviceTemplate.policyTypes?.let { + val nodeTypesContent = JacksonUtils.getWrappedJson(BluePrintConstants.PATH_POLICY_TYPES, it.toSortedMap(), true) + writeTypeFile(definitionDir.absolutePath, BluePrintConstants.PATH_POLICY_TYPES, nodeTypesContent) + } + } + + private fun populateDefaultImports(blueprintContext: BluePrintContext) { + // Get the Default Types + val types = arrayListOf( + BluePrintConstants.PATH_DATA_TYPES, BluePrintConstants.PATH_RELATIONSHIP_TYPES, + BluePrintConstants.PATH_ARTIFACT_TYPES, BluePrintConstants.PATH_NODE_TYPES, + BluePrintConstants.PATH_POLICY_TYPES + ) + + // Clean Type Imports + cleanImportTypes(blueprintContext.serviceTemplate) + + val imports = mutableListOf() + types.forEach { typeName -> + val import = ImportDefinition() + import.file = BluePrintConstants.TOSCA_DEFINITIONS_DIR.plus("/$typeName.json") + imports.add(import) + } + + blueprintContext.serviceTemplate.imports = imports + } + + fun cleanImportTypes(serviceTemplate: ServiceTemplate) { + // Clean the Type imports + val toDeleteTypes = serviceTemplate.imports?.filter { + it.file.endsWith("_types.json") + } + + if (toDeleteTypes != null && toDeleteTypes.isNotEmpty()) { + serviceTemplate.imports?.removeAll(toDeleteTypes) + } + } + + /** + * Re Generate the Blueprint Service Template Definition file based on BluePrint Context. + */ + private fun writeEntryDefinitionFile(blueprintContext: BluePrintContext) { + + val absoluteEntryDefinitionFile = blueprintContext.rootPath.plus(File.separator).plus(blueprintContext.entryDefinition) + + val serviceTemplate = blueprintContext.serviceTemplate + + // Clone the Service Template + val writeServiceTemplate = serviceTemplate.clone() + writeServiceTemplate.dataTypes = null + writeServiceTemplate.artifactTypes = null + writeServiceTemplate.policyTypes = null + writeServiceTemplate.relationshipTypes = null + writeServiceTemplate.nodeTypes = null + + // Write the Service Template + writeDefinitionFile(absoluteEntryDefinitionFile, JacksonUtils.getJson(writeServiceTemplate, true)) + } + + fun writeDefinitionFile(definitionFileName: String, content: String) = runBlocking { + val definitionFile = File(definitionFileName) + // Delete the File If exists + Files.deleteIfExists(definitionFile.toPath()) + + Files.write(definitionFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) + check(definitionFile.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_WRITING_FAIL.value, + "couldn't write definition file under " + + "path(${definitionFile.absolutePath})" + ) + } + } + + private fun writeTypeFile(definitionPath: String, type: String, content: String) = runBlocking { + val typeFile = File(definitionPath.plus(File.separator).plus("$type.json")) + + Files.write(typeFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) + check(typeFile.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_WRITING_FAIL.value, + "couldn't write $type.json file under " + + "path(${typeFile.absolutePath})" + ) + } + } + + private fun getMetaDataContent(): String { + return "TOSCA-Meta-File-Version: 1.0.0" + + "\nCSAR-Version: " + + "\nCreated-By: " + + "\nEntry-Definitions: Definitions/.json" + + "\nTemplate-Name: " + + "\nTemplate-Version: " + + "\nTemplate-Type: " + + "\nTemplate-Tags: " + } + + fun getBluePrintFile(fileName: String, targetPath: Path): File { + val filePath = targetPath.resolve(fileName).toString() + val file = File(filePath) + check(file.exists()) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, + "couldn't get definition file under " + + "path(${file.absolutePath})" + ) + } + return file + } + + fun getCbaStorageDirectory(path: String): Path { + check(StringUtils.isNotBlank(path)) { + throw BluePrintException( + ErrorCode.BLUEPRINT_PATH_MISSING.value, + "couldn't get " + + "Blueprint folder under path($path)" + ) + } + + val fileStorageLocation = Paths.get(path).toAbsolutePath().normalize() + + if (!Files.exists(fileStorageLocation)) + Files.createDirectories(fileStorageLocation) + + return fileStorageLocation + } + + fun compileCacheKey(basePath: String): String { + return normalizedPathName(basePath) + } + + private fun compileJarFileName(artifactName: String, artifactVersion: String): String { + return "$artifactName-$artifactVersion-$COMPILED_JAR_SUFFIX" + } + + fun compileJarFilePathName(basePath: String, artifactName: String, artifactVersion: String): String { + return normalizedPathName( + basePath, BluePrintConstants.TOSCA_SCRIPTS_KOTLIN_DIR, + compileJarFileName(artifactName, artifactVersion) + ) + } + + fun compileJarFile(basePath: String, artifactName: String, artifactVersion: String): File { + return normalizedFile( + compileJarFilePathName( + basePath, + artifactName, artifactVersion + ) + ) + } + + fun stripFileExtension(fileName: String): String { + val dotIndexe = fileName.lastIndexOf('.') + + // In case dot is in first position, we are dealing with a hidden file rather than an extension + return if (dotIndexe > 0) fileName.substring(0, dotIndexe) else fileName + } + + fun getURLClassLoaderFromDirectory(directory: File): URLClassLoader { + if (!directory.exists()) { + throw FileNotFoundException(directory.absolutePath) + } else if (!directory.isDirectory) { + throw NotDirectoryException(directory.absolutePath) + } + + val urls = arrayListOf() + directory.walkTopDown() + .filter { it.name.endsWith(COMPILED_JAR_SUFFIX) } + .forEach { + log.debug("Adding (${it.absolutePath}) to classLoader (${directory.absolutePath})") + + urls.add(it.toURI().toURL()) + } + return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader) + } + + fun getURLClassLoaderFromDirectory(path: String): URLClassLoader { + val directory = normalizedFile(path) + return getURLClassLoaderFromDirectory(directory) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt new file mode 100644 index 000000000..d29fed0d9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt @@ -0,0 +1,41 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +object BluePrintIOUtils { + + suspend fun retry( + times: Int = 1, + initialDelay: Long = 0, + delay: Long = 1000, + block: suspend (Int) -> T, + exceptionBlock: (e: Exception) -> Unit + ): T { + var currentDelay = initialDelay + val currentTimes = times - 1 + repeat(currentTimes) { count -> + try { + return block(count) + } catch (e: Exception) { + exceptionBlock(e) + } + kotlinx.coroutines.delay(currentDelay) + currentDelay = delay + } + return block(currentTimes) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt new file mode 100644 index 000000000..43f3a0b53 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt @@ -0,0 +1,280 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDefinitions +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintImportService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService +import org.slf4j.LoggerFactory +import java.io.File +import java.util.Properties + +class BluePrintMetadataUtils { + companion object { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + suspend fun toscaMetaData(basePath: String): ToscaMetaData { + val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) + return toscaMetaDataFromMetaFile(toscaMetaPath) + } + + suspend fun entryDefinitionFile(basePath: String): String { + val toscaMetaPath = basePath.plus(BluePrintConstants.PATH_DIVIDER) + .plus(BluePrintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) + return toscaMetaDataFromMetaFile(toscaMetaPath).entityDefinitions + } + + fun bluePrintEnvProperties(basePath: String): Properties { + val blueprintsEnvFilePath = basePath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_ENVIRONMENTS_DIR) + return environmentFileProperties(blueprintsEnvFilePath) + } + + fun environmentFileProperties(pathName: String): Properties { + val properties = Properties() + val envDir = normalizedFile(pathName) + // Verify if the environment directory exists + if (envDir.exists() && envDir.isDirectory) { + // Find all available environment files + envDir.listFiles()!! + .filter { it.name.endsWith(".properties") } + .forEach { + val istream = it.inputStream() + properties.load(istream) + istream.close() + } + } + return properties + } + + private suspend fun toscaMetaDataFromMetaFile(metaFilePath: String): ToscaMetaData { + val toscaMetaData = ToscaMetaData() + val lines = normalizedFile(metaFilePath).readNBLines() + lines.forEach { line -> + if (line.contains(":")) { + val keyValue = line.split(":") + if (keyValue.size == 2) { + val value: String = keyValue[1].trim() + when (keyValue[0]) { + "TOSCA-Meta-File-Version" -> toscaMetaData.toscaMetaFileVersion = value + "CSAR-Version" -> toscaMetaData.csarVersion = value + "Created-By" -> toscaMetaData.createdBy = value + "Entry-Definitions" -> toscaMetaData.entityDefinitions = value + "Template-Name" -> toscaMetaData.templateName = value + "Template-Version" -> toscaMetaData.templateVersion = value + "Template-Tags" -> toscaMetaData.templateTags = value + "Template-Type" -> toscaMetaData.templateType = value + } + } + } + } + return toscaMetaData + } + + /** Get the default blueprint runtime for [id] and [blueprintBasePath] */ + suspend fun getBluePrintRuntime(id: String, blueprintBasePath: String): + BluePrintRuntimeService> { + val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath) + return getBluePrintRuntime(id, bluePrintContext) + } + + /** Get the default blocking blueprint runtime api for [id] and [blueprintBasePath] used in testing */ + fun bluePrintRuntime(id: String, blueprintBasePath: String): + BluePrintRuntimeService> = runBlocking { + val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath) + getBluePrintRuntime(id, bluePrintContext) + } + + /** Get the default blueprint runtime from [bluePrintContext] */ + fun getBluePrintRuntime(id: String, bluePrintContext: BluePrintContext): + BluePrintRuntimeService> { + checkNotEmpty(bluePrintContext.rootPath) { "blueprint context root path is missing." } + checkNotEmpty(bluePrintContext.entryDefinition) { "blueprint context entry definition is missing." } + val blueprintBasePath = bluePrintContext.rootPath + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + bluePrintRuntimeService.put( + BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH, + blueprintBasePath.asJsonPrimitive() + ) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) + return bluePrintRuntimeService + } + + /** Get the blueprint runtime for enhancement start for [id] and [blueprintBasePath] */ + suspend fun getBaseEnhancementBluePrintRuntime(id: String, blueprintBasePath: String): + BluePrintRuntimeService> { + + val bluePrintContext: BluePrintContext = getBaseEnhancementBluePrintContext(blueprintBasePath) + + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + bluePrintRuntimeService.put( + BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH, + blueprintBasePath.asJsonPrimitive() + ) + bluePrintRuntimeService.put(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) + + return bluePrintRuntimeService + } + + /** Get the default blueprint runtime for enhancement start for [id], [blueprintBasePath] and [executionContext] */ + suspend fun getBluePrintRuntime( + id: String, + blueprintBasePath: String, + executionContext: MutableMap + ): + BluePrintRuntimeService> { + val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath) + val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext) + executionContext.forEach { + bluePrintRuntimeService.put(it.key, it.value) + } + + bluePrintRuntimeService.setExecutionContext(executionContext) + return bluePrintRuntimeService + } + + /** Get the default blueprint context for [blueprintBasePath]*/ + suspend fun getBluePrintContext(blueprintBasePath: String): BluePrintContext { + + val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) + + log.info( + "Reading blueprint type(${toscaMetaData.templateType}) path($blueprintBasePath) " + + "and entry definition file (${toscaMetaData.entityDefinitions})" + ) + + // If the EntryDefinition is Kotlin file, compile and get Service Template + val bluePrintContext = when (toscaMetaData.templateType.toUpperCase()) { + BluePrintConstants.BLUEPRINT_TYPE_KOTLIN_DSL -> readBlueprintKotlinFile( + toscaMetaData, + blueprintBasePath + ) + BluePrintConstants.BLUEPRINT_TYPE_GENERIC_SCRIPT -> readBlueprintGenericScript( + toscaMetaData, + blueprintBasePath + ) + BluePrintConstants.BLUEPRINT_TYPE_DEFAULT -> readBlueprintFile( + toscaMetaData.entityDefinitions, + blueprintBasePath + ) + else -> + throw BluePrintException( + "Unknown blueprint type(${toscaMetaData.templateType}), " + + "It should be any one of these types[${BluePrintConstants.BLUEPRINT_TYPE_KOTLIN_DSL}," + + "${BluePrintConstants.BLUEPRINT_TYPE_GENERIC_SCRIPT}, " + + "${BluePrintConstants.BLUEPRINT_TYPE_DEFAULT}]" + ) + } + // Copy the metadata info + copyMetaInfoToServiceTemplate(toscaMetaData, bluePrintContext.serviceTemplate) + + return bluePrintContext + } + + private suspend fun getBaseEnhancementBluePrintContext(blueprintBasePath: String): BluePrintContext { + val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) + + // Clean Type files + BluePrintFileUtils.deleteBluePrintTypes(blueprintBasePath) + val rootFilePath: String = blueprintBasePath.plus(File.separator).plus(toscaMetaData.entityDefinitions) + val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) + + // Copy the metadata info + copyMetaInfoToServiceTemplate(toscaMetaData, rootServiceTemplate) + + // Clean the Import Definitions + BluePrintFileUtils.cleanImportTypes(rootServiceTemplate) + + val blueprintContext = BluePrintContext(rootServiceTemplate) + blueprintContext.rootPath = blueprintBasePath + blueprintContext.entryDefinition = toscaMetaData.entityDefinitions + return blueprintContext + } + + /** copy metadata defined in [toscaMetaData] to [serviceTemplate] */ + private fun copyMetaInfoToServiceTemplate(toscaMetaData: ToscaMetaData, serviceTemplate: ServiceTemplate) { + if (serviceTemplate.metadata == null) serviceTemplate.metadata = mutableMapOf() + val metadata = serviceTemplate.metadata!! + metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] = toscaMetaData.createdBy + metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] = toscaMetaData.templateName + metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] = toscaMetaData.templateVersion + metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] = toscaMetaData.templateTags + metadata[BluePrintConstants.METADATA_TEMPLATE_TYPE] = toscaMetaData.templateType + } + + private suspend fun readBlueprintFile(entityDefinitions: String, basePath: String): BluePrintContext { + val normalizedBasePath = normalizedPathName(basePath) + val rootFilePath = normalizedPathName(normalizedBasePath, entityDefinitions) + val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) + + // Recursively Import Template files + val schemaImportResolverUtils = BluePrintImportService(rootServiceTemplate, normalizedBasePath) + val completeServiceTemplate = schemaImportResolverUtils.getImportResolvedServiceTemplate() + val blueprintContext = BluePrintContext(completeServiceTemplate) + blueprintContext.rootPath = normalizedBasePath + blueprintContext.entryDefinition = entityDefinitions + return blueprintContext + } + + /** Reade the Service Template Definitions from the Kotlin file */ + private suspend fun readBlueprintKotlinFile(toscaMetaData: ToscaMetaData, basePath: String): BluePrintContext { + + val definitionClassName = toscaMetaData.entityDefinitions.removeSuffix(".kt") + val normalizedBasePath = normalizedPathName(basePath) + + val bluePrintScriptsService = BluePrintScriptsServiceImpl() + val bluePrintDefinitions = bluePrintScriptsService + .scriptInstance( + normalizedBasePath, toscaMetaData.templateName, + toscaMetaData.templateVersion, definitionClassName, false + ) + // Get the Service Template + val serviceTemplate = bluePrintDefinitions.serviceTemplate() + + // Clean the Default type import Definitions + BluePrintFileUtils.cleanImportTypes(serviceTemplate) + + val blueprintContext = BluePrintContext(serviceTemplate) + blueprintContext.rootPath = normalizedBasePath + blueprintContext.entryDefinition = toscaMetaData.entityDefinitions + blueprintContext.otherDefinitions = bluePrintDefinitions.otherDefinitions() + return blueprintContext + } + + /** Reade the Service Template Definitions from the generic script types */ + private fun readBlueprintGenericScript(toscaMetaData: ToscaMetaData, basePath: String): BluePrintContext { + return BluePrintContext(ServiceTemplate()) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt new file mode 100644 index 000000000..f4c51d455 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.slf4j.LoggerFactory + +/** + * + * + * @author Brinda Santh + */ +object BluePrintRuntimeUtils { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + fun assignInputsFromFile(bluePrintContext: BluePrintContext, fileName: String, context: MutableMap) { + val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputsFromClassPathFile( + bluePrintContext: BluePrintContext, + fileName: String, + context: MutableMap + ) { + val jsonNode = JacksonUtils.jsonNodeFromClassPathFile(fileName) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputsFromContent(bluePrintContext: BluePrintContext, content: String, context: MutableMap) { + val jsonNode: JsonNode = JacksonUtils.jsonNode(content) + return assignInputs(bluePrintContext, jsonNode, context) + } + + fun assignInputs(bluePrintContext: BluePrintContext, jsonNode: JsonNode, context: MutableMap) { + log.info("assignInputs from input JSON ({})", jsonNode.toString()) + bluePrintContext.inputs()?.forEach { propertyName, _ -> + val valueNode: JsonNode = jsonNode.at("/".plus(propertyName)) ?: NullNode.getInstance() + + val path = BluePrintConstants.PATH_INPUTS.plus(BluePrintConstants.PATH_DIVIDER).plus(propertyName) + log.trace("setting input path ({}), values ({})", path, valueNode) + context[path] = valueNode + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt deleted file mode 100644 index a16f58042..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 Nordix Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import com.google.common.base.Predicates -import org.apache.commons.compress.archivers.ArchiveEntry -import org.apache.commons.compress.archivers.ArchiveInputStream -import org.apache.commons.compress.archivers.ArchiveOutputStream -import org.apache.commons.compress.archivers.tar.TarArchiveEntry -import org.apache.commons.compress.archivers.tar.TarArchiveInputStream -import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry -import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream -import org.apache.commons.compress.archivers.zip.ZipFile -import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream -import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.slf4j.LoggerFactory -import java.io.BufferedInputStream -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream -import java.io.Closeable -import java.io.File -import java.io.FileOutputStream -import java.io.IOException -import java.io.InputStream -import java.io.InputStreamReader -import java.io.OutputStream -import java.nio.file.FileVisitResult -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.SimpleFileVisitor -import java.nio.file.attribute.BasicFileAttributes -import java.util.Enumeration -import java.util.function.Predicate -import java.util.zip.Deflater - -enum class ArchiveType { - TarGz, - Zip -} - -class BlueprintArchiveUtils { - - companion object { - - private val log = LoggerFactory.getLogger(BlueprintArchiveUtils::class.java) - - /** - * Create a new Zip from a root directory - * - * @param source the base directory - * @param destination the output filename - * @return True if OK - */ - fun compress(source: File, destination: File, archiveType: ArchiveType = ArchiveType.Zip): Boolean { - try { - if (!destination.parentFile.exists()) { - destination.parentFile.mkdirs() - } - destination.createNewFile() - val ignoreZipFiles = Predicate { path -> !path.endsWith(".zip") && !path.endsWith(".ZIP") } - FileOutputStream(destination).use { out -> - compressFolder(source.toPath(), out, archiveType, pathFilter = ignoreZipFiles) - } - } catch (e: Exception) { - log.error("Fail to compress folder($source) to path(${destination.path})", e) - return false - } - return true - } - - /** - * In-memory compress an entire folder. - */ - fun compressToBytes( - baseDir: Path, - archiveType: ArchiveType = ArchiveType.Zip, - compressionLevel: Int = Deflater.NO_COMPRESSION - ): ByteArray { - return compressFolder(baseDir, ByteArrayOutputStream(), archiveType, compressionLevel = compressionLevel) - .toByteArray() - } - - /** - * Compress an entire folder. - * - * @param baseDir path of base folder to be packaged. - * @param output the output stream - * @param pathFilter filter to ignore files based on its path. - * @param compressionLevel the wanted compression level. - * @param fixedModificationTime to force every entry to have this modification time. - * Useful for reproducible operations, like tests, for example. - */ - private fun compressFolder( - baseDir: Path, - output: T, - archiveType: ArchiveType, - pathFilter: Predicate = Predicates.alwaysTrue(), - compressionLevel: Int = Deflater.DEFAULT_COMPRESSION, - fixedModificationTime: Long? = null - ): T - where T : OutputStream { - val stream: ArchiveOutputStream = if (archiveType == ArchiveType.Zip) - ZipArchiveOutputStream(output).apply { setLevel(compressionLevel) } - else - TarArchiveOutputStream(GzipCompressorOutputStream(output)) - stream - .use { aos -> - Files.walkFileTree( - baseDir, - object : SimpleFileVisitor() { - @Throws(IOException::class) - override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { - if (pathFilter.test(file)) { - var archiveEntry: ArchiveEntry = aos.createArchiveEntry( - file.toFile(), - baseDir.relativize(file).toString() - ) - if (archiveType == ArchiveType.Zip) { - val entry = archiveEntry as ZipArchiveEntry - fixedModificationTime?.let { - entry.time = it - } - entry.time = 0 - } - aos.putArchiveEntry(archiveEntry) - Files.copy(file, aos) - aos.closeArchiveEntry() - } - return FileVisitResult.CONTINUE - } - - @Throws(IOException::class) - override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { - var archiveEntry: ArchiveEntry? - if (archiveType == ArchiveType.Zip) { - val entry = ZipArchiveEntry(baseDir.relativize(dir).toString() + "/") - fixedModificationTime?.let { - entry.time = it - } - archiveEntry = entry - } else - archiveEntry = TarArchiveEntry(baseDir.relativize(dir).toString() + "/") - aos.putArchiveEntry(archiveEntry) - aos.closeArchiveEntry() - return FileVisitResult.CONTINUE - } - } - ) - } - return output - } - - private fun getDefaultEncoding(): String? { - val bytes = byteArrayOf('D'.toByte()) - val inputStream: InputStream = ByteArrayInputStream(bytes) - val reader = InputStreamReader(inputStream) - return reader.encoding - } - - fun deCompress(archiveFile: File, targetPath: String, archiveType: ArchiveType = ArchiveType.Zip): File { - var enumeration: ArchiveEnumerator? = null - if (archiveType == ArchiveType.Zip) { - val zipArchive = ZipFile(archiveFile, getDefaultEncoding()) - enumeration = ArchiveEnumerator(zipArchive) - } else { // Tar Gz - var tarGzArchiveIs: InputStream = BufferedInputStream(archiveFile.inputStream()) - tarGzArchiveIs = GzipCompressorInputStream(tarGzArchiveIs) - val tarGzArchive: ArchiveInputStream = TarArchiveInputStream(tarGzArchiveIs) - enumeration = ArchiveEnumerator(tarGzArchive) - } - - enumeration.use { - while (enumeration!!.hasMoreElements()) { - val entry: ArchiveEntry? = enumeration.nextElement() - val destFilePath = File(targetPath, entry!!.name) - destFilePath.parentFile.mkdirs() - - if (entry!!.isDirectory) - continue - - val bufferedIs = BufferedInputStream(enumeration.getInputStream(entry)) - destFilePath.outputStream().buffered(1024).use { bos -> - bufferedIs.copyTo(bos) - } - - if (!enumeration.getHasSharedEntryInputStream()) - bufferedIs.close() - } - } - - val destinationDir = File(targetPath) - check(destinationDir.isDirectory && destinationDir.exists()) { - throw BlueprintProcessorException("failed to decompress blueprint(${archiveFile.absolutePath}) to ($targetPath) ") - } - - return destinationDir - } - } - - class ArchiveEnumerator : Enumeration, Closeable { - - private val zipArchive: ZipFile? - private val zipEnumeration: Enumeration? - private val archiveStream: ArchiveInputStream? - private var nextEntry: ArchiveEntry? = null - private val hasSharedEntryInputStream: Boolean - - constructor(zipFile: ZipFile) { - zipArchive = zipFile - zipEnumeration = zipFile.entries - archiveStream = null - hasSharedEntryInputStream = false - } - - constructor(archiveStream: ArchiveInputStream) { - this.archiveStream = archiveStream - zipArchive = null - zipEnumeration = null - hasSharedEntryInputStream = true - } - - fun getHasSharedEntryInputStream(): Boolean { - return hasSharedEntryInputStream - } - - fun getInputStream(entry: ArchiveEntry): InputStream? { - return if (zipArchive != null) - zipArchive?.getInputStream(entry as ZipArchiveEntry?) - else - archiveStream - } - - override fun hasMoreElements(): Boolean { - if (zipEnumeration != null) - return zipEnumeration?.hasMoreElements() - else if (archiveStream != null) { - nextEntry = archiveStream.nextEntry - if (nextEntry != null && !archiveStream.canReadEntryData(nextEntry)) - return hasMoreElements() - return nextEntry != null - } - return false - } - - override fun nextElement(): ArchiveEntry? { - if (zipEnumeration != null) - nextEntry = zipEnumeration.nextElement() - else if (archiveStream != null) { - if (nextEntry == null) - nextEntry = archiveStream.nextEntry - } - return nextEntry - } - - override fun close() { - if (zipArchive != null) - zipArchive.close() - else archiveStream?.close() - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtils.kt deleted file mode 100644 index 583709f08..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtils.kt +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import kotlinx.coroutines.runBlocking -import org.apache.commons.io.FileUtils -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode -import org.onap.ccsdk.cds.controllerblueprints.core.data.ImportDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.slf4j.LoggerFactory -import java.io.File -import java.io.FileFilter -import java.io.FileNotFoundException -import java.net.URL -import java.net.URLClassLoader -import java.nio.file.Files -import java.nio.file.NotDirectoryException -import java.nio.file.Path -import java.nio.file.Paths -import java.nio.file.StandardOpenOption - -class BlueprintFileUtils { - companion object { - - const val COMPILED_JAR_SUFFIX = "cba-kts.jar" - - private val log = LoggerFactory.getLogger(this::class.toString()) - - fun createEmptyBlueprint(basePath: String) { - - val blueprintDir = File(basePath) - FileUtils.deleteDirectory(blueprintDir) - - Files.createDirectories(blueprintDir.toPath()) - - val metaDataDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BlueprintConstants.TOSCA_METADATA_DIR)) - Files.createDirectories(metaDataDir.toPath()) - - val metaFile = File( - blueprintDir.absolutePath.plus(File.separator).plus( - BlueprintConstants - .TOSCA_METADATA_ENTRY_DEFINITION_FILE - ) - ) - Files.write(metaFile.toPath(), getMetaDataContent().toByteArray(), StandardOpenOption.CREATE_NEW) - - val definitionsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BlueprintConstants.TOSCA_DEFINITIONS_DIR)) - Files.createDirectories(definitionsDir.toPath()) - - val scriptsDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BlueprintConstants.TOSCA_SCRIPTS_DIR)) - Files.createDirectories(scriptsDir.toPath()) - - val plansDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BlueprintConstants.TOSCA_PLANS_DIR)) - Files.createDirectories(plansDir.toPath()) - - val templatesDir = File(blueprintDir.absolutePath.plus(File.separator).plus(BlueprintConstants.TOSCA_TEMPLATES_DIR)) - Files.createDirectories(templatesDir.toPath()) - } - - fun copyBlueprint(sourcePath: String, targetPath: String) { - val sourceFile = File(sourcePath) - val targetFile = File(targetPath) - sourceFile.copyRecursively(targetFile, true) - } - - fun deleteBlueprintTypes(basePath: String) { - val definitionPath = basePath.plus(File.separator).plus(BlueprintConstants.TOSCA_DEFINITIONS_DIR) - log.info("deleting definition types under : $definitionPath") - - val definitionDir = File(definitionPath) - // Find the Type Definitions - val fileFilter = FileFilter { pathname -> pathname.absolutePath.endsWith("_types.json") } - // Delete the Type Files - definitionDir.listFiles(fileFilter).forEach { - Files.deleteIfExists(it.toPath()) - } - } - - fun writeEnhancedBlueprint(blueprintContext: BlueprintContext) { - - // Write Blueprint Types - writeBlueprintTypes(blueprintContext) - // Re Populate the Imports - populateDefaultImports(blueprintContext) - // Rewrite the Entry Definition Files - writeEntryDefinitionFile(blueprintContext) - } - - fun writeBlueprintTypes(blueprintContext: BlueprintContext) { - - val basePath = blueprintContext.rootPath - val definitionPath = basePath.plus(File.separator).plus(BlueprintConstants.TOSCA_DEFINITIONS_DIR) - val definitionDir = File(definitionPath) - - check(definitionDir.exists()) { - throw BlueprintException( - ErrorCode.BLUEPRINT_PATH_MISSING.value, - "couldn't get definition file under " + - "path(${definitionDir.absolutePath})" - ) - } - - blueprintContext.serviceTemplate.dataTypes?.let { - val dataTypesContent = JacksonUtils.getWrappedJson(BlueprintConstants.PATH_DATA_TYPES, it.toSortedMap(), true) - writeTypeFile(definitionDir.absolutePath, BlueprintConstants.PATH_DATA_TYPES, dataTypesContent) - } - - blueprintContext.serviceTemplate.relationshipTypes?.let { - val nodeTypesContent = JacksonUtils.getWrappedJson(BlueprintConstants.PATH_RELATIONSHIP_TYPES, it.toSortedMap(), true) - writeTypeFile(definitionDir.absolutePath, BlueprintConstants.PATH_RELATIONSHIP_TYPES, nodeTypesContent) - } - - blueprintContext.serviceTemplate.artifactTypes?.let { - val artifactTypesContent = JacksonUtils.getWrappedJson(BlueprintConstants.PATH_ARTIFACT_TYPES, it.toSortedMap(), true) - writeTypeFile(definitionDir.absolutePath, BlueprintConstants.PATH_ARTIFACT_TYPES, artifactTypesContent) - } - - blueprintContext.serviceTemplate.nodeTypes?.let { - val nodeTypesContent = JacksonUtils.getWrappedJson(BlueprintConstants.PATH_NODE_TYPES, it.toSortedMap(), true) - writeTypeFile(definitionDir.absolutePath, BlueprintConstants.PATH_NODE_TYPES, nodeTypesContent) - } - - blueprintContext.serviceTemplate.policyTypes?.let { - val nodeTypesContent = JacksonUtils.getWrappedJson(BlueprintConstants.PATH_POLICY_TYPES, it.toSortedMap(), true) - writeTypeFile(definitionDir.absolutePath, BlueprintConstants.PATH_POLICY_TYPES, nodeTypesContent) - } - } - - private fun populateDefaultImports(blueprintContext: BlueprintContext) { - // Get the Default Types - val types = arrayListOf( - BlueprintConstants.PATH_DATA_TYPES, BlueprintConstants.PATH_RELATIONSHIP_TYPES, - BlueprintConstants.PATH_ARTIFACT_TYPES, BlueprintConstants.PATH_NODE_TYPES, - BlueprintConstants.PATH_POLICY_TYPES - ) - - // Clean Type Imports - cleanImportTypes(blueprintContext.serviceTemplate) - - val imports = mutableListOf() - types.forEach { typeName -> - val import = ImportDefinition() - import.file = BlueprintConstants.TOSCA_DEFINITIONS_DIR.plus("/$typeName.json") - imports.add(import) - } - - blueprintContext.serviceTemplate.imports = imports - } - - fun cleanImportTypes(serviceTemplate: ServiceTemplate) { - // Clean the Type imports - val toDeleteTypes = serviceTemplate.imports?.filter { - it.file.endsWith("_types.json") - } - - if (toDeleteTypes != null && toDeleteTypes.isNotEmpty()) { - serviceTemplate.imports?.removeAll(toDeleteTypes) - } - } - - /** - * Re Generate the Blueprint Service Template Definition file based on Blueprint Context. - */ - private fun writeEntryDefinitionFile(blueprintContext: BlueprintContext) { - - val absoluteEntryDefinitionFile = blueprintContext.rootPath.plus(File.separator).plus(blueprintContext.entryDefinition) - - val serviceTemplate = blueprintContext.serviceTemplate - - // Clone the Service Template - val writeServiceTemplate = serviceTemplate.clone() - writeServiceTemplate.dataTypes = null - writeServiceTemplate.artifactTypes = null - writeServiceTemplate.policyTypes = null - writeServiceTemplate.relationshipTypes = null - writeServiceTemplate.nodeTypes = null - - // Write the Service Template - writeDefinitionFile(absoluteEntryDefinitionFile, JacksonUtils.getJson(writeServiceTemplate, true)) - } - - fun writeDefinitionFile(definitionFileName: String, content: String) = runBlocking { - val definitionFile = File(definitionFileName) - // Delete the File If exists - Files.deleteIfExists(definitionFile.toPath()) - - Files.write(definitionFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) - check(definitionFile.exists()) { - throw BlueprintException( - ErrorCode.BLUEPRINT_WRITING_FAIL.value, - "couldn't write definition file under " + - "path(${definitionFile.absolutePath})" - ) - } - } - - private fun writeTypeFile(definitionPath: String, type: String, content: String) = runBlocking { - val typeFile = File(definitionPath.plus(File.separator).plus("$type.json")) - - Files.write(typeFile.toPath(), content.toByteArray(), StandardOpenOption.CREATE_NEW) - check(typeFile.exists()) { - throw BlueprintException( - ErrorCode.BLUEPRINT_WRITING_FAIL.value, - "couldn't write $type.json file under " + - "path(${typeFile.absolutePath})" - ) - } - } - - private fun getMetaDataContent(): String { - return "TOSCA-Meta-File-Version: 1.0.0" + - "\nCSAR-Version: " + - "\nCreated-By: " + - "\nEntry-Definitions: Definitions/.json" + - "\nTemplate-Name: " + - "\nTemplate-Version: " + - "\nTemplate-Type: " + - "\nTemplate-Tags: " - } - - fun getBlueprintFile(fileName: String, targetPath: Path): File { - val filePath = targetPath.resolve(fileName).toString() - val file = File(filePath) - check(file.exists()) { - throw BlueprintException( - ErrorCode.BLUEPRINT_PATH_MISSING.value, - "couldn't get definition file under " + - "path(${file.absolutePath})" - ) - } - return file - } - - fun getCbaStorageDirectory(path: String): Path { - check(StringUtils.isNotBlank(path)) { - throw BlueprintException( - ErrorCode.BLUEPRINT_PATH_MISSING.value, - "couldn't get " + - "Blueprint folder under path($path)" - ) - } - - val fileStorageLocation = Paths.get(path).toAbsolutePath().normalize() - - if (!Files.exists(fileStorageLocation)) - Files.createDirectories(fileStorageLocation) - - return fileStorageLocation - } - - fun compileCacheKey(basePath: String): String { - return normalizedPathName(basePath) - } - - private fun compileJarFileName(artifactName: String, artifactVersion: String): String { - return "$artifactName-$artifactVersion-$COMPILED_JAR_SUFFIX" - } - - fun compileJarFilePathName(basePath: String, artifactName: String, artifactVersion: String): String { - return normalizedPathName( - basePath, BlueprintConstants.TOSCA_SCRIPTS_KOTLIN_DIR, - compileJarFileName(artifactName, artifactVersion) - ) - } - - fun compileJarFile(basePath: String, artifactName: String, artifactVersion: String): File { - return normalizedFile( - compileJarFilePathName( - basePath, - artifactName, artifactVersion - ) - ) - } - - fun stripFileExtension(fileName: String): String { - val dotIndexe = fileName.lastIndexOf('.') - - // In case dot is in first position, we are dealing with a hidden file rather than an extension - return if (dotIndexe > 0) fileName.substring(0, dotIndexe) else fileName - } - - fun getURLClassLoaderFromDirectory(directory: File): URLClassLoader { - if (!directory.exists()) { - throw FileNotFoundException(directory.absolutePath) - } else if (!directory.isDirectory) { - throw NotDirectoryException(directory.absolutePath) - } - - val urls = arrayListOf() - directory.walkTopDown() - .filter { it.name.endsWith(COMPILED_JAR_SUFFIX) } - .forEach { - log.debug("Adding (${it.absolutePath}) to classLoader (${directory.absolutePath})") - - urls.add(it.toURI().toURL()) - } - return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader) - } - - fun getURLClassLoaderFromDirectory(path: String): URLClassLoader { - val directory = normalizedFile(path) - return getURLClassLoaderFromDirectory(directory) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtils.kt deleted file mode 100644 index c2e0ec39c..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtils.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -object BlueprintIOUtils { - - suspend fun retry( - times: Int = 1, - initialDelay: Long = 0, - delay: Long = 1000, - block: suspend (Int) -> T, - exceptionBlock: (e: Exception) -> Unit - ): T { - var currentDelay = initialDelay - val currentTimes = times - 1 - repeat(currentTimes) { count -> - try { - return block(count) - } catch (e: Exception) { - exceptionBlock(e) - } - kotlinx.coroutines.delay(currentDelay) - currentDelay = delay - } - return block(currentTimes) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtils.kt deleted file mode 100644 index ffaa9e72f..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtils.kt +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018-2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import com.fasterxml.jackson.databind.JsonNode -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintDefinitions -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintScriptsServiceImpl -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintImportService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService -import org.slf4j.LoggerFactory -import java.io.File -import java.util.Properties - -class BlueprintMetadataUtils { - companion object { - - private val log = LoggerFactory.getLogger(this::class.toString()) - - suspend fun toscaMetaData(basePath: String): ToscaMetaData { - val toscaMetaPath = basePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(BlueprintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) - return toscaMetaDataFromMetaFile(toscaMetaPath) - } - - suspend fun entryDefinitionFile(basePath: String): String { - val toscaMetaPath = basePath.plus(BlueprintConstants.PATH_DIVIDER) - .plus(BlueprintConstants.TOSCA_METADATA_ENTRY_DEFINITION_FILE) - return toscaMetaDataFromMetaFile(toscaMetaPath).entityDefinitions - } - - fun bluePrintEnvProperties(basePath: String): Properties { - val blueprintsEnvFilePath = basePath.plus(File.separator) - .plus(BlueprintConstants.TOSCA_ENVIRONMENTS_DIR) - return environmentFileProperties(blueprintsEnvFilePath) - } - - fun environmentFileProperties(pathName: String): Properties { - val properties = Properties() - val envDir = normalizedFile(pathName) - // Verify if the environment directory exists - if (envDir.exists() && envDir.isDirectory) { - // Find all available environment files - envDir.listFiles()!! - .filter { it.name.endsWith(".properties") } - .forEach { - val istream = it.inputStream() - properties.load(istream) - istream.close() - } - } - return properties - } - - private suspend fun toscaMetaDataFromMetaFile(metaFilePath: String): ToscaMetaData { - val toscaMetaData = ToscaMetaData() - val lines = normalizedFile(metaFilePath).readNBLines() - lines.forEach { line -> - if (line.contains(":")) { - val keyValue = line.split(":") - if (keyValue.size == 2) { - val value: String = keyValue[1].trim() - when (keyValue[0]) { - "TOSCA-Meta-File-Version" -> toscaMetaData.toscaMetaFileVersion = value - "CSAR-Version" -> toscaMetaData.csarVersion = value - "Created-By" -> toscaMetaData.createdBy = value - "Entry-Definitions" -> toscaMetaData.entityDefinitions = value - "Template-Name" -> toscaMetaData.templateName = value - "Template-Version" -> toscaMetaData.templateVersion = value - "Template-Tags" -> toscaMetaData.templateTags = value - "Template-Type" -> toscaMetaData.templateType = value - } - } - } - } - return toscaMetaData - } - - /** Get the default blueprint runtime for [id] and [blueprintBasePath] */ - suspend fun getBlueprintRuntime(id: String, blueprintBasePath: String): - BlueprintRuntimeService> { - val bluePrintContext: BlueprintContext = getBlueprintContext(blueprintBasePath) - return getBlueprintRuntime(id, bluePrintContext) - } - - /** Get the default blocking blueprint runtime api for [id] and [blueprintBasePath] used in testing */ - fun bluePrintRuntime(id: String, blueprintBasePath: String): - BlueprintRuntimeService> = runBlocking { - val bluePrintContext: BlueprintContext = getBlueprintContext(blueprintBasePath) - getBlueprintRuntime(id, bluePrintContext) - } - - /** Get the default blueprint runtime from [bluePrintContext] */ - fun getBlueprintRuntime(id: String, bluePrintContext: BlueprintContext): - BlueprintRuntimeService> { - checkNotEmpty(bluePrintContext.rootPath) { "blueprint context root path is missing." } - checkNotEmpty(bluePrintContext.entryDefinition) { "blueprint context entry definition is missing." } - val blueprintBasePath = bluePrintContext.rootPath - val bluePrintRuntimeService = DefaultBlueprintRuntimeService(id, bluePrintContext) - bluePrintRuntimeService.put( - BlueprintConstants.PROPERTY_BLUEPRINT_BASE_PATH, - blueprintBasePath.asJsonPrimitive() - ) - bluePrintRuntimeService.put(BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) - return bluePrintRuntimeService - } - - /** Get the blueprint runtime for enhancement start for [id] and [blueprintBasePath] */ - suspend fun getBaseEnhancementBlueprintRuntime(id: String, blueprintBasePath: String): - BlueprintRuntimeService> { - - val bluePrintContext: BlueprintContext = getBaseEnhancementBlueprintContext(blueprintBasePath) - - val bluePrintRuntimeService = DefaultBlueprintRuntimeService(id, bluePrintContext) - bluePrintRuntimeService.put( - BlueprintConstants.PROPERTY_BLUEPRINT_BASE_PATH, - blueprintBasePath.asJsonPrimitive() - ) - bluePrintRuntimeService.put(BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID, id.asJsonPrimitive()) - - return bluePrintRuntimeService - } - - /** Get the default blueprint runtime for enhancement start for [id], [blueprintBasePath] and [executionContext] */ - suspend fun getBlueprintRuntime( - id: String, - blueprintBasePath: String, - executionContext: MutableMap - ): - BlueprintRuntimeService> { - val bluePrintContext: BlueprintContext = getBlueprintContext(blueprintBasePath) - val bluePrintRuntimeService = DefaultBlueprintRuntimeService(id, bluePrintContext) - executionContext.forEach { - bluePrintRuntimeService.put(it.key, it.value) - } - - bluePrintRuntimeService.setExecutionContext(executionContext) - return bluePrintRuntimeService - } - - /** Get the default blueprint context for [blueprintBasePath]*/ - suspend fun getBlueprintContext(blueprintBasePath: String): BlueprintContext { - - val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) - - log.info( - "Reading blueprint type(${toscaMetaData.templateType}) path($blueprintBasePath) " + - "and entry definition file (${toscaMetaData.entityDefinitions})" - ) - - // If the EntryDefinition is Kotlin file, compile and get Service Template - val bluePrintContext = when (toscaMetaData.templateType.toUpperCase()) { - BlueprintConstants.BLUEPRINT_TYPE_KOTLIN_DSL -> readBlueprintKotlinFile( - toscaMetaData, - blueprintBasePath - ) - BlueprintConstants.BLUEPRINT_TYPE_GENERIC_SCRIPT -> readBlueprintGenericScript( - toscaMetaData, - blueprintBasePath - ) - BlueprintConstants.BLUEPRINT_TYPE_DEFAULT -> readBlueprintFile( - toscaMetaData.entityDefinitions, - blueprintBasePath - ) - else -> - throw BlueprintException( - "Unknown blueprint type(${toscaMetaData.templateType}), " + - "It should be any one of these types[${BlueprintConstants.BLUEPRINT_TYPE_KOTLIN_DSL}," + - "${BlueprintConstants.BLUEPRINT_TYPE_GENERIC_SCRIPT}, " + - "${BlueprintConstants.BLUEPRINT_TYPE_DEFAULT}]" - ) - } - // Copy the metadata info - copyMetaInfoToServiceTemplate(toscaMetaData, bluePrintContext.serviceTemplate) - - return bluePrintContext - } - - private suspend fun getBaseEnhancementBlueprintContext(blueprintBasePath: String): BlueprintContext { - val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath) - - // Clean Type files - BlueprintFileUtils.deleteBlueprintTypes(blueprintBasePath) - val rootFilePath: String = blueprintBasePath.plus(File.separator).plus(toscaMetaData.entityDefinitions) - val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) - - // Copy the metadata info - copyMetaInfoToServiceTemplate(toscaMetaData, rootServiceTemplate) - - // Clean the Import Definitions - BlueprintFileUtils.cleanImportTypes(rootServiceTemplate) - - val blueprintContext = BlueprintContext(rootServiceTemplate) - blueprintContext.rootPath = blueprintBasePath - blueprintContext.entryDefinition = toscaMetaData.entityDefinitions - return blueprintContext - } - - /** copy metadata defined in [toscaMetaData] to [serviceTemplate] */ - private fun copyMetaInfoToServiceTemplate(toscaMetaData: ToscaMetaData, serviceTemplate: ServiceTemplate) { - if (serviceTemplate.metadata == null) serviceTemplate.metadata = mutableMapOf() - val metadata = serviceTemplate.metadata!! - metadata[BlueprintConstants.METADATA_TEMPLATE_AUTHOR] = toscaMetaData.createdBy - metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] = toscaMetaData.templateName - metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] = toscaMetaData.templateVersion - metadata[BlueprintConstants.METADATA_TEMPLATE_TAGS] = toscaMetaData.templateTags - metadata[BlueprintConstants.METADATA_TEMPLATE_TYPE] = toscaMetaData.templateType - } - - private suspend fun readBlueprintFile(entityDefinitions: String, basePath: String): BlueprintContext { - val normalizedBasePath = normalizedPathName(basePath) - val rootFilePath = normalizedPathName(normalizedBasePath, entityDefinitions) - val rootServiceTemplate = ServiceTemplateUtils.getServiceTemplate(rootFilePath) - - // Recursively Import Template files - val schemaImportResolverUtils = BlueprintImportService(rootServiceTemplate, normalizedBasePath) - val completeServiceTemplate = schemaImportResolverUtils.getImportResolvedServiceTemplate() - val blueprintContext = BlueprintContext(completeServiceTemplate) - blueprintContext.rootPath = normalizedBasePath - blueprintContext.entryDefinition = entityDefinitions - return blueprintContext - } - - /** Reade the Service Template Definitions from the Kotlin file */ - private suspend fun readBlueprintKotlinFile(toscaMetaData: ToscaMetaData, basePath: String): BlueprintContext { - - val definitionClassName = toscaMetaData.entityDefinitions.removeSuffix(".kt") - val normalizedBasePath = normalizedPathName(basePath) - - val bluePrintScriptsService = BlueprintScriptsServiceImpl() - val bluePrintDefinitions = bluePrintScriptsService - .scriptInstance( - normalizedBasePath, toscaMetaData.templateName, - toscaMetaData.templateVersion, definitionClassName, false - ) - // Get the Service Template - val serviceTemplate = bluePrintDefinitions.serviceTemplate() - - // Clean the Default type import Definitions - BlueprintFileUtils.cleanImportTypes(serviceTemplate) - - val blueprintContext = BlueprintContext(serviceTemplate) - blueprintContext.rootPath = normalizedBasePath - blueprintContext.entryDefinition = toscaMetaData.entityDefinitions - blueprintContext.otherDefinitions = bluePrintDefinitions.otherDefinitions() - return blueprintContext - } - - /** Reade the Service Template Definitions from the generic script types */ - private fun readBlueprintGenericScript(toscaMetaData: ToscaMetaData, basePath: String): BlueprintContext { - return BlueprintContext(ServiceTemplate()) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintRuntimeUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintRuntimeUtils.kt deleted file mode 100644 index 1df185cf6..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintRuntimeUtils.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.slf4j.LoggerFactory - -/** - * - * - * @author Brinda Santh - */ -object BlueprintRuntimeUtils { - - private val log = LoggerFactory.getLogger(this::class.toString()) - - fun assignInputsFromFile(bluePrintContext: BlueprintContext, fileName: String, context: MutableMap) { - val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName) - return assignInputs(bluePrintContext, jsonNode, context) - } - - fun assignInputsFromClassPathFile( - bluePrintContext: BlueprintContext, - fileName: String, - context: MutableMap - ) { - val jsonNode = JacksonUtils.jsonNodeFromClassPathFile(fileName) - return assignInputs(bluePrintContext, jsonNode, context) - } - - fun assignInputsFromContent(bluePrintContext: BlueprintContext, content: String, context: MutableMap) { - val jsonNode: JsonNode = JacksonUtils.jsonNode(content) - return assignInputs(bluePrintContext, jsonNode, context) - } - - fun assignInputs(bluePrintContext: BlueprintContext, jsonNode: JsonNode, context: MutableMap) { - log.info("assignInputs from input JSON ({})", jsonNode.toString()) - bluePrintContext.inputs()?.forEach { propertyName, _ -> - val valueNode: JsonNode = jsonNode.at("/".plus(propertyName)) ?: NullNode.getInstance() - - val path = BlueprintConstants.PATH_INPUTS.plus(BlueprintConstants.PATH_DIVIDER).plus(propertyName) - log.trace("setting input path ({}), values ({})", path, valueNode) - context[path] = valueNode - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ClusterUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ClusterUtils.kt index cacfc2cd2..7fe955b03 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ClusterUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ClusterUtils.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import java.net.InetAddress object ClusterUtils { @@ -28,19 +28,19 @@ object ClusterUtils { } fun applicationName(): String { - return BlueprintConstants.APP_NAME + return BluePrintConstants.APP_NAME } fun clusterId(): String { - return System.getenv(BlueprintConstants.PROPERTY_CLUSTER_ID) ?: "cds-cluster" + return System.getenv(BluePrintConstants.PROPERTY_CLUSTER_ID) ?: "cds-cluster" } fun clusterNodeId(): String { - return System.getenv(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID) ?: "cds-controller-0" + return System.getenv(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID) ?: "cds-controller-0" } fun clusterNodeAddress(): String { - return System.getenv(BlueprintConstants.PROPERTY_CLUSTER_NODE_ADDRESS) + return System.getenv(BluePrintConstants.PROPERTY_CLUSTER_NODE_ADDRESS) ?: clusterNodeId() } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt index 14b308bc9..02dd2027d 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import java.text.SimpleDateFormat import java.time.LocalDateTime import java.time.ZoneId @@ -31,19 +31,19 @@ fun controllerDate(): Date { fun currentTimestamp(): String { val localDateTime = LocalDateTime.now(ZoneId.systemDefault()) - val formatter = DateTimeFormatter.ofPattern(BlueprintConstants.DATE_TIME_PATTERN) + val formatter = DateTimeFormatter.ofPattern(BluePrintConstants.DATE_TIME_PATTERN) return formatter.format(localDateTime) } /** Parse string date in CDS string format */ fun String.toControllerDate(): Date { - val formatter = SimpleDateFormat(BlueprintConstants.DATE_TIME_PATTERN) + val formatter = SimpleDateFormat(BluePrintConstants.DATE_TIME_PATTERN) return formatter.parse(this) } /** Return date to CDS string format */ fun Date.currentTimestamp(): String { - val formatter = SimpleDateFormat(BlueprintConstants.DATE_TIME_PATTERN) + val formatter = SimpleDateFormat(BluePrintConstants.DATE_TIME_PATTERN) return formatter.format(this) } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt index 1110f6f34..ace66cf7a 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt @@ -33,10 +33,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.apache.commons.io.IOUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.readNBText import java.io.File @@ -76,7 +76,7 @@ class JacksonUtils { try { normalizedFile(fileName).readNBText() } catch (e: Exception) { - throw BlueprintException("couldn't get file ($fileName) content : ${e.message}") + throw BluePrintException("couldn't get file ($fileName) content : ${e.message}") } } @@ -191,13 +191,13 @@ class JacksonUtils { fun getInstanceFromMap(properties: MutableMap, classType: Class): T { return readValue(getJson(properties), classType) - ?: throw BlueprintProcessorException("failed to transform content ($properties) to type ($classType)") + ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)") } fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean { - if (BlueprintTypes.validPrimitiveTypes().contains(type.toLowerCase())) { + if (BluePrintTypes.validPrimitiveTypes().contains(type.toLowerCase())) { return checkJsonNodeValueOfPrimitiveType(type, jsonNode) - } else if (BlueprintTypes.validCollectionTypes().contains(type)) { + } else if (BluePrintTypes.validCollectionTypes().contains(type)) { return checkJsonNodeValueOfCollectionType(type, jsonNode) } return false @@ -205,31 +205,31 @@ class JacksonUtils { fun checkIfPrimitiveType(primitiveType: String): Boolean { return when (primitiveType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_STRING -> true - BlueprintConstants.DATA_TYPE_BOOLEAN -> true - BlueprintConstants.DATA_TYPE_INTEGER -> true - BlueprintConstants.DATA_TYPE_FLOAT -> true - BlueprintConstants.DATA_TYPE_DOUBLE -> true - BlueprintConstants.DATA_TYPE_TIMESTAMP -> true + BluePrintConstants.DATA_TYPE_STRING -> true + BluePrintConstants.DATA_TYPE_BOOLEAN -> true + BluePrintConstants.DATA_TYPE_INTEGER -> true + BluePrintConstants.DATA_TYPE_FLOAT -> true + BluePrintConstants.DATA_TYPE_DOUBLE -> true + BluePrintConstants.DATA_TYPE_TIMESTAMP -> true else -> false } } fun checkJsonNodeValueOfPrimitiveType(primitiveType: String, jsonNode: JsonNode): Boolean { return when (primitiveType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_STRING -> jsonNode.isTextual - BlueprintConstants.DATA_TYPE_BOOLEAN -> jsonNode.isBoolean - BlueprintConstants.DATA_TYPE_INTEGER -> jsonNode.isInt - BlueprintConstants.DATA_TYPE_FLOAT -> jsonNode.isDouble - BlueprintConstants.DATA_TYPE_DOUBLE -> jsonNode.isDouble - BlueprintConstants.DATA_TYPE_TIMESTAMP -> jsonNode.isTextual + BluePrintConstants.DATA_TYPE_STRING -> jsonNode.isTextual + BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNode.isBoolean + BluePrintConstants.DATA_TYPE_INTEGER -> jsonNode.isInt + BluePrintConstants.DATA_TYPE_FLOAT -> jsonNode.isDouble + BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNode.isDouble + BluePrintConstants.DATA_TYPE_TIMESTAMP -> jsonNode.isTextual else -> false } } fun checkJsonNodeValueOfCollectionType(type: String, jsonNode: JsonNode): Boolean { return when (type.toLowerCase()) { - BlueprintConstants.DATA_TYPE_LIST -> jsonNode.isArray + BluePrintConstants.DATA_TYPE_LIST -> jsonNode.isArray else -> false } } @@ -247,62 +247,62 @@ class JacksonUtils { fun getValue(value: Any, type: String): Any { return when (type.toLowerCase()) { - BlueprintConstants.DATA_TYPE_BOOLEAN -> (value as BooleanNode).booleanValue() - BlueprintConstants.DATA_TYPE_INTEGER -> (value as IntNode).intValue() - BlueprintConstants.DATA_TYPE_FLOAT -> (value as FloatNode).floatValue() - BlueprintConstants.DATA_TYPE_DOUBLE -> (value as DoubleNode).doubleValue() - BlueprintConstants.DATA_TYPE_STRING -> (value as TextNode).textValue() + BluePrintConstants.DATA_TYPE_BOOLEAN -> (value as BooleanNode).booleanValue() + BluePrintConstants.DATA_TYPE_INTEGER -> (value as IntNode).intValue() + BluePrintConstants.DATA_TYPE_FLOAT -> (value as FloatNode).floatValue() + BluePrintConstants.DATA_TYPE_DOUBLE -> (value as DoubleNode).doubleValue() + BluePrintConstants.DATA_TYPE_STRING -> (value as TextNode).textValue() else -> (value as JsonNode) } } fun populatePrimitiveValues(key: String, value: JsonNode, primitiveType: String, objectNode: ObjectNode) { when (primitiveType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_BOOLEAN, - BlueprintConstants.DATA_TYPE_INTEGER, - BlueprintConstants.DATA_TYPE_FLOAT, - BlueprintConstants.DATA_TYPE_DOUBLE, - BlueprintConstants.DATA_TYPE_TIMESTAMP, - BlueprintConstants.DATA_TYPE_STRING, - BlueprintConstants.DATA_TYPE_NULL -> + BluePrintConstants.DATA_TYPE_BOOLEAN, + BluePrintConstants.DATA_TYPE_INTEGER, + BluePrintConstants.DATA_TYPE_FLOAT, + BluePrintConstants.DATA_TYPE_DOUBLE, + BluePrintConstants.DATA_TYPE_TIMESTAMP, + BluePrintConstants.DATA_TYPE_STRING, + BluePrintConstants.DATA_TYPE_NULL -> objectNode.set(key, value) - else -> throw BlueprintException("populatePrimitiveValues expected only primitive values! Received: ($value)") + else -> throw BluePrintException("populatePrimitiveValues expected only primitive values! Received: ($value)") } } fun populatePrimitiveValues(value: JsonNode, primitiveType: String, arrayNode: ArrayNode) { when (primitiveType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_BOOLEAN, - BlueprintConstants.DATA_TYPE_INTEGER, - BlueprintConstants.DATA_TYPE_FLOAT, - BlueprintConstants.DATA_TYPE_DOUBLE, - BlueprintConstants.DATA_TYPE_TIMESTAMP, - BlueprintConstants.DATA_TYPE_STRING, - BlueprintConstants.DATA_TYPE_NULL -> + BluePrintConstants.DATA_TYPE_BOOLEAN, + BluePrintConstants.DATA_TYPE_INTEGER, + BluePrintConstants.DATA_TYPE_FLOAT, + BluePrintConstants.DATA_TYPE_DOUBLE, + BluePrintConstants.DATA_TYPE_TIMESTAMP, + BluePrintConstants.DATA_TYPE_STRING, + BluePrintConstants.DATA_TYPE_NULL -> arrayNode.add(value) - else -> throw BlueprintException("populatePrimitiveValues expected only primitive values! Received: ($value)") + else -> throw BluePrintException("populatePrimitiveValues expected only primitive values! Received: ($value)") } } fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) { val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) - ?: throw BlueprintException("populatePrimitiveDefaultValues expected only primitive values! Received type ($primitiveType)") + ?: throw BluePrintException("populatePrimitiveDefaultValues expected only primitive values! Received type ($primitiveType)") objectNode.set(key, defaultValue) } fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) { val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(primitiveType) - ?: throw BlueprintException("populatePrimitiveDefaultValuesForArrayNode expected only primitive values! Received type ($primitiveType)") + ?: throw BluePrintException("populatePrimitiveDefaultValuesForArrayNode expected only primitive values! Received type ($primitiveType)") arrayNode.add(defaultValue) } private fun getDefaultValueOfPrimitiveAsJsonNode(primitiveType: String): JsonNode? { return when (primitiveType.toLowerCase()) { - BlueprintConstants.DATA_TYPE_BOOLEAN -> BooleanNode.valueOf(false) - BlueprintConstants.DATA_TYPE_INTEGER -> IntNode.valueOf(0) - BlueprintConstants.DATA_TYPE_FLOAT -> FloatNode.valueOf(0.0f) - BlueprintConstants.DATA_TYPE_DOUBLE -> DoubleNode.valueOf(0.0) - BlueprintConstants.DATA_TYPE_STRING -> MissingNode.getInstance() + BluePrintConstants.DATA_TYPE_BOOLEAN -> BooleanNode.valueOf(false) + BluePrintConstants.DATA_TYPE_INTEGER -> IntNode.valueOf(0) + BluePrintConstants.DATA_TYPE_FLOAT -> FloatNode.valueOf(0.0f) + BluePrintConstants.DATA_TYPE_DOUBLE -> DoubleNode.valueOf(0.0) + BluePrintConstants.DATA_TYPE_STRING -> MissingNode.getInstance() else -> null } } @@ -310,7 +310,7 @@ class JacksonUtils { fun populateJsonNodeValues(key: String, nodeValue: JsonNode?, type: String, objectNode: ObjectNode) { if (nodeValue == null || nodeValue is NullNode) { objectNode.set(key, nodeValue) - } else if (BlueprintTypes.validPrimitiveTypes().contains(type)) { + } else if (BluePrintTypes.validPrimitiveTypes().contains(type)) { populatePrimitiveValues(key, nodeValue, type, objectNode) } else { objectNode.set(key, nodeValue) @@ -319,11 +319,11 @@ class JacksonUtils { fun convertPrimitiveResourceValue(type: String, value: String): JsonNode { return when (type.toLowerCase()) { - BlueprintConstants.DATA_TYPE_BOOLEAN -> jsonNodeFromObject(value.toBoolean()) - BlueprintConstants.DATA_TYPE_INTEGER -> jsonNodeFromObject(value.toInt()) - BlueprintConstants.DATA_TYPE_FLOAT -> jsonNodeFromObject(value.toFloat()) - BlueprintConstants.DATA_TYPE_DOUBLE -> jsonNodeFromObject(value.toDouble()) - BlueprintConstants.DATA_TYPE_STRING -> jsonNodeFromObject(value) + BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNodeFromObject(value.toBoolean()) + BluePrintConstants.DATA_TYPE_INTEGER -> jsonNodeFromObject(value.toInt()) + BluePrintConstants.DATA_TYPE_FLOAT -> jsonNodeFromObject(value.toFloat()) + BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNodeFromObject(value.toDouble()) + BluePrintConstants.DATA_TYPE_STRING -> jsonNodeFromObject(value) else -> getJsonNode(value) } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtils.kt index 1a082d353..48319325c 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtils.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.LOG_PROTECT +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.LOG_PROTECT import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition class PropertyDefinitionUtils { diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt index 1b8af5897..c0204af8d 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty import org.slf4j.LoggerFactory import java.io.File @@ -56,7 +56,7 @@ object ResourceResolverUtils { // FIXME("Convert into reactive") return JacksonUtils.getContent(resolvedFileName) } catch (e: Exception) { - throw BlueprintException(e, "failed to file (%s), basePath (%s) ", filename, basePath) + throw BluePrintException(e, "failed to file (%s), basePath (%s) ", filename, basePath) } } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt index 6ebe7c11a..fea637f61 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow @@ -36,10 +36,10 @@ object WorkflowGraphUtils { } } graph.startNodes().forEach { rootNode -> - graph.addEdge(BlueprintConstants.GRAPH_START_NODE_NAME, rootNode.id, EdgeLabel.SUCCESS) + graph.addEdge(BluePrintConstants.GRAPH_START_NODE_NAME, rootNode.id, EdgeLabel.SUCCESS) } graph.endNodes().forEach { endNode -> - graph.addEdge(endNode.id, BlueprintConstants.GRAPH_END_NODE_NAME, EdgeLabel.SUCCESS) + graph.addEdge(endNode.id, BluePrintConstants.GRAPH_END_NODE_NAME, EdgeLabel.SUCCESS) } return graph } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript new file mode 100644 index 000000000..e69de29bb diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BlueprintKotlinScript b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BlueprintKotlinScript deleted file mode 100644 index e69de29bb..000000000 diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt new file mode 100644 index 000000000..167c0381a --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt @@ -0,0 +1,33 @@ +package org.onap.ccsdk.cds.controllerblueprints.core + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class BluePrintErrorTest { + + @Test + fun testBluePrintErrorIsCreatedWithemptyList() { + val bluePrintError = BluePrintError() + + assertTrue(bluePrintError.allErrors().isEmpty()) + } + + @Test + fun testAddErrorWith3Params() { + val bluePrintError = BluePrintError() + + bluePrintError.addError("type", "name", "error", "step") + + assertEquals("type : name : error", bluePrintError.stepErrors("step")!![0]) + } + + @Test + fun testAddErrorWith2Params() { + val bluePrintError = BluePrintError() + + bluePrintError.addError("error", "step") + + assertEquals("error", bluePrintError.stepErrors("step")!![0]) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintErrorTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintErrorTest.kt deleted file mode 100644 index 94ba98603..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintErrorTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package org.onap.ccsdk.cds.controllerblueprints.core - -import org.junit.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class BlueprintErrorTest { - - @Test - fun testBlueprintErrorIsCreatedWithemptyList() { - val bluePrintError = BlueprintError() - - assertTrue(bluePrintError.allErrors().isEmpty()) - } - - @Test - fun testAddErrorWith3Params() { - val bluePrintError = BlueprintError() - - bluePrintError.addError("type", "name", "error", "step") - - assertEquals("type : name : error", bluePrintError.stepErrors("step")!![0]) - } - - @Test - fun testAddErrorWith2Params() { - val bluePrintError = BlueprintError() - - bluePrintError.addError("error", "step") - - assertEquals("error", bluePrintError.stepErrors("step")!![0]) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt index 8c1e9f65f..7ac9b8649 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt @@ -95,13 +95,13 @@ class CustomFunctionsTest { val returnValueBool: JsonNode = false.asJsonType() assertFalse(returnValueBool.asBoolean()) - val returnValue: JsonNode = BlueprintError().asJsonType() + val returnValue: JsonNode = BluePrintError().asJsonType() assertEquals(JsonNodeType.OBJECT, returnValue.getNodeType()) } @Test fun testMapAsObjectNode() { - val returnValue: ObjectNode = hashMapOf("test" to BlueprintError()).asObjectNode() + val returnValue: ObjectNode = hashMapOf("test" to BluePrintError()).asObjectNode() assertNotNull(returnValue.get("test")) } @@ -121,7 +121,7 @@ class CustomFunctionsTest { assertNull(returnValueString) } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testCastValue() { val initMap: Map = hashMapOf("test" to 1.1) val returnValue = initMap.castValue("test", Number::class) @@ -178,7 +178,7 @@ class CustomFunctionsTest { assertTrue("[{\"key\": \"value\"},{\"key\": \"value\"}]".asJsonType().isComplexType()) } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testRootFieldsToMap() { 1.asJsonType().rootFieldsToMap() } @@ -192,7 +192,7 @@ class CustomFunctionsTest { assertEquals(3, mutMap["hello"]?.asInt()) } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testMapGetAsString() { val initMap = hashMapOf("test" to "hello".asJsonType()) @@ -201,7 +201,7 @@ class CustomFunctionsTest { initMap.getAsString("test2") } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testMapGetAsBoolean() { val initMap = hashMapOf("test" to true.asJsonType()) @@ -210,7 +210,7 @@ class CustomFunctionsTest { initMap.getAsBoolean("test2") } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testMapGetAsInt() { val initMap = hashMapOf("test" to 1.asJsonType()) @@ -219,7 +219,7 @@ class CustomFunctionsTest { initMap.getAsInt("test2") } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testCheckEquals() { assertTrue(checkEquals("hello", "hello", { -> "error" })) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt index 0fe2fbf7f..643549be0 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt @@ -41,14 +41,14 @@ class MDCContextTest { @Test fun testContextCanBePassedBetweenCoroutines() { - MDC.put(BlueprintConstants.ONAP_REQUEST_ID, "12345") + MDC.put(BluePrintConstants.ONAP_REQUEST_ID, "12345") runBlocking { GlobalScope.launch { - assertEquals(null, MDC.get(BlueprintConstants.ONAP_REQUEST_ID)) + assertEquals(null, MDC.get(BluePrintConstants.ONAP_REQUEST_ID)) } launch(MDCContext()) { assertEquals( - "12345", MDC.get(BlueprintConstants.ONAP_REQUEST_ID), + "12345", MDC.get(BluePrintConstants.ONAP_REQUEST_ID), "couldn't get request id" ) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt new file mode 100644 index 000000000..a75262f96 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt @@ -0,0 +1,119 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.annotations + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asBluePrintsDataTypes +import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap +import kotlin.test.Test +import kotlin.test.assertNotNull + +class BluePrintsAnnotationsTest { + + @Test + fun testBluePrintWorkflowData() { + val wfInput = TestBluePrintsWorkflowInput::class.asPropertyDefinitionMap() + // println(wfInput.asJsonString(true)) + assertNotNull(wfInput, "failed to generate wfInput property map") + + val wfOutput = TestBluePrintsWorkflowOutput::class.asPropertyDefinitionMap() + // println(wfOutput.asJsonString(true)) + assertNotNull(wfInput, "failed to generate wfOutput property map") + } + + @Test + fun testBluePrintDataType() { + val dataTypes = TestBluePrintsDataType::class.asBluePrintsDataTypes() + // println(dataTypes.asJsonString(true)) + assertNotNull(dataTypes, "failed to generate dataTypes definition") + } +} + +@BluePrintsDataType( + name = "dt-test-datatype", description = "I am test", + version = "1.0.0", derivedFrom = "tosca.datatypes.root" +) +data class TestBluePrintsDataType( + @BluePrintsProperty(description = "this stringData") + var stringData: String, + @BluePrintsProperty(description = "this stringDataWithValue") + @PropertyDefaultValue(value = "USA") + val stringDataWithValue: String, + @BluePrintsProperty(description = "this intDataWithValue") + @PropertyDefaultValue(value = "30") + val intDataWithValue: Int, + @BluePrintsProperty(description = "this booleanDataWithValue") + @PropertyDefaultValue(value = "true") + val booleanDataWithValue: Boolean, + @BluePrintsProperty(description = "this anyData") + val anyData: Any, + @BluePrintsProperty(description = "this jsonDataWithValue") + @PropertyDefaultValue(value = """{"data" : "1234"}""") + val jsonDataWithValue: JsonNode?, + @BluePrintsProperty(description = "listData") + val listData: MutableList, + @BluePrintsProperty(description = "this mapData") + val mapData: MutableMap = hashMapOf(), + @BluePrintsProperty(description = "this complexData") + val complexData: TestBluePrintsChildDataType?, + @BluePrintsProperty(description = "this complexDataList") + val complexDataList: MutableList +) + +data class TestBluePrintsChildDataType(val name: String) + +@BluePrintsWorkflowInput +data class TestBluePrintsWorkflowInput( + @BluePrintsProperty(description = "this sample name") + @PropertyDefaultValue(value = "Brinda") + var name: String, + @BluePrintsProperty(description = "this sample name") + val place: String +) + +@BluePrintsWorkflowOutput +data class TestBluePrintsWorkflowOutput( + @BluePrintsProperty(description = "this is dslExpression") + @DSLExpression("field1") + var dslExpression: String, + + @BluePrintsProperty(description = "this is withNodeAttributeExpression") + @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data") + var withNodeAttributeExpression: String, + + @BluePrintsProperty(description = "this is withNodeAttributeExpressionSubAttribute") + @AttributeExpression( + modelableEntityName = "sample-node", attributeName = "response-data", + subAttributeName = ".\$field1" + ) + var withNodeAttributeExpressionSubAttribute: String, + + @BluePrintsProperty(description = "this is withAttributeExpressionSubAttribute") + @AttributeExpression(attributeName = "response-data", subAttributeName = ".\$field1") + var withAttributeExpressionSubAttribute: String, + + @BluePrintsProperty(description = "this is withAttributeExpression") + @AttributeExpression(attributeName = "response-data") + var withAttributeExpression: String, + + @BluePrintsProperty(description = "this is withAArtifactExpression") + @ArtifactExpression(modelableEntityName = "test-node", artifactName = "content-template") + var withAArtifactExpression: String, + + @BluePrintsProperty(description = "this status") + val status: String = "success" +) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotationsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotationsTest.kt deleted file mode 100644 index b19c3502a..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BlueprintsAnnotationsTest.kt +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.annotations - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.asBlueprintsDataTypes -import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap -import kotlin.test.Test -import kotlin.test.assertNotNull - -class BlueprintsAnnotationsTest { - - @Test - fun testBlueprintWorkflowData() { - val wfInput = TestBlueprintsWorkflowInput::class.asPropertyDefinitionMap() - // println(wfInput.asJsonString(true)) - assertNotNull(wfInput, "failed to generate wfInput property map") - - val wfOutput = TestBlueprintsWorkflowOutput::class.asPropertyDefinitionMap() - // println(wfOutput.asJsonString(true)) - assertNotNull(wfInput, "failed to generate wfOutput property map") - } - - @Test - fun testBlueprintDataType() { - val dataTypes = TestBlueprintsDataType::class.asBlueprintsDataTypes() - // println(dataTypes.asJsonString(true)) - assertNotNull(dataTypes, "failed to generate dataTypes definition") - } -} - -@BlueprintsDataType( - name = "dt-test-datatype", description = "I am test", - version = "1.0.0", derivedFrom = "tosca.datatypes.root" -) -data class TestBlueprintsDataType( - @BlueprintsProperty(description = "this stringData") - var stringData: String, - @BlueprintsProperty(description = "this stringDataWithValue") - @PropertyDefaultValue(value = "USA") - val stringDataWithValue: String, - @BlueprintsProperty(description = "this intDataWithValue") - @PropertyDefaultValue(value = "30") - val intDataWithValue: Int, - @BlueprintsProperty(description = "this booleanDataWithValue") - @PropertyDefaultValue(value = "true") - val booleanDataWithValue: Boolean, - @BlueprintsProperty(description = "this anyData") - val anyData: Any, - @BlueprintsProperty(description = "this jsonDataWithValue") - @PropertyDefaultValue(value = """{"data" : "1234"}""") - val jsonDataWithValue: JsonNode?, - @BlueprintsProperty(description = "listData") - val listData: MutableList, - @BlueprintsProperty(description = "this mapData") - val mapData: MutableMap = hashMapOf(), - @BlueprintsProperty(description = "this complexData") - val complexData: TestBlueprintsChildDataType?, - @BlueprintsProperty(description = "this complexDataList") - val complexDataList: MutableList -) - -data class TestBlueprintsChildDataType(val name: String) - -@BlueprintsWorkflowInput -data class TestBlueprintsWorkflowInput( - @BlueprintsProperty(description = "this sample name") - @PropertyDefaultValue(value = "Brinda") - var name: String, - @BlueprintsProperty(description = "this sample name") - val place: String -) - -@BlueprintsWorkflowOutput -data class TestBlueprintsWorkflowOutput( - @BlueprintsProperty(description = "this is dslExpression") - @DSLExpression("field1") - var dslExpression: String, - - @BlueprintsProperty(description = "this is withNodeAttributeExpression") - @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data") - var withNodeAttributeExpression: String, - - @BlueprintsProperty(description = "this is withNodeAttributeExpressionSubAttribute") - @AttributeExpression( - modelableEntityName = "sample-node", attributeName = "response-data", - subAttributeName = ".\$field1" - ) - var withNodeAttributeExpressionSubAttribute: String, - - @BlueprintsProperty(description = "this is withAttributeExpressionSubAttribute") - @AttributeExpression(attributeName = "response-data", subAttributeName = ".\$field1") - var withAttributeExpressionSubAttribute: String, - - @BlueprintsProperty(description = "this is withAttributeExpression") - @AttributeExpression(attributeName = "response-data") - var withAttributeExpression: String, - - @BlueprintsProperty(description = "this is withAArtifactExpression") - @ArtifactExpression(modelableEntityName = "test-node", artifactName = "content-template") - var withAArtifactExpression: String, - - @BlueprintsProperty(description = "this status") - val status: String = "success" -) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt new file mode 100644 index 000000000..f2d95cdc6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt @@ -0,0 +1,318 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.dsl + +import com.fasterxml.jackson.databind.JsonNode +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType +import kotlin.test.assertNotNull + +class BluePrintDSLTest { + + @Test + fun testOperationDSLWorkflow() { + + val blueprint = blueprint( + "sample-bp", "1.0.0", + "brindasanth@onap.com", "sample, blueprints" + ) { + + artifactType(BluePrintTypes.artifactTypeTemplateVelocity()) + + // For New Component Definition + component( + "resource-resolution", "component-script-executor", "1.0.0", + "Resource Resolution component." + ) { + implementation(180) + // Attributes ( Properties which will be set during execution) + attribute("template1-data", "string", true, "") + + // Properties + property("string-value1", "string", true, "sample") + property("string-value2", "string", true, getInput("key-1")) + // Inputs + input("json-content", "json", true, """{ "name" : "cds"}""") + input("template-content", "string", true, getArtifact("template1")) + // Outputs + output("self-attribute-expression", "json", true, getAttribute("template1-data")) + // Artifacts + artifact("template1", "artifact-template-velocity", "Templates/template1.vtl") + } + + // Already definitions Registered Components + registryComponent( + "activate-restconf", "component-resource-resolution", "1.0.0", + "RestconfExecutor", "Resource Resolution component." + ) { + implementation(180) + // Properties + property("string-value1", "data") + // Inputs + input("json-content", """{ "name" : "cds"}""") + // Outputs + output("self-attribute-expression", getAttribute("template1-data")) + // Artifacts + artifact("template2", "artifact-template-velocity", "Templates/template1.vtl") + } + + workflow("resource-resolution-process", "Resource Resolution wf") { + input("json-content", "json", true, "") + input("key-1", "string", true, "") + output("status", "string", true, "success") + step("resource-resolution-call", "resource-resolution", "Resource Resolution component invoke") + } + } + assertNotNull(blueprint.components, "failed to get components") + assertNotNull(blueprint.workflows, "failed to get workflows") + // println(blueprint.asJsonString(true)) + + val serviceTemplateGenerator = BluePrintServiceTemplateGenerator(blueprint) + val serviceTemplate = serviceTemplateGenerator.serviceTemplate() + assertNotNull(serviceTemplate.topologyTemplate, "failed to get service topology template") + // println(serviceTemplate.asJsonString(true)) + } + + @Test + fun testServiceTemplate() { + val serviceTemplate = serviceTemplate( + "sample-bp", "1.0.0", + "brindasanth@onap.com", "sample, blueprints" + ) { + metadata("release", "1806") + import("Definition/data_types.json") + dsl("rest-endpoint", """{ "selector" : "odl-selector"}""") + dsl("db-endpoint", """{ "selector" : "db-selector"}""") + + nodeTypeComponent() + nodeTypeResourceSource() + nodeTypeVnf() + + artifactTypeTemplateVelocity() + artifactTypeTempleJinja() + artifactTypeScriptKotlin() + artifactTypeMappingResource() + artifactTypeComponentJar() + artifactTypeK8sProfileFolder() + artifactTypeK8sConfigFolder() + + relationshipTypeConnectsTo() + relationshipTypeDependsOn() + relationshipTypeHostedOn() + + topologyTemplate { + nodeTemplateOperation( + nodeTemplateName = "activate", type = "sample-node-type", interfaceName = "RestconfExecutor", + description = "sample activation" + ) { + implementation(360, "SELF") { + primary("Scripts/sample.py") + dependencies("one", "two") + } + inputs { + property("json-content", """{ "name" : "cds"}""") + property("array-content", """["controller", "blueprints"]""") + property("int-value", 234) + property("boolean-value", true) + property("string-value", "sample") + property("input-expression", getInput("key-1")) + property("self-property-expression", getProperty("key-1")) + property("self-artifact-expression", getArtifact("key-1")) + property("other-artifact-expression", getNodeTemplateArtifact("node-1", "key-1")) + } + outputs { + property("self-attribute-expression", getAttribute("key-1")) + } + } + // Other way of defining Node Template with artifacts, implementation + nodeTemplate("resolve", "sample-resolve-type", "Resource Resolution") { + operation("ResourceResolutionExecutor", "") { + implementation(180) + inputs { + property("boolean-value", true) + property("string-value", "sample") + } + outputs { + property("resolve-expression", getAttribute("key-1")) + } + } + artifact("sample-template", "artifact-velocity", "Templates/sample-template.vtl") + } + + workflow("resource-resolution", "to resolve resources") { + step("resource-resolution-call", "resolve", "Resource Resolution component invoke") + } + // Alternate way to define workflow + workflow("activate", "to resolve resources") { + // Alternate step definition + step("netconf-activate-call", "activate", "call activation component") { + success("END") + failure("END") + } + inputs { + property("request-content", "json", true) + } + outputs { + property("response-content", "json", true) { + value(getAttribute("key-1")) + defaultValue("""{ "status" : "success"}""".jsonAsJsonType()) + } + } + } + } + } + + // println(serviceTemplate.asJsonString(true)) + assertNotNull(serviceTemplate.artifactTypes, "failed to get artifactTypes") + assertNotNull(serviceTemplate.nodeTypes, "failed to get nodeTypes") + assertNotNull(serviceTemplate.relationshipTypes, "failed to get relationshipTypes") + assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") + assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates, "failed to get nodeTypes") + assertNotNull( + serviceTemplate.topologyTemplate?.nodeTemplates!!["activate"], + "failed to get nodeTypes(activate)" + ) + } + + @Test + fun testNodeTypePropertyConstrains() { + val nodeType = nodeType("data-node", "1.0.0", "tosca.Nodes.root", "") { + property("ip-address", "string", true, "") { + defaultValue("127.0.0.1") + constrain { + validValues(arrayListOf("""127.0.0.1""".asJsonPrimitive())) + length(10) + maxLength(20) + minLength(10) + } + } + property("disk-space", "string", true, "") { + defaultValue(10) + constrain { + validValues("""["200KB", "400KB"]""") + equal("200KB") + inRange("""["100KB", "500KB" ]""") + maxLength("10MB") + minLength("10KB") + } + constrain { + validValues("""[ 200, 400]""") + greaterOrEqual("10KB") + greaterThan("20KB") + lessOrEqual("200KB") + lessThan("190KB") + } + } + } + assertNotNull(nodeType, "failed to get nodeType") + // println(nodeType.asJsonString(true)) + } + + @Test + fun testServiceTemplateWorkflow() { + val serviceTemplate = serviceTemplate( + "sample-bp", "1.0.0", + "brindasanth@onap.com", "sample, blueprints" + ) { + topologyTemplate { + workflowNodeTemplate("activate", "component-resource-resolution", "") { + operation("ResourceResolutionExecutor", "") { + inputs { + property("string-value", "sample") + } + } + } + } + } + assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") + assertNotNull(serviceTemplate.topologyTemplate?.workflows?.get("activate"), "failed to get workflow(activate)") + // println(serviceTemplate.asJsonString(true)) + } + + @Test + fun testNodeTemplateOperationTypes() { + + val testNodeTemplateInstance = BluePrintTypes.nodeTemplateComponentTestExecutor( + id = "test-node-template", + description = "" + ) { + definedProperties { + prop1("i am property1") + prop2("i am property2") + } + definedOperation("") { + implementation(360) + inputs { + request("i am request") + } + outputs { + response(getAttribute("attribute1")) + } + } + } + assertNotNull(testNodeTemplateInstance, "failed to get test node template") + // println(testNodeTemplateInstance.asJsonString(true)) + } +} + +fun BluePrintTypes.nodeTemplateComponentTestExecutor( + id: String, + description: String, + block: TestNodeTemplateOperationImplBuilder.() -> Unit +): + NodeTemplate { + return TestNodeTemplateOperationImplBuilder(id, description).apply(block).build() + } + +class TestNodeTemplateOperationImplBuilder(id: String, description: String) : + AbstractNodeTemplateOperationImplBuilder( + id, "component-test-executor", + "ComponentTestExecutor", + description + ) + +class TestProperty : PropertiesAssignmentBuilder() { + + fun prop1(prop1: String) { + property("prop1", prop1.asJsonPrimitive()) + } + + fun prop2(prop2: String) { + property("prop2", prop2.asJsonPrimitive()) + } +} + +class TestInput : PropertiesAssignmentBuilder() { + + fun request(request: String) { + property("request", request.asJsonPrimitive()) + } +} + +class TestOutput : PropertiesAssignmentBuilder() { + + fun response(response: String) { + response(response.asJsonPrimitive()) + } + + fun response(response: JsonNode) { + property("response", response) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLTest.kt deleted file mode 100644 index 57f671dc4..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLTest.kt +++ /dev/null @@ -1,318 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.dsl - -import com.fasterxml.jackson.databind.JsonNode -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType -import kotlin.test.assertNotNull - -class BlueprintDSLTest { - - @Test - fun testOperationDSLWorkflow() { - - val blueprint = blueprint( - "sample-bp", "1.0.0", - "brindasanth@onap.com", "sample, blueprints" - ) { - - artifactType(BlueprintTypes.artifactTypeTemplateVelocity()) - - // For New Component Definition - component( - "resource-resolution", "component-script-executor", "1.0.0", - "Resource Resolution component." - ) { - implementation(180) - // Attributes ( Properties which will be set during execution) - attribute("template1-data", "string", true, "") - - // Properties - property("string-value1", "string", true, "sample") - property("string-value2", "string", true, getInput("key-1")) - // Inputs - input("json-content", "json", true, """{ "name" : "cds"}""") - input("template-content", "string", true, getArtifact("template1")) - // Outputs - output("self-attribute-expression", "json", true, getAttribute("template1-data")) - // Artifacts - artifact("template1", "artifact-template-velocity", "Templates/template1.vtl") - } - - // Already definitions Registered Components - registryComponent( - "activate-restconf", "component-resource-resolution", "1.0.0", - "RestconfExecutor", "Resource Resolution component." - ) { - implementation(180) - // Properties - property("string-value1", "data") - // Inputs - input("json-content", """{ "name" : "cds"}""") - // Outputs - output("self-attribute-expression", getAttribute("template1-data")) - // Artifacts - artifact("template2", "artifact-template-velocity", "Templates/template1.vtl") - } - - workflow("resource-resolution-process", "Resource Resolution wf") { - input("json-content", "json", true, "") - input("key-1", "string", true, "") - output("status", "string", true, "success") - step("resource-resolution-call", "resource-resolution", "Resource Resolution component invoke") - } - } - assertNotNull(blueprint.components, "failed to get components") - assertNotNull(blueprint.workflows, "failed to get workflows") - // println(blueprint.asJsonString(true)) - - val serviceTemplateGenerator = BlueprintServiceTemplateGenerator(blueprint) - val serviceTemplate = serviceTemplateGenerator.serviceTemplate() - assertNotNull(serviceTemplate.topologyTemplate, "failed to get service topology template") - // println(serviceTemplate.asJsonString(true)) - } - - @Test - fun testServiceTemplate() { - val serviceTemplate = serviceTemplate( - "sample-bp", "1.0.0", - "brindasanth@onap.com", "sample, blueprints" - ) { - metadata("release", "1806") - import("Definition/data_types.json") - dsl("rest-endpoint", """{ "selector" : "odl-selector"}""") - dsl("db-endpoint", """{ "selector" : "db-selector"}""") - - nodeTypeComponent() - nodeTypeResourceSource() - nodeTypeVnf() - - artifactTypeTemplateVelocity() - artifactTypeTempleJinja() - artifactTypeScriptKotlin() - artifactTypeMappingResource() - artifactTypeComponentJar() - artifactTypeK8sProfileFolder() - artifactTypeK8sConfigFolder() - - relationshipTypeConnectsTo() - relationshipTypeDependsOn() - relationshipTypeHostedOn() - - topologyTemplate { - nodeTemplateOperation( - nodeTemplateName = "activate", type = "sample-node-type", interfaceName = "RestconfExecutor", - description = "sample activation" - ) { - implementation(360, "SELF") { - primary("Scripts/sample.py") - dependencies("one", "two") - } - inputs { - property("json-content", """{ "name" : "cds"}""") - property("array-content", """["controller", "blueprints"]""") - property("int-value", 234) - property("boolean-value", true) - property("string-value", "sample") - property("input-expression", getInput("key-1")) - property("self-property-expression", getProperty("key-1")) - property("self-artifact-expression", getArtifact("key-1")) - property("other-artifact-expression", getNodeTemplateArtifact("node-1", "key-1")) - } - outputs { - property("self-attribute-expression", getAttribute("key-1")) - } - } - // Other way of defining Node Template with artifacts, implementation - nodeTemplate("resolve", "sample-resolve-type", "Resource Resolution") { - operation("ResourceResolutionExecutor", "") { - implementation(180) - inputs { - property("boolean-value", true) - property("string-value", "sample") - } - outputs { - property("resolve-expression", getAttribute("key-1")) - } - } - artifact("sample-template", "artifact-velocity", "Templates/sample-template.vtl") - } - - workflow("resource-resolution", "to resolve resources") { - step("resource-resolution-call", "resolve", "Resource Resolution component invoke") - } - // Alternate way to define workflow - workflow("activate", "to resolve resources") { - // Alternate step definition - step("netconf-activate-call", "activate", "call activation component") { - success("END") - failure("END") - } - inputs { - property("request-content", "json", true) - } - outputs { - property("response-content", "json", true) { - value(getAttribute("key-1")) - defaultValue("""{ "status" : "success"}""".jsonAsJsonType()) - } - } - } - } - } - - // println(serviceTemplate.asJsonString(true)) - assertNotNull(serviceTemplate.artifactTypes, "failed to get artifactTypes") - assertNotNull(serviceTemplate.nodeTypes, "failed to get nodeTypes") - assertNotNull(serviceTemplate.relationshipTypes, "failed to get relationshipTypes") - assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") - assertNotNull(serviceTemplate.topologyTemplate?.nodeTemplates, "failed to get nodeTypes") - assertNotNull( - serviceTemplate.topologyTemplate?.nodeTemplates!!["activate"], - "failed to get nodeTypes(activate)" - ) - } - - @Test - fun testNodeTypePropertyConstrains() { - val nodeType = nodeType("data-node", "1.0.0", "tosca.Nodes.root", "") { - property("ip-address", "string", true, "") { - defaultValue("127.0.0.1") - constrain { - validValues(arrayListOf("""127.0.0.1""".asJsonPrimitive())) - length(10) - maxLength(20) - minLength(10) - } - } - property("disk-space", "string", true, "") { - defaultValue(10) - constrain { - validValues("""["200KB", "400KB"]""") - equal("200KB") - inRange("""["100KB", "500KB" ]""") - maxLength("10MB") - minLength("10KB") - } - constrain { - validValues("""[ 200, 400]""") - greaterOrEqual("10KB") - greaterThan("20KB") - lessOrEqual("200KB") - lessThan("190KB") - } - } - } - assertNotNull(nodeType, "failed to get nodeType") - // println(nodeType.asJsonString(true)) - } - - @Test - fun testServiceTemplateWorkflow() { - val serviceTemplate = serviceTemplate( - "sample-bp", "1.0.0", - "brindasanth@onap.com", "sample, blueprints" - ) { - topologyTemplate { - workflowNodeTemplate("activate", "component-resource-resolution", "") { - operation("ResourceResolutionExecutor", "") { - inputs { - property("string-value", "sample") - } - } - } - } - } - assertNotNull(serviceTemplate.topologyTemplate, "failed to get topology template") - assertNotNull(serviceTemplate.topologyTemplate?.workflows?.get("activate"), "failed to get workflow(activate)") - // println(serviceTemplate.asJsonString(true)) - } - - @Test - fun testNodeTemplateOperationTypes() { - - val testNodeTemplateInstance = BlueprintTypes.nodeTemplateComponentTestExecutor( - id = "test-node-template", - description = "" - ) { - definedProperties { - prop1("i am property1") - prop2("i am property2") - } - definedOperation("") { - implementation(360) - inputs { - request("i am request") - } - outputs { - response(getAttribute("attribute1")) - } - } - } - assertNotNull(testNodeTemplateInstance, "failed to get test node template") - // println(testNodeTemplateInstance.asJsonString(true)) - } -} - -fun BlueprintTypes.nodeTemplateComponentTestExecutor( - id: String, - description: String, - block: TestNodeTemplateOperationImplBuilder.() -> Unit -): - NodeTemplate { - return TestNodeTemplateOperationImplBuilder(id, description).apply(block).build() - } - -class TestNodeTemplateOperationImplBuilder(id: String, description: String) : - AbstractNodeTemplateOperationImplBuilder( - id, "component-test-executor", - "ComponentTestExecutor", - description - ) - -class TestProperty : PropertiesAssignmentBuilder() { - - fun prop1(prop1: String) { - property("prop1", prop1.asJsonPrimitive()) - } - - fun prop2(prop2: String) { - property("prop2", prop2.asJsonPrimitive()) - } -} - -class TestInput : PropertiesAssignmentBuilder() { - - fun request(request: String) { - property("request", request.asJsonPrimitive()) - } -} - -class TestOutput : PropertiesAssignmentBuilder() { - - fun response(response: String) { - response(response.asJsonPrimitive()) - } - - fun response(response: JsonNode) { - property("response", response) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt new file mode 100644 index 000000000..0803d921b --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt @@ -0,0 +1,88 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.scripts + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDefinitions +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import kotlin.script.experimental.jvm.util.classpathFromClass +import kotlin.script.experimental.jvm.util.classpathFromClassloader +import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty +import kotlin.test.assertNotNull + +class BluePrintScriptsServiceImplTest { + + private fun viewClassPathInfo() { + + println(" *********** classpathFromClass *********** ") + classpathFromClass( + BluePrintScriptsServiceImplTest::class.java.classLoader, + BluePrintScriptsServiceImplTest::class + )!! + .forEach(::println) + + println(" *********** classpathFromClassloader *********** ") + classpathFromClassloader(BluePrintScriptsServiceImplTest::class.java.classLoader)!! + .forEach(::println) + + println(" *********** classpathFromClasspathProperty *********** ") + classpathFromClasspathProperty()!! + .forEach(::println) + } + + @Test + fun testCachedService() { + runBlocking { + + val bluePrintScriptsService = BluePrintScriptsServiceImpl() + + val basePath = normalizedPathName("src/test/resources/compile") + + /** Load the Definitions */ + val bluePrintDefinitions = bluePrintScriptsService + .scriptInstance( + basePath, + "cba.scripts.ActivateBlueprintDefinitions", true + ) + assertNotNull(bluePrintDefinitions, "failed to get blueprint definitions") + + val serviceTemplate = bluePrintDefinitions.serviceTemplate() + assertNotNull(serviceTemplate, "failed to get service template") + + val customDataType = bluePrintDefinitions.otherDefinition("datatype-custom-datatype") + assertNotNull(customDataType, "failed to get custom definitions") + + val instance = bluePrintScriptsService + .scriptInstance>( + basePath, + "cba.scripts.SampleBlueprintFunctionNode", false + ) + assertNotNull(instance, "failed to get compiled instance") + + val cachedInstance = bluePrintScriptsService + .scriptInstance>( + basePath, + "cba.scripts.SampleBlueprintFunctionNode", false + ) + assertNotNull(cachedInstance, "failed to get cached compile instance") + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImplTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImplTest.kt deleted file mode 100644 index 7dd980dc7..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BlueprintScriptsServiceImplTest.kt +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.scripts - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintDefinitions -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import kotlin.script.experimental.jvm.util.classpathFromClass -import kotlin.script.experimental.jvm.util.classpathFromClassloader -import kotlin.script.experimental.jvm.util.classpathFromClasspathProperty -import kotlin.test.assertNotNull - -class BlueprintScriptsServiceImplTest { - - private fun viewClassPathInfo() { - - println(" *********** classpathFromClass *********** ") - classpathFromClass( - BlueprintScriptsServiceImplTest::class.java.classLoader, - BlueprintScriptsServiceImplTest::class - )!! - .forEach(::println) - - println(" *********** classpathFromClassloader *********** ") - classpathFromClassloader(BlueprintScriptsServiceImplTest::class.java.classLoader)!! - .forEach(::println) - - println(" *********** classpathFromClasspathProperty *********** ") - classpathFromClasspathProperty()!! - .forEach(::println) - } - - @Test - fun testCachedService() { - runBlocking { - - val bluePrintScriptsService = BlueprintScriptsServiceImpl() - - val basePath = normalizedPathName("src/test/resources/compile") - - /** Load the Definitions */ - val bluePrintDefinitions = bluePrintScriptsService - .scriptInstance( - basePath, - "cba.scripts.ActivateBlueprintDefinitions", true - ) - assertNotNull(bluePrintDefinitions, "failed to get blueprint definitions") - - val serviceTemplate = bluePrintDefinitions.serviceTemplate() - assertNotNull(serviceTemplate, "failed to get service template") - - val customDataType = bluePrintDefinitions.otherDefinition("datatype-custom-datatype") - assertNotNull(customDataType, "failed to get custom definitions") - - val instance = bluePrintScriptsService - .scriptInstance>( - basePath, - "cba.scripts.SampleBlueprintFunctionNode", false - ) - assertNotNull(instance, "failed to get compiled instance") - - val cachedInstance = bluePrintScriptsService - .scriptInstance>( - basePath, - "cba.scripts.SampleBlueprintFunctionNode", false - ) - assertNotNull(cachedInstance, "failed to get cached compile instance") - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt new file mode 100644 index 000000000..38f6ea2ec --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt @@ -0,0 +1,588 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.ObjectMapper +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * + * + * @author Brinda Santh + */ +class BluePrintContextTest { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + val blueprintBasePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG + + @Test + fun testBluePrintContextCreation() { + runBlocking { + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(blueprintBasePath) + assertNotNull(bluePrintContext, "Failed to populate Blueprint context") + } + } + + @Test + fun testChainedProperty() { + runBlocking { + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(blueprintBasePath) + val nodeType = bluePrintContext.nodeTypeChained("component-resource-resolution") + assertNotNull(nodeType, "Failed to get chained node type") + log.trace("Properties {}", JacksonUtils.getJson(nodeType, true)) + } + } + + @Test + fun testImports() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.imports = mutableListOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.imports()!!.isEmpty()) + + serviceTemplate.imports = null + assertNull(bluePrintContext.imports()) + } + + @Test + fun testDataTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.dataTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.dataTypes()!!.isEmpty()) + + serviceTemplate.dataTypes = null + assertNull(bluePrintContext.dataTypes()) + } + + @Test + fun testInputs() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.inputs = mutableMapOf() + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.inputs()!!.isEmpty()) + + topologyTemplate.inputs = null + + assertNull(bluePrintContext.inputs()) + } + + @Test + fun testBluePrintJson() { + val serviceTemplate = ServiceTemplate() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("{\"tosca_definitions_version\":\"controller_blueprint_1_0_0\"}", bluePrintContext.blueprintJson()) + } + + @Test(expected = BluePrintException::class) + fun testName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_NAME to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.name()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.name() + } + + @Test(expected = BluePrintException::class) + fun testVersion() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_VERSION to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.version()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.version() + } + + @Test(expected = BluePrintException::class) + fun testAuthor() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.metadata = mutableMapOf(BluePrintConstants.METADATA_TEMPLATE_AUTHOR to "hello") + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.author()) + + serviceTemplate.metadata = mutableMapOf() + val bluePrintContext2 = BluePrintContext(serviceTemplate) + bluePrintContext2.author() + } + + @Test + fun testWorkflows() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.workflows = mutableMapOf() + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.workflows()!!.isEmpty()) + + topologyTemplate.workflows = null + assertNull(bluePrintContext.workflows()) + } + + @Test(expected = BluePrintException::class) + fun testWorkFlowsByName() { + val topologyTemplate = TopologyTemplate() + topologyTemplate.workflows = mutableMapOf("workflow" to Workflow()) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.workflowByName("workflow")) + + bluePrintContext.workflowByName("") + } + + @Test + fun testWorkflowInput() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + workflow.inputs = mutableMapOf() + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.workflowInputs("workflow")!!.isEmpty()) + + workflow.inputs = null + + assertNull(bluePrintContext.workflowInputs("workflow")) + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepByName() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + workflow.steps = mutableMapOf("step" to Step()) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.workflowStepByName("workflow", "step")) + + bluePrintContext.workflowStepByName("workflow", "") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepNodeTemplate() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + step.target = "hello" + workflow.steps = mutableMapOf("step" to step) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowStepNodeTemplate("workflow", "step")) + + bluePrintContext.workflowStepNodeTemplate("workflow", "") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowFirstStepNodeTemplate() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + step.target = "hello" + workflow.steps = mutableMapOf("step" to step, "step2" to Step()) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowFirstStepNodeTemplate("workflow")) + + workflow.steps = null + bluePrintContext.workflowFirstStepNodeTemplate("workflow") + } + + @Test(expected = BluePrintException::class) + fun testWorkflowStepFirstCallOperation() { + val topologyTemplate = TopologyTemplate() + val workflow = Workflow() + val step = Step() + val activity = Activity() + activity.callOperation = "hello" + step.activities = arrayListOf(activity) + workflow.steps = mutableMapOf("step" to step) + topologyTemplate.workflows = mutableMapOf("workflow" to workflow) + val serviceTemplate = ServiceTemplate() + serviceTemplate.topologyTemplate = topologyTemplate + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.workflowStepFirstCallOperation("workflow", "step")) + + bluePrintContext.workflowStepFirstCallOperation("workflow", "") + } + + @Test + fun testDatatypeByName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.dataTypes = mutableMapOf("data" to DataType()) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.dataTypeByName("data")) + assertNull(bluePrintContext.dataTypeByName("")) + } + + @Test + fun testArtifactTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.artifactTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.artifactTypes()!!.isEmpty()) + + serviceTemplate.artifactTypes = null + assertNull(bluePrintContext.artifactTypes()) + } + + @Test + fun testPolicyTypes() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.policyTypes = mutableMapOf() + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.policyTypes()!!.isEmpty()) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypes()) + } + + @Test(expected = BluePrintException::class) + fun testPolicyTypeByName() { + val serviceTemplate = ServiceTemplate() + serviceTemplate.policyTypes = mutableMapOf("policy" to PolicyType()) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.policyTypeByName("policy")) + + bluePrintContext.policyTypeByName("") + } + + @Test + fun testPolicyTypesDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.derivedFrom = "hi" + val policyType2 = PolicyType() + policyType2.derivedFrom = "hello" + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesDerivedFrom("hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesDerivedFrom("hi")) + } + + @Test + fun testPolicyTypesTarget() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.targets = mutableListOf("hi") + val policyType2 = PolicyType() + policyType2.targets = mutableListOf() + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesTarget("hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesTarget("hi")) + } + + @Test + fun testPolicyTypesTargetNDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val policyType = PolicyType() + policyType.targets = mutableListOf("hi") + policyType.derivedFrom = "hi" + val policyType2 = PolicyType() + policyType2.targets = mutableListOf() + policyType2.derivedFrom = "hi" + serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")!!.size) + + serviceTemplate.policyTypes = null + assertNull(bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")) + } + + @Test + fun testNodeTypeDerivedFrom() { + val serviceTemplate = ServiceTemplate() + val nodeType = NodeType() + nodeType.derivedFrom = "hi" + val nodeType2 = NodeType() + nodeType2.derivedFrom = "hiii" + serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType, "node2" to nodeType2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.nodeTypeDerivedFrom("hi")!!.size) + + serviceTemplate.nodeTypes = null + assertNull(bluePrintContext.nodeTypeDerivedFrom("hi")) + } + + @Test(expected = BluePrintException::class) + fun testInterfaceNameForNodeType() { + val serviceTemplate = ServiceTemplate() + val nodeType = NodeType() + nodeType.interfaces = mutableMapOf("hello" to InterfaceDefinition(), "hi" to InterfaceDefinition()) + serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("hello", bluePrintContext.interfaceNameForNodeType("node")) + + bluePrintContext.interfaceNameForNodeType("") + } + + @Test + fun testNodeTemplateForNodeType() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.type = "hello" + val nodeTemplate2 = NodeTemplate() + nodeTemplate2.type = "hi" + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = + mutableMapOf("node" to nodeTemplate, "node2" to nodeTemplate2) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals(1, bluePrintContext.nodeTemplateForNodeType("hello")!!.size) + + serviceTemplate.topologyTemplate!!.nodeTemplates = null + assertNull(bluePrintContext.nodeTemplateForNodeType("hello")) + } + + @Test + fun testNodeTemplateProperty() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateProperty("node", "prop")) + + assertNull(bluePrintContext.nodeTemplateProperty("node", "")) + + nodeTemplate.properties = null + assertNull(bluePrintContext.nodeTemplateProperty("node", "prop")) + } + + @Test + fun testNodeTemplateArtifacts() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.artifacts = mutableMapOf() + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertTrue(bluePrintContext.nodeTemplateArtifacts("node")!!.isEmpty()) + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateArtifact() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.artifacts = mutableMapOf("art" to ArtifactDefinition()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateArtifact("node", "art")) + + bluePrintContext.nodeTemplateArtifact("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateArtifactForArtifactType() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val artifactDefinition = ArtifactDefinition() + artifactDefinition.type = "type" + val artifactDefinition2 = ArtifactDefinition() + artifactDefinition2.type = "No type" + nodeTemplate.artifacts = mutableMapOf("art" to artifactDefinition, "art2" to artifactDefinition2) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateArtifactForArtifactType("node", "type")) + + bluePrintContext.nodeTemplateArtifactForArtifactType("", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterface() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateFirstInterface("node")) + + nodeTemplate.interfaces = null + bluePrintContext.nodeTemplateFirstInterface("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterfaceName() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("interface", bluePrintContext.nodeTemplateFirstInterfaceName("node")) + + nodeTemplate.interfaces = null + bluePrintContext.nodeTemplateFirstInterfaceName("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateFirstInterfaceFirstOperationName() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val interfaceAssignment = InterfaceAssignment() + interfaceAssignment.operations = mutableMapOf("op" to OperationAssignment(), "op2" to OperationAssignment()) + nodeTemplate.interfaces = mutableMapOf("intf" to interfaceAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertEquals("op", bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node")) + + interfaceAssignment.operations = null + bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateCapability() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.capabilities = mutableMapOf("cap" to CapabilityAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateCapability("node", "cap")) + + bluePrintContext.nodeTemplateCapability("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateRequirement() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + nodeTemplate.requirements = mutableMapOf("req" to RequirementAssignment()) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateRequirement("node", "req")) + + bluePrintContext.nodeTemplateRequirement("node", "") + } + + @Test(expected = BluePrintException::class) + fun testNodeTemplateRequirementNode() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val requirementAssignment = RequirementAssignment() + requirementAssignment.node = "node" + nodeTemplate.requirements = mutableMapOf("req" to requirementAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateRequirementNode("node", "req")) + + bluePrintContext.nodeTemplateRequirementNode("node", "") + } + + @Test + fun testNodeTemplateCapabilityProperty() { + val serviceTemplate = ServiceTemplate() + val nodeTemplate = NodeTemplate() + val capabilityAssignment = CapabilityAssignment() + capabilityAssignment.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) + nodeTemplate.capabilities = mutableMapOf("cap" to capabilityAssignment) + serviceTemplate.topologyTemplate = TopologyTemplate() + serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) + + assertNotNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) + + capabilityAssignment.properties = null + + assertNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt new file mode 100644 index 000000000..4f645270d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt @@ -0,0 +1,140 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +/** + * + * + * @author Brinda Santh + */ +class BluePrintExpressionServiceTest { + + @Test + fun testInputExpression() { + val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_input\" : \"input-name\" }") + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.inputExpression, " Failed to populate input expression data") + assertEquals("input-name", expressionData.inputExpression?.propertyName, "Failed to get propertyName from expression data") + } + + @Test + fun testPropertyExpression() { + val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"property-name\"] }") + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.propertyExpression, " Failed to populate property expression data") + assertEquals("SELF", expressionData.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("property-name", expressionData.propertyExpression?.propertyName, " Failed to get expected propertyName") + + val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"\",\"property-name\", \"resource\", \"name\"] }") + val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1) + assertNotNull(expressionData1, " Failed to populate expression data") + assertEquals(expressionData1.isExpression, true, "Failed to identify as nested property expression") + assertNotNull(expressionData1.propertyExpression, " Failed to populate nested property expression data") + assertEquals("SELF", expressionData1.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("property-name", expressionData1.propertyExpression?.propertyName, " Failed to get expected propertyName") + assertEquals( + "resource.name", + expressionData1.propertyExpression?.subPropertyName, + " Failed to populate nested subPropertyName expression data" + ) + } + + @Test + fun testAttributeExpression() { + val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"resource\"] }") + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.attributeExpression, " Failed to populate attribute expression data") + assertEquals("SELF", expressionData.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("resource", expressionData.attributeExpression?.attributeName, " Failed to get expected attributeName") + + val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"\",\"attribute-name\", \"resource\", \"name\"] }") + val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1) + assertNotNull(expressionData1, " Failed to populate expression data") + assertEquals(expressionData1.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData1.attributeExpression, " Failed to populate attribute expression data") + assertEquals("SELF", expressionData1.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("attribute-name", expressionData1.attributeExpression?.attributeName, " Failed to get expected attributeName") + assertEquals( + "resource.name", + expressionData1.attributeExpression?.subAttributeName, + " Failed to populate nested subAttributeName expression data" + ) + } + + @Test + fun testOutputOperationExpression() { + val node: JsonNode = + jacksonObjectMapper().readTree("{ \"get_operation_output\": [\"SELF\", \"interface-name\", \"operation-name\", \"output-property-name\"] }") + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.operationOutputExpression, " Failed to populate output expression data") + assertEquals("SELF", expressionData.operationOutputExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("interface-name", expressionData.operationOutputExpression?.interfaceName, " Failed to get expected interfaceName") + assertEquals("operation-name", expressionData.operationOutputExpression?.operationName, " Failed to get expected operationName") + assertEquals("output-property-name", expressionData.operationOutputExpression?.propertyName, " Failed to get expected propertyName") + } + + @Test + fun testArtifactExpression() { + val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\"] }") + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.artifactExpression, " Failed to populate Artifact expression data") + assertEquals("SELF", expressionData.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("artifact-template", expressionData.artifactExpression?.artifactName, " Failed to get expected artifactName") + + val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\", \"location\", true] }") + val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1) + assertNotNull(expressionData1, " Failed to populate expression data") + assertEquals(expressionData1.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData1.artifactExpression, " Failed to populate Artifact expression data") + assertEquals("SELF", expressionData1.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName") + assertEquals("artifact-template", expressionData1.artifactExpression?.artifactName, " Failed to get expected artifactName") + assertEquals("location", expressionData1.artifactExpression?.location, " Failed to get expected location") + assertEquals(true, expressionData1.artifactExpression?.remove, " Failed to get expected remove") + } + + @Test + fun testDSLExpression() { + val node: JsonNode = "*dynamic-rest-source".asJsonPrimitive() + val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node) + assertNotNull(expressionData, " Failed to populate expression data") + assertEquals(expressionData.isExpression, true, "Failed to identify as expression") + assertNotNull(expressionData.dslExpression, " Failed to populate dsl expression data") + assertEquals( + "dynamic-rest-source", expressionData.dslExpression!!.propertyName, + " Failed to populate dsl property name" + ) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt new file mode 100644 index 000000000..265175165 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt @@ -0,0 +1,58 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import kotlin.test.assertNotNull + +/** + * BluePrintRepoFileServiceTest + * @author Brinda Santh + * + */ +class BluePrintRepoFileServiceTest { + + private val basePath = TestConstants.PATH_TEST_DEFINITION_TYPE_STARTER + private val bluePrintRepoFileService = BluePrintRepoFileService(basePath) + + @Test + fun testGetDataType() { + val dataType = bluePrintRepoFileService.getDataType("dt-v4-aggregate") + assertNotNull(dataType, "Failed to get DataType from repo") + } + + @Test + fun testGetNodeType() { + val nodeType = bluePrintRepoFileService.getNodeType("component-resource-resolution") + assertNotNull(nodeType, "Failed to get NodeType from repo") + } + + @Test + fun testGetArtifactType() { + val nodeType = bluePrintRepoFileService.getArtifactType("artifact-template-velocity") + assertNotNull(nodeType, "Failed to get ArtifactType from repo") + } + + @Test(expected = BluePrintException::class) + fun testModelNotFound() { + val dataType = bluePrintRepoFileService.getDataType("dt-not-found") + assertNotNull(dataType, "Failed to get DataType from repo") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt new file mode 100644 index 000000000..4fcbb2d98 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt @@ -0,0 +1,299 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.NullNode +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintRuntimeUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +/** + * + * + * @author Brinda Santh + */ +class BluePrintRuntimeServiceTest { + + private val log = LoggerFactory.getLogger(this::class.toString()) + + @Test + fun `test Resolve NodeTemplate Properties`() { + log.info("************************ testResolveNodeTemplateProperties **********************") + + val bluePrintRuntimeService = getBluePrintRuntimeService() + + val inputDataPath = "src/test/resources/data/default-context.json" + + val inputNode: JsonNode = JacksonUtils.jsonNodeFromFile(inputDataPath) + bluePrintRuntimeService.assignInputs(inputNode) + + val propContext: MutableMap = bluePrintRuntimeService + .resolveNodeTemplateProperties("activate-process") + + assertNotNull(propContext, "Failed to populate interface property values") + } + + @Test + fun `test Resolve Relationship Properties`() { + log.info("************************ testResolveRelationshipTemplateProperties **********************") + + val bluePrintRuntimeService = getBluePrintRuntimeService() + + val inputDataPath = "src/test/resources/data/default-context.json" + + val inputNode: JsonNode = JacksonUtils.jsonNodeFromFile(inputDataPath) + bluePrintRuntimeService.assignInputs(inputNode) + + val propContext: MutableMap = bluePrintRuntimeService + .resolveRelationshipTemplateProperties("cli-device-properties") + + assertNotNull(propContext, "Failed to populate relationship property values") + assertEquals( + "localhost".asJsonPrimitive(), + propContext["connection-config"]!!.get("host"), + "failed to resolve expression" + ) + } + + @Test + fun `test resolve NodeTemplate Capability Properties`() { + log.info("************************ testResolveNodeTemplateRequirementProperties **********************") + val bluePrintRuntimeService = getBluePrintRuntimeService() + + val executionContext = bluePrintRuntimeService.getExecutionContext() + + BluePrintRuntimeUtils.assignInputsFromClassPathFile( + bluePrintRuntimeService.bluePrintContext(), + "data/default-context.json", executionContext + ) + + val assignmentParams = "{\n" + + " \"ipAddress\": \"127.0.0.1\",\n" + + " \"hostName\": \"vnf-host\"\n" + + " }" + + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment", "assignment-params", + JacksonUtils.jsonNode(assignmentParams) + ) + + val capProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties( + "sample-netconf-device", + "netconf" + ) + assertNotNull(capProperties, "Failed to populate capability property values") + assertEquals( + capProperties["target-ip-address"], + "127.0.0.1".asJsonPrimitive(), + "Failed to populate parameter target-ip-address" + ) + assertEquals( + capProperties["port-number"], + JacksonUtils.jsonNodeFromObject(830), + "Failed to populate parameter port-number" + ) + } + + @Test + fun `test Resolve NodeTemplate Interface Operation Inputs`() { + log.info("************************ testResolveNodeTemplateInterfaceOperationInputs **********************") + + val bluePrintRuntimeService = getBluePrintRuntimeService() + + val executionContext = bluePrintRuntimeService.getExecutionContext() + + BluePrintRuntimeUtils.assignInputsFromClassPathFile( + bluePrintRuntimeService.bluePrintContext(), + "data/default-context.json", executionContext + ) + + val inContext: MutableMap = bluePrintRuntimeService + .resolveNodeTemplateInterfaceOperationInputs( + "resource-assignment", + "ResourceResolutionComponent", "process" + ) + + assertNotNull(inContext, "Failed to populate interface input property values") + assertEquals( + inContext["action-name"], + JacksonUtils.jsonNodeFromObject("sample-action"), + "Failed to populate parameter action-name" + ) + assertEquals( + inContext["request-id"], + JacksonUtils.jsonNodeFromObject("12345"), + "Failed to populate parameter action-name" + ) + } + + @Test + fun `test Resolve NodeTemplate Interface Operation Outputs`() { + log.info("************************ testResolveNodeTemplateInterfaceOperationOutputs **********************") + + val bluePrintRuntimeService = getBluePrintRuntimeService() + + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment", + "assignment-params", + NullNode.getInstance() + ) + + bluePrintRuntimeService.resolveNodeTemplateInterfaceOperationOutputs( + "resource-assignment", + "ResourceResolutionComponent", "process" + ) + + val outputStatus = bluePrintRuntimeService.getNodeTemplateOperationOutputValue( + "resource-assignment", + "ResourceResolutionComponent", "process", "status" + ) + assertEquals("success".asJsonPrimitive(), outputStatus, "Failed to get operation property status") + + val outputParams = bluePrintRuntimeService.getNodeTemplateOperationOutputValue( + "resource-assignment", + "ResourceResolutionComponent", "process", "resource-assignment-params" + ) + assertEquals( + NullNode.getInstance(), + outputParams, + "Failed to get operation property resource-assignment-params" + ) + } + + @Test + fun `test NodeTemplate Context Property`() { + log.info("************************ testNodeTemplateContextProperty **********************") + val bluePrintRuntimeService = getBluePrintRuntimeService() + + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment-ra-component", "context1", + JacksonUtils.jsonNodeFromObject("context1-value") + ) + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment-ra-component", "context2", + JacksonUtils.jsonNodeFromObject("context2-value") + ) + + val keys = listOf("context1", "context2") + + val jsonValueNode = + bluePrintRuntimeService.getJsonForNodeTemplateAttributeProperties("resource-assignment-ra-component", keys) + assertNotNull(jsonValueNode, "Failed to get Json for Node Template Context Properties") + log.info("JSON Prepared Value Context {}", jsonValueNode) + } + + @Test + fun `test Resolve DSL Properties`() { + log.info("************************ resolveDSLExpression **********************") + + val bluePrintRuntimeService = getBluePrintRuntimeService() + + bluePrintRuntimeService.setInputValue("rest-user-name", "sample-username".asJsonPrimitive()) + + val resolvedJsonNode: JsonNode = bluePrintRuntimeService.resolveDSLExpression("dynamic-rest-source") + assertNotNull(resolvedJsonNode, "Failed to populate dsl property values") + } + + @Test + fun `test Resolve Workflow Outputs`() { + log.info("************************ resolvePropertyAssignments **********************") + val bluePrintRuntimeService = getBluePrintRuntimeService() + + val assignmentParams = "{\"ipAddress\": \"127.0.0.1\", \"hostName\": \"vnf-host\"}" + + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment", "assignment-params", + JacksonUtils.jsonNode(assignmentParams) + ) + + val resolvedJsonNode = bluePrintRuntimeService.resolveWorkflowOutputs("resource-assignment") + assertNotNull(resolvedJsonNode, "Failed to populate workflow output property values") + } + + @Test + fun `test resolvePropertyDefinitions using sub attributes`() { + val bluePrintRuntimeService = getBluePrintRuntimeService() + + bluePrintRuntimeService.setNodeTemplateAttributeValue( + "resource-assignment", "assignment-map", + JacksonUtils.jsonNode( + """ + { + "a-prefix":{ + "an-object":{ + "a-key":123 + } + } + } + """.trimIndent() + ) + ) + + val propertyDefinitions = mutableMapOf( + "resolution" to PropertyDefinition().apply { + this.type = "json" + this.value = JacksonUtils.jsonNode( + """ + { + "get_attribute":[ + "resource-assignment", + "", + "assignment-map", + "a-prefix", + "an-object", + "a-key" + ] + } + """.trimIndent() + ) + } + ) + + val result = bluePrintRuntimeService.resolvePropertyDefinitions("workflow", "WORKFLOW", propertyDefinitions) + + assertEquals("123", result["resolution"]!!.asText()) + } + + private fun getBluePrintRuntimeService(): BluePrintRuntimeService> { + val blueprintBasePath = normalizedPathName(TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG) + val blueprintRuntime = BluePrintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) + val checkProcessId = blueprintRuntime.get(BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID) + val checkBasePath = blueprintRuntime.get(BluePrintConstants.PROPERTY_BLUEPRINT_BASE_PATH) + + assertEquals( + "1234".asJsonPrimitive(), + checkProcessId, "Failed to get process id after runtime creation" + ) + assertEquals( + blueprintBasePath.asJsonPrimitive(), + checkBasePath, "Failed to get base path after runtime creation" + ) + + return blueprintRuntime + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt new file mode 100644 index 000000000..0e93ccf6b --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Modifications Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import kotlin.test.BeforeTest +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +class BluePrintTemplateServiceTest { + + lateinit var blueprintRuntime: BluePrintRuntimeService<*> + + @BeforeTest + fun setup() { + val blueprintBasePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG + blueprintRuntime = BluePrintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) + } + + @Test + fun testVelocityGeneratedContent() { + runBlocking { + val template = JacksonUtils.getClassPathFileContent("templates/base-config-velocity-template.vtl") + val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-velocity.json") + + val content = BluePrintVelocityTemplateService.generateContent(template, json) + assertNotNull(content, "failed to generate content for velocity template") + } + } + + @Test + fun testJinjaGeneratedContent() { + runBlocking { + val template = JacksonUtils.getClassPathFileContent("templates/master.jinja") + val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-jinja.json") + + val element: MutableMap = mutableMapOf() + element["additional_array"] = arrayListOf( + hashMapOf("name" to "Element1", "location" to "Region0"), + hashMapOf("name" to "Element2", "location" to "Region1") + ) + + val content = BluePrintJinjaTemplateService.generateContent(template, json, false, element) + assertNotNull(content, "failed to generate content for velocity template") + } + } + + @Test + fun `no value variable should evaluate to default value - standalone template mesh test`() { + runBlocking { + val template = + JacksonUtils.getClassPathFileContent("templates/default-variable-value-velocity-template.vtl") + val json = JacksonUtils.getClassPathFileContent("templates/default-variable-value-data.json") + + val content = BluePrintVelocityTemplateService.generateContent(template, json) + // first line represents a variable whose value was successfully retrieved, second line contains a variable + // whose value could not be evaluated + val expected = "sample-hostname\n\${node0_backup_router_address}" + assertEquals(expected, content, "No value variable should use default value") + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt new file mode 100644 index 000000000..eb6246989 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt @@ -0,0 +1,272 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.service + +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel +import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.toGraph +import kotlin.test.assertNotNull + +class BluePrintWorkflowServiceTest { + + @Test + fun testSimpleFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>E/SUCCESS, E>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testMultipleFlows() { + runBlocking { + coroutineScope { + val wfs = listOf("12345", "12346").map { + async { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null) + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(it), it) + assertNotNull(response, "failed to get response") + } + } + wfs.awaitAll() + } + } + } + + @Test + fun testMissingEdgeForBFailureState() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), arrayListOf("B")) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testBExceptionFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testTimeoutExceptionFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>TO/SUCCESS, TO>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "TO", "C", "D", "E"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testConditionalFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testBothConditionalFlow() { + runBlocking { + // Failure Flow + val failurePatGraph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val failurePathWorkflow = TestBluePrintWorkFlowService() + failurePathWorkflow.simulatedState = prepareSimulation( + arrayListOf("B", "C", "D", "E"), + arrayListOf("A") + ) + val failurePathWorkflowInput = "123456" + val failurePathResponse = failurePathWorkflow.executeWorkflow(failurePatGraph, mockBluePrintRuntimeService(), failurePathWorkflowInput) + assertNotNull(failurePathResponse, "failed to get response") + } + } + + @Test + fun testMultipleSkipFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, C>D/SUCCESS, D>E/SUCCESS, B>E/SUCCESS, E>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + @Test + fun testParallelFlow() { + runBlocking { + val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/SUCCESS, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" + .toGraph() + val simpleWorkflow = TestBluePrintWorkFlowService() + simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null) + val input = "123456" + val response = simpleWorkflow.executeWorkflow(graph, mockBluePrintRuntimeService(), input) + assertNotNull(response, "failed to get response") + } + } + + private fun mockBluePrintRuntimeService(): BluePrintRuntimeService<*> { + return mockBluePrintRuntimeService("123456") + } + + private fun mockBluePrintRuntimeService(id: String): BluePrintRuntimeService<*> { + val bluePrintRuntimeService = mockk>() + every { bluePrintRuntimeService.id() } returns id + return bluePrintRuntimeService + } + + private fun prepareSimulation(successes: List?, failures: List?): MutableMap { + val simulatedState: MutableMap = hashMapOf() + successes?.forEach { + simulatedState[it] = EdgeLabel.SUCCESS + } + failures?.forEach { + simulatedState[it] = EdgeLabel.FAILURE + } + return simulatedState + } +} + +class TestBluePrintWorkFlowService : + AbstractBluePrintWorkFlowService() { + + val log = logger(TestBluePrintWorkFlowService::class) + + lateinit var simulatedState: MutableMap + + override suspend fun initializeWorkflow(input: String): EdgeLabel { + return EdgeLabel.SUCCESS + } + + override suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: String): String { + log.info("Executing Graph : $graph") + this.graph = graph + this.workflowId = bluePrintRuntimeService.id() + val output = CompletableDeferred() + val startMessage = WorkflowExecuteMessage(input, output) + val workflowActor = workflowActor() + if (!workflowActor.isClosedForSend) { + workflowActor().send(startMessage) + } else { + throw BluePrintProcessorException("workflow actor is closed for send $workflowActor") + } + return startMessage.output.await() + } + + override suspend fun prepareNodeExecutionMessage(node: Graph.Node): + NodeExecuteMessage { + return NodeExecuteMessage(node, "$node Input", "") + } + + override suspend fun executeNode( + node: Graph.Node, + nodeInput: String, + nodeOutput: String + ): EdgeLabel { + // val random = (1..10).random() * 100 + // log.info("workflow($workflowId) node(${node.id}) will reply in $random ms") + // kotlinx.coroutines.delay(random.toLong()) + // //Simulation for timeout + if (node.id == "TO") { + withTimeout(1) { + kotlinx.coroutines.delay(2) + } + } + return simulatedState[node.id] ?: throw BluePrintException("failed to get status for the node($node)") + } + + override suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage { + val nodeOutput = "" + return NodeSkipMessage(node, "$node Skip Input", nodeOutput) + } + + override suspend fun skipNode( + node: Graph.Node, + nodeInput: String, + nodeOutput: String + ): EdgeLabel { + return simulatedState[node.id] ?: throw BluePrintException("failed to get status for the node($node)") + } + + override suspend fun cancelNode( + node: Graph.Node, + nodeInput: String, + nodeOutput: String + ): EdgeLabel { + TODO("not implemented") // To change body of created functions use File | Settings | File Templates. + } + + override suspend fun restartNode( + node: Graph.Node, + nodeInput: String, + nodeOutput: String + ): EdgeLabel { + TODO("not implemented") // To change body of created functions use File | Settings | File Templates. + } + + override suspend fun prepareWorkflowOutput(): String { + if (exceptions.isNotEmpty()) { + exceptions.forEach { + log.error("workflow($workflowId) exceptions :", it) + } + } + return "Final Response" + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContextTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContextTest.kt deleted file mode 100644 index 4ad4ab403..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContextTest.kt +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.ObjectMapper -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * - * - * @author Brinda Santh - */ -class BlueprintContextTest { - - private val log = LoggerFactory.getLogger(this::class.toString()) - - val blueprintBasePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG - - @Test - fun testBlueprintContextCreation() { - runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext(blueprintBasePath) - assertNotNull(bluePrintContext, "Failed to populate Blueprint context") - } - } - - @Test - fun testChainedProperty() { - runBlocking { - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext(blueprintBasePath) - val nodeType = bluePrintContext.nodeTypeChained("component-resource-resolution") - assertNotNull(nodeType, "Failed to get chained node type") - log.trace("Properties {}", JacksonUtils.getJson(nodeType, true)) - } - } - - @Test - fun testImports() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.imports = mutableListOf() - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.imports()!!.isEmpty()) - - serviceTemplate.imports = null - assertNull(bluePrintContext.imports()) - } - - @Test - fun testDataTypes() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.dataTypes = mutableMapOf() - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.dataTypes()!!.isEmpty()) - - serviceTemplate.dataTypes = null - assertNull(bluePrintContext.dataTypes()) - } - - @Test - fun testInputs() { - val topologyTemplate = TopologyTemplate() - topologyTemplate.inputs = mutableMapOf() - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.inputs()!!.isEmpty()) - - topologyTemplate.inputs = null - - assertNull(bluePrintContext.inputs()) - } - - @Test - fun testBlueprintJson() { - val serviceTemplate = ServiceTemplate() - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("{\"tosca_definitions_version\":\"controller_blueprint_1_0_0\"}", bluePrintContext.blueprintJson()) - } - - @Test(expected = BlueprintException::class) - fun testName() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.metadata = mutableMapOf(BlueprintConstants.METADATA_TEMPLATE_NAME to "hello") - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.name()) - - serviceTemplate.metadata = mutableMapOf() - val bluePrintContext2 = BlueprintContext(serviceTemplate) - bluePrintContext2.name() - } - - @Test(expected = BlueprintException::class) - fun testVersion() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.metadata = mutableMapOf(BlueprintConstants.METADATA_TEMPLATE_VERSION to "hello") - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.version()) - - serviceTemplate.metadata = mutableMapOf() - val bluePrintContext2 = BlueprintContext(serviceTemplate) - bluePrintContext2.version() - } - - @Test(expected = BlueprintException::class) - fun testAuthor() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.metadata = mutableMapOf(BlueprintConstants.METADATA_TEMPLATE_AUTHOR to "hello") - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.author()) - - serviceTemplate.metadata = mutableMapOf() - val bluePrintContext2 = BlueprintContext(serviceTemplate) - bluePrintContext2.author() - } - - @Test - fun testWorkflows() { - val topologyTemplate = TopologyTemplate() - topologyTemplate.workflows = mutableMapOf() - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.workflows()!!.isEmpty()) - - topologyTemplate.workflows = null - assertNull(bluePrintContext.workflows()) - } - - @Test(expected = BlueprintException::class) - fun testWorkFlowsByName() { - val topologyTemplate = TopologyTemplate() - topologyTemplate.workflows = mutableMapOf("workflow" to Workflow()) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.workflowByName("workflow")) - - bluePrintContext.workflowByName("") - } - - @Test - fun testWorkflowInput() { - val topologyTemplate = TopologyTemplate() - val workflow = Workflow() - workflow.inputs = mutableMapOf() - topologyTemplate.workflows = mutableMapOf("workflow" to workflow) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.workflowInputs("workflow")!!.isEmpty()) - - workflow.inputs = null - - assertNull(bluePrintContext.workflowInputs("workflow")) - } - - @Test(expected = BlueprintException::class) - fun testWorkflowStepByName() { - val topologyTemplate = TopologyTemplate() - val workflow = Workflow() - workflow.steps = mutableMapOf("step" to Step()) - topologyTemplate.workflows = mutableMapOf("workflow" to workflow) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.workflowStepByName("workflow", "step")) - - bluePrintContext.workflowStepByName("workflow", "") - } - - @Test(expected = BlueprintException::class) - fun testWorkflowStepNodeTemplate() { - val topologyTemplate = TopologyTemplate() - val workflow = Workflow() - val step = Step() - step.target = "hello" - workflow.steps = mutableMapOf("step" to step) - topologyTemplate.workflows = mutableMapOf("workflow" to workflow) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.workflowStepNodeTemplate("workflow", "step")) - - bluePrintContext.workflowStepNodeTemplate("workflow", "") - } - - @Test(expected = BlueprintException::class) - fun testWorkflowFirstStepNodeTemplate() { - val topologyTemplate = TopologyTemplate() - val workflow = Workflow() - val step = Step() - step.target = "hello" - workflow.steps = mutableMapOf("step" to step, "step2" to Step()) - topologyTemplate.workflows = mutableMapOf("workflow" to workflow) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.workflowFirstStepNodeTemplate("workflow")) - - workflow.steps = null - bluePrintContext.workflowFirstStepNodeTemplate("workflow") - } - - @Test(expected = BlueprintException::class) - fun testWorkflowStepFirstCallOperation() { - val topologyTemplate = TopologyTemplate() - val workflow = Workflow() - val step = Step() - val activity = Activity() - activity.callOperation = "hello" - step.activities = arrayListOf(activity) - workflow.steps = mutableMapOf("step" to step) - topologyTemplate.workflows = mutableMapOf("workflow" to workflow) - val serviceTemplate = ServiceTemplate() - serviceTemplate.topologyTemplate = topologyTemplate - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.workflowStepFirstCallOperation("workflow", "step")) - - bluePrintContext.workflowStepFirstCallOperation("workflow", "") - } - - @Test - fun testDatatypeByName() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.dataTypes = mutableMapOf("data" to DataType()) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.dataTypeByName("data")) - assertNull(bluePrintContext.dataTypeByName("")) - } - - @Test - fun testArtifactTypes() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.artifactTypes = mutableMapOf() - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.artifactTypes()!!.isEmpty()) - - serviceTemplate.artifactTypes = null - assertNull(bluePrintContext.artifactTypes()) - } - - @Test - fun testPolicyTypes() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.policyTypes = mutableMapOf() - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.policyTypes()!!.isEmpty()) - - serviceTemplate.policyTypes = null - assertNull(bluePrintContext.policyTypes()) - } - - @Test(expected = BlueprintException::class) - fun testPolicyTypeByName() { - val serviceTemplate = ServiceTemplate() - serviceTemplate.policyTypes = mutableMapOf("policy" to PolicyType()) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.policyTypeByName("policy")) - - bluePrintContext.policyTypeByName("") - } - - @Test - fun testPolicyTypesDerivedFrom() { - val serviceTemplate = ServiceTemplate() - val policyType = PolicyType() - policyType.derivedFrom = "hi" - val policyType2 = PolicyType() - policyType2.derivedFrom = "hello" - serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals(1, bluePrintContext.policyTypesDerivedFrom("hi")!!.size) - - serviceTemplate.policyTypes = null - assertNull(bluePrintContext.policyTypesDerivedFrom("hi")) - } - - @Test - fun testPolicyTypesTarget() { - val serviceTemplate = ServiceTemplate() - val policyType = PolicyType() - policyType.targets = mutableListOf("hi") - val policyType2 = PolicyType() - policyType2.targets = mutableListOf() - serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals(1, bluePrintContext.policyTypesTarget("hi")!!.size) - - serviceTemplate.policyTypes = null - assertNull(bluePrintContext.policyTypesTarget("hi")) - } - - @Test - fun testPolicyTypesTargetNDerivedFrom() { - val serviceTemplate = ServiceTemplate() - val policyType = PolicyType() - policyType.targets = mutableListOf("hi") - policyType.derivedFrom = "hi" - val policyType2 = PolicyType() - policyType2.targets = mutableListOf() - policyType2.derivedFrom = "hi" - serviceTemplate.policyTypes = mutableMapOf("policy" to policyType, "policy2" to policyType2) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals(1, bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")!!.size) - - serviceTemplate.policyTypes = null - assertNull(bluePrintContext.policyTypesTargetNDerivedFrom("hi", "hi")) - } - - @Test - fun testNodeTypeDerivedFrom() { - val serviceTemplate = ServiceTemplate() - val nodeType = NodeType() - nodeType.derivedFrom = "hi" - val nodeType2 = NodeType() - nodeType2.derivedFrom = "hiii" - serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType, "node2" to nodeType2) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals(1, bluePrintContext.nodeTypeDerivedFrom("hi")!!.size) - - serviceTemplate.nodeTypes = null - assertNull(bluePrintContext.nodeTypeDerivedFrom("hi")) - } - - @Test(expected = BlueprintException::class) - fun testInterfaceNameForNodeType() { - val serviceTemplate = ServiceTemplate() - val nodeType = NodeType() - nodeType.interfaces = mutableMapOf("hello" to InterfaceDefinition(), "hi" to InterfaceDefinition()) - serviceTemplate.nodeTypes = mutableMapOf("node" to nodeType) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("hello", bluePrintContext.interfaceNameForNodeType("node")) - - bluePrintContext.interfaceNameForNodeType("") - } - - @Test - fun testNodeTemplateForNodeType() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.type = "hello" - val nodeTemplate2 = NodeTemplate() - nodeTemplate2.type = "hi" - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = - mutableMapOf("node" to nodeTemplate, "node2" to nodeTemplate2) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals(1, bluePrintContext.nodeTemplateForNodeType("hello")!!.size) - - serviceTemplate.topologyTemplate!!.nodeTemplates = null - assertNull(bluePrintContext.nodeTemplateForNodeType("hello")) - } - - @Test - fun testNodeTemplateProperty() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateProperty("node", "prop")) - - assertNull(bluePrintContext.nodeTemplateProperty("node", "")) - - nodeTemplate.properties = null - assertNull(bluePrintContext.nodeTemplateProperty("node", "prop")) - } - - @Test - fun testNodeTemplateArtifacts() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.artifacts = mutableMapOf() - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertTrue(bluePrintContext.nodeTemplateArtifacts("node")!!.isEmpty()) - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateArtifact() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.artifacts = mutableMapOf("art" to ArtifactDefinition()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateArtifact("node", "art")) - - bluePrintContext.nodeTemplateArtifact("node", "") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateArtifactForArtifactType() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - val artifactDefinition = ArtifactDefinition() - artifactDefinition.type = "type" - val artifactDefinition2 = ArtifactDefinition() - artifactDefinition2.type = "No type" - nodeTemplate.artifacts = mutableMapOf("art" to artifactDefinition, "art2" to artifactDefinition2) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateArtifactForArtifactType("node", "type")) - - bluePrintContext.nodeTemplateArtifactForArtifactType("", "") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateFirstInterface() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateFirstInterface("node")) - - nodeTemplate.interfaces = null - bluePrintContext.nodeTemplateFirstInterface("node") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateFirstInterfaceName() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.interfaces = mutableMapOf("interface" to InterfaceAssignment(), "interf" to InterfaceAssignment()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("interface", bluePrintContext.nodeTemplateFirstInterfaceName("node")) - - nodeTemplate.interfaces = null - bluePrintContext.nodeTemplateFirstInterfaceName("node") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateFirstInterfaceFirstOperationName() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - val interfaceAssignment = InterfaceAssignment() - interfaceAssignment.operations = mutableMapOf("op" to OperationAssignment(), "op2" to OperationAssignment()) - nodeTemplate.interfaces = mutableMapOf("intf" to interfaceAssignment) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertEquals("op", bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node")) - - interfaceAssignment.operations = null - bluePrintContext.nodeTemplateFirstInterfaceFirstOperationName("node") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateCapability() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.capabilities = mutableMapOf("cap" to CapabilityAssignment()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateCapability("node", "cap")) - - bluePrintContext.nodeTemplateCapability("node", "") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateRequirement() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - nodeTemplate.requirements = mutableMapOf("req" to RequirementAssignment()) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateRequirement("node", "req")) - - bluePrintContext.nodeTemplateRequirement("node", "") - } - - @Test(expected = BlueprintException::class) - fun testNodeTemplateRequirementNode() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - val requirementAssignment = RequirementAssignment() - requirementAssignment.node = "node" - nodeTemplate.requirements = mutableMapOf("req" to requirementAssignment) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateRequirementNode("node", "req")) - - bluePrintContext.nodeTemplateRequirementNode("node", "") - } - - @Test - fun testNodeTemplateCapabilityProperty() { - val serviceTemplate = ServiceTemplate() - val nodeTemplate = NodeTemplate() - val capabilityAssignment = CapabilityAssignment() - capabilityAssignment.properties = mutableMapOf("prop" to ObjectMapper().createObjectNode()) - nodeTemplate.capabilities = mutableMapOf("cap" to capabilityAssignment) - serviceTemplate.topologyTemplate = TopologyTemplate() - serviceTemplate.topologyTemplate!!.nodeTemplates = mutableMapOf("node" to nodeTemplate) - val bluePrintContext = BlueprintContext(serviceTemplate) - - assertNotNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) - - capabilityAssignment.properties = null - - assertNull(bluePrintContext.nodeTemplateCapabilityProperty("node", "cap", "prop")) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionServiceTest.kt deleted file mode 100644 index 552f7b6f8..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintExpressionServiceTest.kt +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -/** - * - * - * @author Brinda Santh - */ -class BlueprintExpressionServiceTest { - - @Test - fun testInputExpression() { - val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_input\" : \"input-name\" }") - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.inputExpression, " Failed to populate input expression data") - assertEquals("input-name", expressionData.inputExpression?.propertyName, "Failed to get propertyName from expression data") - } - - @Test - fun testPropertyExpression() { - val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"property-name\"] }") - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.propertyExpression, " Failed to populate property expression data") - assertEquals("SELF", expressionData.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("property-name", expressionData.propertyExpression?.propertyName, " Failed to get expected propertyName") - - val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"\",\"property-name\", \"resource\", \"name\"] }") - val expressionData1: ExpressionData = BlueprintExpressionService.getExpressionData(node1) - assertNotNull(expressionData1, " Failed to populate expression data") - assertEquals(expressionData1.isExpression, true, "Failed to identify as nested property expression") - assertNotNull(expressionData1.propertyExpression, " Failed to populate nested property expression data") - assertEquals("SELF", expressionData1.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("property-name", expressionData1.propertyExpression?.propertyName, " Failed to get expected propertyName") - assertEquals( - "resource.name", - expressionData1.propertyExpression?.subPropertyName, - " Failed to populate nested subPropertyName expression data" - ) - } - - @Test - fun testAttributeExpression() { - val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"resource\"] }") - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.attributeExpression, " Failed to populate attribute expression data") - assertEquals("SELF", expressionData.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("resource", expressionData.attributeExpression?.attributeName, " Failed to get expected attributeName") - - val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"\",\"attribute-name\", \"resource\", \"name\"] }") - val expressionData1: ExpressionData = BlueprintExpressionService.getExpressionData(node1) - assertNotNull(expressionData1, " Failed to populate expression data") - assertEquals(expressionData1.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData1.attributeExpression, " Failed to populate attribute expression data") - assertEquals("SELF", expressionData1.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("attribute-name", expressionData1.attributeExpression?.attributeName, " Failed to get expected attributeName") - assertEquals( - "resource.name", - expressionData1.attributeExpression?.subAttributeName, - " Failed to populate nested subAttributeName expression data" - ) - } - - @Test - fun testOutputOperationExpression() { - val node: JsonNode = - jacksonObjectMapper().readTree("{ \"get_operation_output\": [\"SELF\", \"interface-name\", \"operation-name\", \"output-property-name\"] }") - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.operationOutputExpression, " Failed to populate output expression data") - assertEquals("SELF", expressionData.operationOutputExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("interface-name", expressionData.operationOutputExpression?.interfaceName, " Failed to get expected interfaceName") - assertEquals("operation-name", expressionData.operationOutputExpression?.operationName, " Failed to get expected operationName") - assertEquals("output-property-name", expressionData.operationOutputExpression?.propertyName, " Failed to get expected propertyName") - } - - @Test - fun testArtifactExpression() { - val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\"] }") - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.artifactExpression, " Failed to populate Artifact expression data") - assertEquals("SELF", expressionData.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("artifact-template", expressionData.artifactExpression?.artifactName, " Failed to get expected artifactName") - - val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\", \"location\", true] }") - val expressionData1: ExpressionData = BlueprintExpressionService.getExpressionData(node1) - assertNotNull(expressionData1, " Failed to populate expression data") - assertEquals(expressionData1.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData1.artifactExpression, " Failed to populate Artifact expression data") - assertEquals("SELF", expressionData1.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName") - assertEquals("artifact-template", expressionData1.artifactExpression?.artifactName, " Failed to get expected artifactName") - assertEquals("location", expressionData1.artifactExpression?.location, " Failed to get expected location") - assertEquals(true, expressionData1.artifactExpression?.remove, " Failed to get expected remove") - } - - @Test - fun testDSLExpression() { - val node: JsonNode = "*dynamic-rest-source".asJsonPrimitive() - val expressionData: ExpressionData = BlueprintExpressionService.getExpressionData(node) - assertNotNull(expressionData, " Failed to populate expression data") - assertEquals(expressionData.isExpression, true, "Failed to identify as expression") - assertNotNull(expressionData.dslExpression, " Failed to populate dsl expression data") - assertEquals( - "dynamic-rest-source", expressionData.dslExpression!!.propertyName, - " Failed to populate dsl property name" - ) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileServiceTest.kt deleted file mode 100644 index 5ef28cce2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRepoFileServiceTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import kotlin.test.assertNotNull - -/** - * BlueprintRepoFileServiceTest - * @author Brinda Santh - * - */ -class BlueprintRepoFileServiceTest { - - private val basePath = TestConstants.PATH_TEST_DEFINITION_TYPE_STARTER - private val bluePrintRepoFileService = BlueprintRepoFileService(basePath) - - @Test - fun testGetDataType() { - val dataType = bluePrintRepoFileService.getDataType("dt-v4-aggregate") - assertNotNull(dataType, "Failed to get DataType from repo") - } - - @Test - fun testGetNodeType() { - val nodeType = bluePrintRepoFileService.getNodeType("component-resource-resolution") - assertNotNull(nodeType, "Failed to get NodeType from repo") - } - - @Test - fun testGetArtifactType() { - val nodeType = bluePrintRepoFileService.getArtifactType("artifact-template-velocity") - assertNotNull(nodeType, "Failed to get ArtifactType from repo") - } - - @Test(expected = BlueprintException::class) - fun testModelNotFound() { - val dataType = bluePrintRepoFileService.getDataType("dt-not-found") - assertNotNull(dataType, "Failed to get DataType from repo") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeServiceTest.kt deleted file mode 100644 index 268811091..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintRuntimeServiceTest.kt +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018-2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.NullNode -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintRuntimeUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -/** - * - * - * @author Brinda Santh - */ -class BlueprintRuntimeServiceTest { - - private val log = LoggerFactory.getLogger(this::class.toString()) - - @Test - fun `test Resolve NodeTemplate Properties`() { - log.info("************************ testResolveNodeTemplateProperties **********************") - - val bluePrintRuntimeService = getBlueprintRuntimeService() - - val inputDataPath = "src/test/resources/data/default-context.json" - - val inputNode: JsonNode = JacksonUtils.jsonNodeFromFile(inputDataPath) - bluePrintRuntimeService.assignInputs(inputNode) - - val propContext: MutableMap = bluePrintRuntimeService - .resolveNodeTemplateProperties("activate-process") - - assertNotNull(propContext, "Failed to populate interface property values") - } - - @Test - fun `test Resolve Relationship Properties`() { - log.info("************************ testResolveRelationshipTemplateProperties **********************") - - val bluePrintRuntimeService = getBlueprintRuntimeService() - - val inputDataPath = "src/test/resources/data/default-context.json" - - val inputNode: JsonNode = JacksonUtils.jsonNodeFromFile(inputDataPath) - bluePrintRuntimeService.assignInputs(inputNode) - - val propContext: MutableMap = bluePrintRuntimeService - .resolveRelationshipTemplateProperties("cli-device-properties") - - assertNotNull(propContext, "Failed to populate relationship property values") - assertEquals( - "localhost".asJsonPrimitive(), - propContext["connection-config"]!!.get("host"), - "failed to resolve expression" - ) - } - - @Test - fun `test resolve NodeTemplate Capability Properties`() { - log.info("************************ testResolveNodeTemplateRequirementProperties **********************") - val bluePrintRuntimeService = getBlueprintRuntimeService() - - val executionContext = bluePrintRuntimeService.getExecutionContext() - - BlueprintRuntimeUtils.assignInputsFromClassPathFile( - bluePrintRuntimeService.bluePrintContext(), - "data/default-context.json", executionContext - ) - - val assignmentParams = "{\n" + - " \"ipAddress\": \"127.0.0.1\",\n" + - " \"hostName\": \"vnf-host\"\n" + - " }" - - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment", "assignment-params", - JacksonUtils.jsonNode(assignmentParams) - ) - - val capProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties( - "sample-netconf-device", - "netconf" - ) - assertNotNull(capProperties, "Failed to populate capability property values") - assertEquals( - capProperties["target-ip-address"], - "127.0.0.1".asJsonPrimitive(), - "Failed to populate parameter target-ip-address" - ) - assertEquals( - capProperties["port-number"], - JacksonUtils.jsonNodeFromObject(830), - "Failed to populate parameter port-number" - ) - } - - @Test - fun `test Resolve NodeTemplate Interface Operation Inputs`() { - log.info("************************ testResolveNodeTemplateInterfaceOperationInputs **********************") - - val bluePrintRuntimeService = getBlueprintRuntimeService() - - val executionContext = bluePrintRuntimeService.getExecutionContext() - - BlueprintRuntimeUtils.assignInputsFromClassPathFile( - bluePrintRuntimeService.bluePrintContext(), - "data/default-context.json", executionContext - ) - - val inContext: MutableMap = bluePrintRuntimeService - .resolveNodeTemplateInterfaceOperationInputs( - "resource-assignment", - "ResourceResolutionComponent", "process" - ) - - assertNotNull(inContext, "Failed to populate interface input property values") - assertEquals( - inContext["action-name"], - JacksonUtils.jsonNodeFromObject("sample-action"), - "Failed to populate parameter action-name" - ) - assertEquals( - inContext["request-id"], - JacksonUtils.jsonNodeFromObject("12345"), - "Failed to populate parameter action-name" - ) - } - - @Test - fun `test Resolve NodeTemplate Interface Operation Outputs`() { - log.info("************************ testResolveNodeTemplateInterfaceOperationOutputs **********************") - - val bluePrintRuntimeService = getBlueprintRuntimeService() - - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment", - "assignment-params", - NullNode.getInstance() - ) - - bluePrintRuntimeService.resolveNodeTemplateInterfaceOperationOutputs( - "resource-assignment", - "ResourceResolutionComponent", "process" - ) - - val outputStatus = bluePrintRuntimeService.getNodeTemplateOperationOutputValue( - "resource-assignment", - "ResourceResolutionComponent", "process", "status" - ) - assertEquals("success".asJsonPrimitive(), outputStatus, "Failed to get operation property status") - - val outputParams = bluePrintRuntimeService.getNodeTemplateOperationOutputValue( - "resource-assignment", - "ResourceResolutionComponent", "process", "resource-assignment-params" - ) - assertEquals( - NullNode.getInstance(), - outputParams, - "Failed to get operation property resource-assignment-params" - ) - } - - @Test - fun `test NodeTemplate Context Property`() { - log.info("************************ testNodeTemplateContextProperty **********************") - val bluePrintRuntimeService = getBlueprintRuntimeService() - - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment-ra-component", "context1", - JacksonUtils.jsonNodeFromObject("context1-value") - ) - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment-ra-component", "context2", - JacksonUtils.jsonNodeFromObject("context2-value") - ) - - val keys = listOf("context1", "context2") - - val jsonValueNode = - bluePrintRuntimeService.getJsonForNodeTemplateAttributeProperties("resource-assignment-ra-component", keys) - assertNotNull(jsonValueNode, "Failed to get Json for Node Template Context Properties") - log.info("JSON Prepared Value Context {}", jsonValueNode) - } - - @Test - fun `test Resolve DSL Properties`() { - log.info("************************ resolveDSLExpression **********************") - - val bluePrintRuntimeService = getBlueprintRuntimeService() - - bluePrintRuntimeService.setInputValue("rest-user-name", "sample-username".asJsonPrimitive()) - - val resolvedJsonNode: JsonNode = bluePrintRuntimeService.resolveDSLExpression("dynamic-rest-source") - assertNotNull(resolvedJsonNode, "Failed to populate dsl property values") - } - - @Test - fun `test Resolve Workflow Outputs`() { - log.info("************************ resolvePropertyAssignments **********************") - val bluePrintRuntimeService = getBlueprintRuntimeService() - - val assignmentParams = "{\"ipAddress\": \"127.0.0.1\", \"hostName\": \"vnf-host\"}" - - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment", "assignment-params", - JacksonUtils.jsonNode(assignmentParams) - ) - - val resolvedJsonNode = bluePrintRuntimeService.resolveWorkflowOutputs("resource-assignment") - assertNotNull(resolvedJsonNode, "Failed to populate workflow output property values") - } - - @Test - fun `test resolvePropertyDefinitions using sub attributes`() { - val bluePrintRuntimeService = getBlueprintRuntimeService() - - bluePrintRuntimeService.setNodeTemplateAttributeValue( - "resource-assignment", "assignment-map", - JacksonUtils.jsonNode( - """ - { - "a-prefix":{ - "an-object":{ - "a-key":123 - } - } - } - """.trimIndent() - ) - ) - - val propertyDefinitions = mutableMapOf( - "resolution" to PropertyDefinition().apply { - this.type = "json" - this.value = JacksonUtils.jsonNode( - """ - { - "get_attribute":[ - "resource-assignment", - "", - "assignment-map", - "a-prefix", - "an-object", - "a-key" - ] - } - """.trimIndent() - ) - } - ) - - val result = bluePrintRuntimeService.resolvePropertyDefinitions("workflow", "WORKFLOW", propertyDefinitions) - - assertEquals("123", result["resolution"]!!.asText()) - } - - private fun getBlueprintRuntimeService(): BlueprintRuntimeService> { - val blueprintBasePath = normalizedPathName(TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG) - val blueprintRuntime = BlueprintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) - val checkProcessId = blueprintRuntime.get(BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID) - val checkBasePath = blueprintRuntime.get(BlueprintConstants.PROPERTY_BLUEPRINT_BASE_PATH) - - assertEquals( - "1234".asJsonPrimitive(), - checkProcessId, "Failed to get process id after runtime creation" - ) - assertEquals( - blueprintBasePath.asJsonPrimitive(), - checkBasePath, "Failed to get base path after runtime creation" - ) - - return blueprintRuntime - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateServiceTest.kt deleted file mode 100644 index 6ebb6b7ff..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintTemplateServiceTest.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import kotlin.test.BeforeTest -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -class BlueprintTemplateServiceTest { - - lateinit var blueprintRuntime: BlueprintRuntimeService<*> - - @BeforeTest - fun setup() { - val blueprintBasePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG - blueprintRuntime = BlueprintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) - } - - @Test - fun testVelocityGeneratedContent() { - runBlocking { - val template = JacksonUtils.getClassPathFileContent("templates/base-config-velocity-template.vtl") - val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-velocity.json") - - val content = BlueprintVelocityTemplateService.generateContent(template, json) - assertNotNull(content, "failed to generate content for velocity template") - } - } - - @Test - fun testJinjaGeneratedContent() { - runBlocking { - val template = JacksonUtils.getClassPathFileContent("templates/master.jinja") - val json = JacksonUtils.getClassPathFileContent("templates/base-config-data-jinja.json") - - val element: MutableMap = mutableMapOf() - element["additional_array"] = arrayListOf( - hashMapOf("name" to "Element1", "location" to "Region0"), - hashMapOf("name" to "Element2", "location" to "Region1") - ) - - val content = BlueprintJinjaTemplateService.generateContent(template, json, false, element) - assertNotNull(content, "failed to generate content for velocity template") - } - } - - @Test - fun `no value variable should evaluate to default value - standalone template mesh test`() { - runBlocking { - val template = - JacksonUtils.getClassPathFileContent("templates/default-variable-value-velocity-template.vtl") - val json = JacksonUtils.getClassPathFileContent("templates/default-variable-value-data.json") - - val content = BlueprintVelocityTemplateService.generateContent(template, json) - // first line represents a variable whose value was successfully retrieved, second line contains a variable - // whose value could not be evaluated - val expected = "sample-hostname\n\${node0_backup_router_address}" - assertEquals(expected, content, "No value variable should use default value") - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowServiceTest.kt deleted file mode 100644 index 291a81f28..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintWorkflowServiceTest.kt +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.service - -import io.mockk.every -import io.mockk.mockk -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.async -import kotlinx.coroutines.awaitAll -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel -import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.toGraph -import kotlin.test.assertNotNull - -class BlueprintWorkflowServiceTest { - - @Test - fun testSimpleFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>E/SUCCESS, E>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testMultipleFlows() { - runBlocking { - coroutineScope { - val wfs = listOf("12345", "12346").map { - async { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null) - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(it), it) - assertNotNull(response, "failed to get response") - } - } - wfs.awaitAll() - } - } - } - - @Test - fun testMissingEdgeForBFailureState() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), arrayListOf("B")) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testBExceptionFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, B>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "C", "D", "E"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testTimeoutExceptionFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>TO/SUCCESS, TO>C/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "TO", "C", "D", "E"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testConditionalFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testBothConditionalFlow() { - runBlocking { - // Failure Flow - val failurePatGraph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val failurePathWorkflow = TestBlueprintWorkFlowService() - failurePathWorkflow.simulatedState = prepareSimulation( - arrayListOf("B", "C", "D", "E"), - arrayListOf("A") - ) - val failurePathWorkflowInput = "123456" - val failurePathResponse = failurePathWorkflow.executeWorkflow(failurePatGraph, mockBlueprintRuntimeService(), failurePathWorkflowInput) - assertNotNull(failurePathResponse, "failed to get response") - } - } - - @Test - fun testMultipleSkipFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/FAILURE, C>D/SUCCESS, D>E/SUCCESS, B>E/SUCCESS, E>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D", "E"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - @Test - fun testParallelFlow() { - runBlocking { - val graph = "[START>A/SUCCESS, A>B/SUCCESS, A>C/SUCCESS, B>D/SUCCESS, C>D/SUCCESS, D>END/SUCCESS]" - .toGraph() - val simpleWorkflow = TestBlueprintWorkFlowService() - simpleWorkflow.simulatedState = prepareSimulation(arrayListOf("A", "B", "C", "D"), null) - val input = "123456" - val response = simpleWorkflow.executeWorkflow(graph, mockBlueprintRuntimeService(), input) - assertNotNull(response, "failed to get response") - } - } - - private fun mockBlueprintRuntimeService(): BlueprintRuntimeService<*> { - return mockBlueprintRuntimeService("123456") - } - - private fun mockBlueprintRuntimeService(id: String): BlueprintRuntimeService<*> { - val bluePrintRuntimeService = mockk>() - every { bluePrintRuntimeService.id() } returns id - return bluePrintRuntimeService - } - - private fun prepareSimulation(successes: List?, failures: List?): MutableMap { - val simulatedState: MutableMap = hashMapOf() - successes?.forEach { - simulatedState[it] = EdgeLabel.SUCCESS - } - failures?.forEach { - simulatedState[it] = EdgeLabel.FAILURE - } - return simulatedState - } -} - -class TestBlueprintWorkFlowService : - AbstractBlueprintWorkFlowService() { - - val log = logger(TestBlueprintWorkFlowService::class) - - lateinit var simulatedState: MutableMap - - override suspend fun initializeWorkflow(input: String): EdgeLabel { - return EdgeLabel.SUCCESS - } - - override suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BlueprintRuntimeService<*>, input: String): String { - log.info("Executing Graph : $graph") - this.graph = graph - this.workflowId = bluePrintRuntimeService.id() - val output = CompletableDeferred() - val startMessage = WorkflowExecuteMessage(input, output) - val workflowActor = workflowActor() - if (!workflowActor.isClosedForSend) { - workflowActor().send(startMessage) - } else { - throw BlueprintProcessorException("workflow actor is closed for send $workflowActor") - } - return startMessage.output.await() - } - - override suspend fun prepareNodeExecutionMessage(node: Graph.Node): - NodeExecuteMessage { - return NodeExecuteMessage(node, "$node Input", "") - } - - override suspend fun executeNode( - node: Graph.Node, - nodeInput: String, - nodeOutput: String - ): EdgeLabel { - // val random = (1..10).random() * 100 - // log.info("workflow($workflowId) node(${node.id}) will reply in $random ms") - // kotlinx.coroutines.delay(random.toLong()) - // //Simulation for timeout - if (node.id == "TO") { - withTimeout(1) { - kotlinx.coroutines.delay(2) - } - } - return simulatedState[node.id] ?: throw BlueprintException("failed to get status for the node($node)") - } - - override suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage { - val nodeOutput = "" - return NodeSkipMessage(node, "$node Skip Input", nodeOutput) - } - - override suspend fun skipNode( - node: Graph.Node, - nodeInput: String, - nodeOutput: String - ): EdgeLabel { - return simulatedState[node.id] ?: throw BlueprintException("failed to get status for the node($node)") - } - - override suspend fun cancelNode( - node: Graph.Node, - nodeInput: String, - nodeOutput: String - ): EdgeLabel { - TODO("not implemented") // To change body of created functions use File | Settings | File Templates. - } - - override suspend fun restartNode( - node: Graph.Node, - nodeInput: String, - nodeOutput: String - ): EdgeLabel { - TODO("not implemented") // To change body of created functions use File | Settings | File Templates. - } - - override suspend fun prepareWorkflowOutput(): String { - if (exceptions.isNotEmpty()) { - exceptions.forEach { - log.error("workflow($workflowId) exceptions :", it) - } - } - return "Final Response" - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt new file mode 100644 index 000000000..6e19656ec --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import java.io.File +import java.nio.file.Paths +import kotlin.test.assertTrue + +class BluePrintFileUtilsTest { + + @Test + fun testNewBlueprint() = runBlocking { + val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-new-test") + BluePrintFileUtils.createEmptyBluePrint(targetPath) + } + + @Test + fun testBlueprintCopy() = runBlocking { + val sourcePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG + + val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-copy-test") + + val targetDir = File(targetPath) + targetDir.deleteOnExit() + // Copy the BP file + BluePrintFileUtils.copyBluePrint(sourcePath, targetDir.absolutePath) + + assertTrue(targetDir.exists(), "faield to copy blueprint to ${targetDir.absolutePath}") + + // Delete Type Files + BluePrintFileUtils.deleteBluePrintTypes(targetDir.absolutePath) + + // Generate the Type Files + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(sourcePath) + bluePrintContext.rootPath = targetDir.absolutePath + + BluePrintFileUtils.writeBluePrintTypes(bluePrintContext) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt new file mode 100644 index 000000000..62bb0afcb --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt @@ -0,0 +1,41 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintRetryException + +class BluePrintIOUtilsTest { + + @Test + fun testRetry() { + runBlocking { + val executionBlock: suspend (Int) -> String = { count: Int -> + "success" + } + val exceptionBlock = { e: Exception -> + if (e is BluePrintRetryException) { + println("this is blueprint error") + } else { + throw e + } + } + BluePrintIOUtils.retry(4, 0, 500, executionBlock, exceptionBlock) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt new file mode 100644 index 000000000..6ccfe1e95 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.core.utils + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants +import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class BluePrintMetadataUtilsTest { + + @Test + fun testToscaMetaData() { + + runBlocking { + val basePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG + + val toscaMetaData: ToscaMetaData = BluePrintMetadataUtils.toscaMetaData(basePath) + assertNotNull(toscaMetaData, "Missing Tosca Definition Object") + assertNotNull(toscaMetaData.toscaMetaFileVersion, "Missing Tosca Metadata Version") + assertNotNull(toscaMetaData.csarVersion, "Missing CSAR version") + assertNotNull(toscaMetaData.createdBy, "Missing Created by") + assertNotNull(toscaMetaData.entityDefinitions, "Missing Tosca Entity Definition") + assertNotNull(toscaMetaData.templateTags, "Missing Template Tags") + } + } + + @Test + fun testKotlinBluePrintContext() { + runBlocking { + val path = normalizedPathName("src/test/resources/compile") + val blueprintContext = BluePrintMetadataUtils.getBluePrintContext(path) + assertNotNull(blueprintContext, "failed to get blueprint context") + assertNotNull(blueprintContext.serviceTemplate, "failed to get blueprint context service template") + assertNotNull(blueprintContext.serviceTemplate, "failed to get blueprint context service template") + assertNotNull(blueprintContext.otherDefinitions, "failed to get blueprint contextother definitions") + + var cachePresent = BluePrintCompileCache.hasClassLoader(path) + assertTrue(cachePresent, "failed to generate cache key ($path)") + + /** Cleaning Cache */ + BluePrintCompileCache.cleanClassLoader(path) + cachePresent = BluePrintCompileCache.hasClassLoader(path) + assertTrue(!cachePresent, "failed to remove cache key ($path)") + } + } + + @Test + fun environmentDataTest() { + val environmentPath = "./src/test/resources/environments" + + val properties = BluePrintMetadataUtils.bluePrintEnvProperties(environmentPath) + + assertNotNull(properties, "Could not read the properties") + assertEquals(properties.getProperty("blueprintsprocessor.database.alt1.username"), "username1", "failed 1") + assertEquals(properties.getProperty("blueprintsprocessor.database.alt1.password"), "password1", "failed 2") + assertEquals(properties.getProperty("blueprintsprocessor.database.alt2.username"), "username2", "failed 3") + assertEquals(properties.getProperty("blueprintsprocessor.database.alt2.password"), "password2", "failed 4") + assertNull(properties.getProperty("blueprintsprocessor.database.alt3.password"), "failed 5") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtilsTest.kt deleted file mode 100644 index ac74f7ab1..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintFileUtilsTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import java.io.File -import java.nio.file.Paths -import kotlin.test.assertTrue - -class BlueprintFileUtilsTest { - - @Test - fun testNewBlueprint() = runBlocking { - val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-new-test") - BlueprintFileUtils.createEmptyBlueprint(targetPath) - } - - @Test - fun testBlueprintCopy() = runBlocking { - val sourcePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG - - val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-copy-test") - - val targetDir = File(targetPath) - targetDir.deleteOnExit() - // Copy the BP file - BlueprintFileUtils.copyBlueprint(sourcePath, targetDir.absolutePath) - - assertTrue(targetDir.exists(), "faield to copy blueprint to ${targetDir.absolutePath}") - - // Delete Type Files - BlueprintFileUtils.deleteBlueprintTypes(targetDir.absolutePath) - - // Generate the Type Files - val bluePrintContext = BlueprintMetadataUtils.getBlueprintContext(sourcePath) - bluePrintContext.rootPath = targetDir.absolutePath - - BlueprintFileUtils.writeBlueprintTypes(bluePrintContext) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtilsTest.kt deleted file mode 100644 index d0c32cc39..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintIOUtilsTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintRetryException - -class BlueprintIOUtilsTest { - - @Test - fun testRetry() { - runBlocking { - val executionBlock: suspend (Int) -> String = { count: Int -> - "success" - } - val exceptionBlock = { e: Exception -> - if (e is BlueprintRetryException) { - println("this is blueprint error") - } else { - throw e - } - } - BlueprintIOUtils.retry(4, 0, 500, executionBlock, exceptionBlock) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtilsTest.kt deleted file mode 100644 index b03fb9fc1..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintMetadataUtilsTest.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.core.utils - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants -import org.onap.ccsdk.cds.controllerblueprints.core.data.ToscaMetaData -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintCompileCache -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.assertTrue - -class BlueprintMetadataUtilsTest { - - @Test - fun testToscaMetaData() { - - runBlocking { - val basePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG - - val toscaMetaData: ToscaMetaData = BlueprintMetadataUtils.toscaMetaData(basePath) - assertNotNull(toscaMetaData, "Missing Tosca Definition Object") - assertNotNull(toscaMetaData.toscaMetaFileVersion, "Missing Tosca Metadata Version") - assertNotNull(toscaMetaData.csarVersion, "Missing CSAR version") - assertNotNull(toscaMetaData.createdBy, "Missing Created by") - assertNotNull(toscaMetaData.entityDefinitions, "Missing Tosca Entity Definition") - assertNotNull(toscaMetaData.templateTags, "Missing Template Tags") - } - } - - @Test - fun testKotlinBlueprintContext() { - runBlocking { - val path = normalizedPathName("src/test/resources/compile") - val blueprintContext = BlueprintMetadataUtils.getBlueprintContext(path) - assertNotNull(blueprintContext, "failed to get blueprint context") - assertNotNull(blueprintContext.serviceTemplate, "failed to get blueprint context service template") - assertNotNull(blueprintContext.serviceTemplate, "failed to get blueprint context service template") - assertNotNull(blueprintContext.otherDefinitions, "failed to get blueprint contextother definitions") - - var cachePresent = BlueprintCompileCache.hasClassLoader(path) - assertTrue(cachePresent, "failed to generate cache key ($path)") - - /** Cleaning Cache */ - BlueprintCompileCache.cleanClassLoader(path) - cachePresent = BlueprintCompileCache.hasClassLoader(path) - assertTrue(!cachePresent, "failed to remove cache key ($path)") - } - } - - @Test - fun environmentDataTest() { - val environmentPath = "./src/test/resources/environments" - - val properties = BlueprintMetadataUtils.bluePrintEnvProperties(environmentPath) - - assertNotNull(properties, "Could not read the properties") - assertEquals(properties.getProperty("blueprintsprocessor.database.alt1.username"), "username1", "failed 1") - assertEquals(properties.getProperty("blueprintsprocessor.database.alt1.password"), "password1", "failed 2") - assertEquals(properties.getProperty("blueprintsprocessor.database.alt2.username"), "username2", "failed 3") - assertEquals(properties.getProperty("blueprintsprocessor.database.alt2.password"), "password2", "failed 4") - assertNull(properties.getProperty("blueprintsprocessor.database.alt3.password"), "failed 5") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt index ec12639fb..d78e62f28 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt @@ -18,7 +18,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.slf4j.LoggerFactory import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -57,19 +57,19 @@ class JacksonUtilsTest { val rootJson = JacksonUtils.jsonNodeFromClassPathFile(filePath) assertNotNull(rootJson, "Failed to get all type data json node") val intValue = rootJson.get("intValue") - assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_INTEGER, intValue), "Failed to get as int value") + assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_INTEGER, intValue), "Failed to get as int value") val floatValue = rootJson.get("floatValue") - assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_FLOAT, floatValue), "Failed to get as float value") + assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_FLOAT, floatValue), "Failed to get as float value") val stringValue = rootJson.get("stringValue") - assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_STRING, stringValue), "Failed to get as string value") + assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_STRING, stringValue), "Failed to get as string value") val booleanValue = rootJson.get("booleanValue") - assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_BOOLEAN, booleanValue), "Failed to get as boolean value") + assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_BOOLEAN, booleanValue), "Failed to get as boolean value") val arrayStringValue = rootJson.get("arrayStringValue") - assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_LIST, arrayStringValue), "Failed to get as List value") + assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_LIST, arrayStringValue), "Failed to get as List value") // FIX needed for ("complex type JSON & MAP") // val mapValue = rootJson.get("mapValue") - // assertTrue(JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_MAP, mapValue), "Failed to get as Map value") + // assertTrue(JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_MAP, mapValue), "Failed to get as Map value") - assertTrue(!JacksonUtils.checkJsonNodeValueOfType(BlueprintConstants.DATA_TYPE_LIST, stringValue), "Negative type failed") + assertTrue(!JacksonUtils.checkJsonNodeValueOfType(BluePrintConstants.DATA_TYPE_LIST, stringValue), "Negative type failed") } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtilsTest.kt index f2d63531d..83764c517 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtilsTest.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/PropertyDefinitionUtilsTest.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.controllerblueprints.core.utils import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.LOG_PROTECT +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.LOG_PROTECT import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils.Companion.hasLogProtect import kotlin.test.assertFalse diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt index 4ba7694ee..5dd1937f8 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt @@ -16,13 +16,13 @@ package cba.scripts -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dataType import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.AbstractBlueprintDefinitions +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.AbstractBluePrintDefinitions -class ActivateBlueprintDefinitions : AbstractBlueprintDefinitions() { +class ActivateBlueprintDefinitions : AbstractBluePrintDefinitions() { override fun serviceTemplate(): ServiceTemplate { @@ -46,10 +46,10 @@ class ActivateBlueprintDefinitions : AbstractBlueprintDefinitions() { /** Sample Definitions */ val customDataType = dataType( "custom-datatype", "1.0.0", - BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT, "" + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, "" ) { - property("name", BlueprintConstants.DATA_TYPE_STRING, true, "") - property("value", BlueprintConstants.DATA_TYPE_STRING, true, "") + property("name", BluePrintConstants.DATA_TYPE_STRING, true, "") + property("value", BluePrintConstants.DATA_TYPE_STRING, true, "") } /** Loading to definitions */ addOtherDefinition("datatype-custom-datatype", customDataType) diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt new file mode 100644 index 000000000..73504314b --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt @@ -0,0 +1,99 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service +import java.io.File + +@Service("default-artifact-definition-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintArtifactDefinitionValidatorImpl( + private val bluePrintTypeValidatorService: BluePrintTypeValidatorService +) : BluePrintArtifactDefinitionValidator { + + private val log = LoggerFactory.getLogger(BluePrintArtifactDefinitionValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + var paths: MutableList = arrayListOf() + + override fun validate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + artifactDefinition: ArtifactDefinition + ) { + + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + paths.add(name) + val type: String = artifactDefinition.type + log.trace("Validation ArtifactDefinition of type {$type}") + // Check Artifact Type + checkValidArtifactType(name, type) + + val file: String = artifactDefinition.file + + val completePath = bluePrintContext.rootPath.plus(File.separator).plus(file) + + check(File(completePath).exists()) { + throw BluePrintException("couldn't find file ($completePath)") + } + + // Perform Extension Validation + validateExtension("$type-artifact-definition-validator", name, artifactDefinition) + + paths.removeAt(paths.lastIndex) + } + + open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) { + + val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) + ?: throw BluePrintException("failed to get artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)") + + checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom) + } + + @Throws(BluePrintException::class) + open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition") + } + } + + private fun validateExtension(referencePrefix: String, name: String, artifactDefinition: ArtifactDefinition) { + + val customValidators = bluePrintTypeValidatorService + .bluePrintValidators(referencePrefix, BluePrintArtifactDefinitionValidator::class.java) + + customValidators?.let { + it.forEach { validator -> + validator.validate(bluePrintRuntimeService, name, artifactDefinition) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt new file mode 100644 index 000000000..b31211e2d --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt @@ -0,0 +1,36 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.stereotype.Service + +@Service("default-artifact-type-validator") +open class BluePrintArtifactTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintArtifactTypeValidator { + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) { + + artifactType.properties?.let { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, artifactType.properties!!) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt new file mode 100644 index 000000000..9a4650104 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.format +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-attribute-definition-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintAttributeDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintAttributeDefinitionValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun validate( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + attributeDefinition: AttributeDefinition + ) { + + log.trace("Validating AttributeDefinition($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + val dataType: String = attributeDefinition.type + + when { + BluePrintTypes.validPrimitiveTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validComplexTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validCollectionTypes().contains(dataType) -> { + val entrySchemaType: String = attributeDefinition.entrySchema?.type + ?: throw BluePrintException("Entry schema for DataType ($dataType) for the property ($name) not found") + checkPrimitiveOrComplex(entrySchemaType, name) + } + else -> checkPropertyDataType(dataType, name) + } + } + + private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { + if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { + return true + } else { + throw BluePrintException("DataType($dataType) for the attribute($propertyName) is not valid") + } + } + + private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { + + val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName) + ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) + + checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) + } + + private fun checkDataType(key: String): Boolean { + return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false + } + + open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ") + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt new file mode 100644 index 000000000..dab6a78bc --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt @@ -0,0 +1,35 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.stereotype.Service + +@Service("default-data-type-validator") +open class BluePrintDataTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintDataTypeValidator { + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, dataType: DataType) { + dataType.properties?.let { + + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, dataType.properties!!) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt new file mode 100644 index 000000000..ac5773c76 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt @@ -0,0 +1,86 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants +import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service +import java.io.File +import java.util.UUID + +@Service("bluePrintDesignTimeValidatorService") +open class BluePrintDesignTimeValidatorService( + private val bluePrintTypeValidatorService: BluePrintTypeValidatorService, + private val resourceDefinitionValidator: ResourceDefinitionValidator +) : + BluePrintValidatorService { + + private val log = LoggerFactory.getLogger(BluePrintDesignTimeValidatorService::class.toString()) + + override suspend fun validateBluePrints(basePath: String): Boolean { + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(UUID.randomUUID().toString(), basePath) + return validateBluePrints(bluePrintRuntimeService) + } + + override suspend fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean { + + bluePrintTypeValidatorService.validateServiceTemplate( + bluePrintRuntimeService, "service_template", + bluePrintRuntimeService.bluePrintContext().serviceTemplate + ) + + // Validate Resource Definitions + validateResourceDefinitions(bluePrintRuntimeService) + + bluePrintRuntimeService.getBluePrintError().allErrors().ifNotEmpty { + throw BluePrintException("failed in blueprint validation : ${this.joinToString("\n")}") + } + + return true + } + + private fun validateResourceDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>) { + // Validate Resource Dictionary + val blueprintBasePath = bluePrintRuntimeService.bluePrintContext().rootPath + + val resourceDefinitionsPath = blueprintBasePath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator) + .plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json") + + val resourceDefinitionFile = File(resourceDefinitionsPath) + + if (resourceDefinitionFile.exists()) { + val resourceDefinitionMap = JacksonUtils.getMapFromFile(resourceDefinitionFile, ResourceDefinition::class.java) + + resourceDefinitionMap.forEach { resourceDefinitionName, resourceDefinition -> + resourceDefinitionValidator.validate(bluePrintRuntimeService, resourceDefinitionName, resourceDefinition) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTemplateValidatorImpl.kt new file mode 100644 index 000000000..6fa83119e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTemplateValidatorImpl.kt @@ -0,0 +1,274 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018-2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-node-template-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintNodeTemplateValidator { + + private val log = LoggerFactory.getLogger(BluePrintNodeTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + lateinit var propertyAssignmentValidationUtils: PropertyAssignmentValidationUtils + var paths: MutableList = arrayListOf() + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + log.debug("Validating NodeTemplate($name)") + + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + propertyAssignmentValidationUtils = PropertyAssignmentValidationUtils(bluePrintContext) + + paths.add(name) + + val type: String = nodeTemplate.type + + val nodeType: NodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(type) + ?: throw BluePrintException("Failed to get NodeType($type) definition for NodeTemplate($name)") + + nodeTemplate.properties?.let { + propertyAssignmentValidationUtils + .validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) + } + nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, name, nodeTemplate) } + nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, name, nodeTemplate) } + nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeType, name, nodeTemplate) } + nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) } + + // Perform Extension Validation + validateExtension("$type-node-template-validator", name, nodeTemplate) + + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateArtifactDefinitions(artifacts: MutableMap) { + paths.add("artifacts") + artifacts.forEach { artifactDefinitionName, artifactDefinition -> + bluePrintTypeValidatorService.validateArtifactDefinition( + bluePrintRuntimeService, + artifactDefinitionName, artifactDefinition + ) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val capabilities = nodeTemplate.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityAssignment -> + paths.add(capabilityName) + + val capabilityDefinition = nodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + "Failed to get NodeTemplate($nodeTemplateName) capability definition ($capabilityName) " + + "from NodeType(${nodeTemplate.type})" + ) + + validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateCapabilityAssignment( + nodeTemplateName: String, + capabilityName: String, + capabilityDefinition: CapabilityDefinition, + capabilityAssignment: CapabilityAssignment + ) { + + capabilityAssignment.properties?.let { + propertyAssignmentValidationUtils + .validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) + } + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + val requirements = nodeTemplate.requirements + paths.add("requirements") + requirements?.forEach { requirementName, requirementAssignment -> + paths.add(requirementName) + val requirementDefinition = nodeType.requirements?.get(requirementName) + ?: throw BluePrintException( + "Failed to get NodeTemplate($nodeTemplateName) requirement definition ($requirementName) from" + + " NodeType(${nodeTemplate.type})" + ) + // Validate Requirement Assignment + validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateRequirementAssignment( + nodeTemplateName: String, + requirementAssignmentName: String, + requirementDefinition: RequirementDefinition, + requirementAssignment: RequirementAssignment + ) { + log.debug( + "Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, + requirementAssignmentName + ) + val requirementNodeTemplateName = requirementAssignment.node!! + val capabilityName = requirementAssignment.capability + val relationship = requirementAssignment.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException("Failed to get relationship type ($relationship) for NodeTemplate($nodeTemplateName)'s requirement($requirementAssignmentName)") + } + + val relationShipNodeTemplate = bluePrintContext.serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName) + ?: throw BluePrintException( + "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " + + "for NodeTemplate($nodeTemplateName) requirement($requirementAssignmentName)" + ) + + relationShipNodeTemplate.capabilities?.get(capabilityName) + ?: throw BluePrintException( + "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " + + "capability($capabilityName) for NodeTemplate ($nodeTemplateName)'s requirement($requirementAssignmentName)" + ) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { + + val interfaces = nodeTemplate.interfaces + paths.add("interfaces") + interfaces?.forEach { interfaceAssignmentName, interfaceAssignment -> + paths.add(interfaceAssignmentName) + val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName) + ?: throw BluePrintException( + "Failed to get NodeTemplate($nodeTemplateName) interface definition ($interfaceAssignmentName) from" + + " NodeType(${nodeTemplate.type})" + ) + + validateInterfaceAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + @Throws(BluePrintException::class) + open fun validateInterfaceAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + validateInterfaceOperationsAssignment( + nodeTemplateName, interfaceAssignmentName, interfaceDefinition, + interfaceAssignment + ) + } + } + + @Throws(BluePrintException::class) + open fun validateInterfaceOperationsAssignment( + nodeTemplateName: String, + interfaceAssignmentName: String, + interfaceDefinition: InterfaceDefinition, + interfaceAssignment: InterfaceAssignment + ) { + + val operations = interfaceAssignment.operations + operations?.let { + it.forEach { operationAssignmentName, operationAssignments -> + + val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName) + ?: throw BluePrintException("Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName)") + + log.debug( + "Validation NodeTemplate($nodeTemplateName) Interface($interfaceAssignmentName) Operation " + + "($operationAssignmentName)" + ) + + val inputs = operationAssignments.inputs + val outputs = operationAssignments.outputs + + inputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.inputs?.get(propertyName) + ?: throw BluePrintException( + "Failed to get NodeTemplate($nodeTemplateName) operation " + + "definition ($operationAssignmentName) property definition($propertyName)" + ) + // Check the property values with property definition + propertyAssignmentValidationUtils + .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + + outputs?.forEach { propertyName, propertyAssignment -> + val propertyDefinition = operationDefinition.outputs?.get(propertyName) + ?: throw BluePrintException( + "Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName) " + + "output property definition($propertyName)" + ) + // Check the property values with property definition + propertyAssignmentValidationUtils + .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) + } + } + } + } + + private fun validateExtension(referencePrefix: String, name: String, nodeTemplate: NodeTemplate) { + val customValidator = bluePrintTypeValidatorService + .bluePrintValidator(referencePrefix, BluePrintNodeTemplateValidator::class.java) + + customValidator?.let { + it.validate(bluePrintRuntimeService, name, nodeTemplate) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTypeValidatorImpl.kt new file mode 100644 index 000000000..04a3fd046 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTypeValidatorImpl.kt @@ -0,0 +1,179 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-node-type-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintNodeTypeValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + var paths: MutableList = arrayListOf() + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTypeName: String, nodeType: NodeType) { + log.trace("Validating NodeType($nodeTypeName)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + paths.add(nodeTypeName) + + val derivedFrom: String = nodeType.derivedFrom + // Check Derived From + checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom) + + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + bluePrintContext.serviceTemplate.nodeTypes?.get(derivedFrom) + ?: throw BluePrintException("Failed to get derivedFrom NodeType($derivedFrom)'s for NodeType($nodeTypeName)") + } + + nodeType.attributes?.let { + bluePrintTypeValidatorService.validateAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) + } + + nodeType.properties?.let { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) + } + + nodeType.capabilities?.let { validateCapabilityDefinitions(nodeTypeName, nodeType) } + nodeType.requirements?.let { validateRequirementDefinitions(nodeTypeName, nodeType) } + nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) } + + paths.removeAt(paths.lastIndex) + } + + fun checkValidNodeTypesDerivedFrom(nodeTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validNodeTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("Failed to get node type ($nodeTypeName)'s derivedFrom($derivedFrom) definition ") + } + } + + open fun validateCapabilityDefinitions(nodeTypeName: String, nodeType: NodeType) { + val capabilities = nodeType.capabilities + paths.add("capabilities") + capabilities?.forEach { capabilityName, capabilityDefinition -> + paths.add(capabilityName) + + validateCapabilityDefinition(nodeTypeName, nodeType, capabilityName, capabilityDefinition) + + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + open fun validateCapabilityDefinition( + nodeTypeName: String, + nodeType: NodeType, + capabilityName: String, + capabilityDefinition: CapabilityDefinition + ) { + val capabilityType = capabilityDefinition.type + check(BluePrintTypes.validCapabilityTypes.contains(capabilityType)) { + throw BluePrintException("failed to get CapabilityType($capabilityType) for NodeType($nodeTypeName)") + } + } + + open fun validateRequirementDefinitions(nodeName: String, nodeType: NodeType) { + paths.add("requirements") + val requirements = nodeType.requirements + + requirements?.forEach { requirementDefinitionName, requirementDefinition -> + paths.add(requirementDefinitionName) + validateRequirementDefinition(nodeName, nodeType, requirementDefinitionName, requirementDefinition) + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + open fun validateRequirementDefinition( + nodeTypeName: String, + nodeType: NodeType, + requirementDefinitionName: String, + requirementDefinition: RequirementDefinition + ) { + + log.info("validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName) + val requirementNodeTypeName = requirementDefinition.node!! + val capabilityName = requirementDefinition.capability + val relationship = requirementDefinition.relationship!! + + check(BluePrintTypes.validRelationShipDerivedFroms.contains(relationship)) { + throw BluePrintException("failed to get relationship($relationship) for NodeType($nodeTypeName)'s requirement($requirementDefinitionName)") + } + + val relationShipNodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(requirementNodeTypeName) + ?: throw BluePrintException("failed to get requirement NodeType($requirementNodeTypeName)'s for requirement($requirementDefinitionName) ") + + relationShipNodeType.capabilities?.get(capabilityName) + ?: throw BluePrintException( + "failed to get requirement NodeType($requirementNodeTypeName)'s " + + "capability($nodeTypeName) for NodeType ($capabilityName)'s requirement($requirementDefinitionName) " + ) + } + + open fun validateInterfaceDefinitions(interfaces: MutableMap) { + paths.add("interfaces") + interfaces.forEach { interfaceName, interfaceDefinition -> + paths.add(interfaceName) + interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + open fun validateOperationDefinitions(operations: MutableMap) { + paths.add("operations") + operations.forEach { opertaionName, operationDefinition -> + paths.add(opertaionName) + operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) } + + operationDefinition.inputs?.let { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.inputs!!) + } + + operationDefinition.outputs?.let { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.outputs!!) + } + paths.removeAt(paths.lastIndex) + } + paths.removeAt(paths.lastIndex) + } + + open fun validateImplementation(implementation: Implementation) { + checkNotEmpty(implementation.primary) { "couldn't get implementation" } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt new file mode 100644 index 000000000..5683c0170 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt @@ -0,0 +1,89 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.format +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-property-definition-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintPropertyDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintPropertyDefinitionValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + this.bluePrintRuntimeService = bluePrintRuntimeService + + log.trace("Validating PropertyDefinition($name)") + + val dataType: String = propertyDefinition.type + + when { + BluePrintTypes.validPrimitiveTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validComplexTypes().contains(dataType) -> { + // Do Nothing + } + BluePrintTypes.validCollectionTypes().contains(dataType) -> { + val entrySchemaType: String = propertyDefinition.entrySchema?.type + ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, name)) + checkPrimitiveOrComplex(entrySchemaType, name) + } + else -> checkPropertyDataType(dataType, name) + } + } + + private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { + if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { + return true + } else { + throw BluePrintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName)) + } + } + + private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { + + val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName) + ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) + + checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) + } + + private fun checkDataType(key: String): Boolean { + return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false + } + + open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { + check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom)) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt new file mode 100644 index 000000000..b01116fcb --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import com.google.common.base.Preconditions +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-service-template-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintServiceTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintServiceTemplateValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var error: BluePrintError + + var paths: MutableList = arrayListOf() + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { + log.trace("Validating Service Template..") + try { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.error = bluePrintRuntimeService.getBluePrintError() + + serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) } + serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) } + serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) } + serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) } + serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) } + } catch (e: Exception) { + log.error("failed in blueprint service template validation", e) + error.addError(BluePrintConstants.PATH_SERVICE_TEMPLATE, paths.joinToString(BluePrintConstants.PATH_DIVIDER), e.message!!, "BlueprintServiceTemplateValidator") + } + } + + fun validateMetadata(metaDataMap: MutableMap) { + + paths.add(BluePrintConstants.PATH_METADATA) + + val templateName = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_NAME] + val templateVersion = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_VERSION] + val templateTags = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_TAGS] + val templateAuthor = metaDataMap[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + + Preconditions.checkArgument(StringUtils.isNotBlank(templateName), "failed to get template name metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateVersion), "failed to get template version metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateTags), "failed to get template tags metadata") + Preconditions.checkArgument(StringUtils.isNotBlank(templateAuthor), "failed to get template author metadata") + + paths.removeAt(paths.lastIndex) + } + + fun validateDataTypes(dataTypes: MutableMap) { + + paths.add(BluePrintConstants.PATH_DATA_TYPES) + dataTypes.forEach { dataTypeName, dataType -> + // Validate Single Data Type + bluePrintTypeValidatorService.validateDataType(bluePrintRuntimeService, dataTypeName, dataType) + } + paths.removeAt(paths.lastIndex) + } + + fun validateArtifactTypes(artifactTypes: MutableMap) { + paths.add(BluePrintConstants.PATH_ARTIFACT_TYPES) + artifactTypes.forEach { artifactName, artifactType -> + // Validate Single Artifact Type + bluePrintTypeValidatorService.validateArtifactType(bluePrintRuntimeService, artifactName, artifactType) + } + paths.removeAt(paths.lastIndex) + } + + fun validateNodeTypes(nodeTypes: MutableMap) { + paths.add(BluePrintConstants.PATH_NODE_TYPES) + nodeTypes.forEach { nodeTypeName, nodeType -> + // Validate Single Node Type + bluePrintTypeValidatorService.validateNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) + } + paths.removeAt(paths.lastIndex) + } + + fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) { + paths.add(BluePrintConstants.PATH_TOPOLOGY_TEMPLATE) + bluePrintTypeValidatorService.validateTopologyTemplate(bluePrintRuntimeService, "topologyTemplate", topologyTemplate) + paths.removeAt(paths.lastIndex) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt new file mode 100644 index 000000000..a7fb3d57e --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt @@ -0,0 +1,76 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-topology-template-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintTopologyTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintTopologyTemplateValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { + log.trace("Validating Topology Template..") + this.bluePrintRuntimeService = bluePrintRuntimeService + + // Validate Inputs + topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) } + // Validate Node Templates + topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) } + // Validate Workflow + topologyTemplate.workflows?.let { validateWorkflows(topologyTemplate.workflows!!) } + } + + @Throws(BluePrintException::class) + fun validateInputs(inputs: MutableMap) { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, inputs) + } + + @Throws(BluePrintException::class) + fun validateNodeTemplates(nodeTemplates: MutableMap) { + + nodeTemplates.forEach { nodeTemplateName, nodeTemplate -> + // Validate Single Node Template + bluePrintTypeValidatorService.validateNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) + } + } + + @Throws(BluePrintException::class) + open fun validateWorkflows(workflows: MutableMap) { + + workflows.forEach { workflowName, workflow -> + // Validate Single workflow + bluePrintTypeValidatorService.validateWorkflow(bluePrintRuntimeService, workflowName, workflow) + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt new file mode 100644 index 000000000..db7d91a22 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service + +@Service +class BluePrintTypeValidatorServiceImpl : BluePrintTypeValidatorService { + + companion object { + + const val PREFIX_DEFAULT = "default" + } + + @Autowired + private lateinit var context: ApplicationContext + + override fun > bluePrintValidator(referenceName: String, classType: Class): T? { + return if (context.containsBean(referenceName)) { + context.getBean(referenceName, classType) + } else { + null + } + } + + override fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? { + return context.getBeansOfType(classType) + .filter { it.key.startsWith(referenceNamePrefix) } + .mapNotNull { it.value } + } + + override fun > bluePrintValidators(classType: Class): List? { + return context.getBeansOfType(classType).mapNotNull { it.value } + } + + override fun getServiceTemplateValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintServiceTemplateValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default ServiceTemplate validators") + } + + override fun getDataTypeValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintDataTypeValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default DataType validators") + } + + override fun getArtifactTypeValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactTypeValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default ArtifactType validators") + } + + override fun getArtifactDefinitionsValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactDefinitionValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default ArtifactDefinition validators") + } + + override fun getNodeTypeValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTypeValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default NodeType validators") + } + + override fun getTopologyTemplateValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintTopologyTemplateValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default TopologyTemplate validators") + } + + override fun getNodeTemplateValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTemplateValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default NodeTemplate validators") + } + + override fun getWorkflowValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintWorkflowValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default Workflow validators") + } + + override fun getPropertyDefinitionValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintPropertyDefinitionValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default PropertyDefinition validators") + } + + override fun getAttributeDefinitionValidators(): List { + return bluePrintValidators(PREFIX_DEFAULT, BluePrintAttributeDefinitionValidator::class.java) + ?: throw BluePrintProcessorException("failed to get default AttributeDefinition validators") + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt new file mode 100644 index 000000000..a1a9eb913 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt @@ -0,0 +1,24 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +open class BluePrintValidationConfiguration diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt new file mode 100644 index 000000000..21923d1f9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt @@ -0,0 +1,110 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("default-workflow-validator") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintWorkflowValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintWorkflowValidator { + + private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString()) + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + var paths: MutableList = arrayListOf() + + override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, workflowName: String, workflow: Workflow) { + log.info("Validating Workflow($workflowName)") + + this.bluePrintRuntimeService = bluePrintRuntimeService + + paths.add(workflowName) + paths.joinToString(BluePrintConstants.PATH_DIVIDER) + + // Validate Workflow Inputs + validateInputs(workflow) + + // Validate Workflow outputs + validateOutputs(workflow) + + // Step Validation Start + paths.add("steps") + workflow.steps?.forEach { stepName, step -> + paths.add(stepName) + paths.joinToString(BluePrintConstants.PATH_DIVIDER) + + // Validate target + step.target?.let { + try { + val nodeTemplate = bluePrintRuntimeService.bluePrintContext().nodeTemplateByName(it) + + val nodeTypeDerivedFrom = bluePrintRuntimeService.bluePrintContext().nodeTemplateNodeType(it).derivedFrom + + check( + nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW || + nodeTypeDerivedFrom == BluePrintConstants.MODEL_TYPE_NODE_COMPONENT + ) { + "NodeType(${nodeTemplate.type}) derived from is '$nodeTypeDerivedFrom', Expected " + + "'${BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW}' or '${BluePrintConstants.MODEL_TYPE_NODE_COMPONENT}'" + } + } catch (e: Exception) { + bluePrintRuntimeService.getBluePrintError() + .addError( + "Failed to validate Workflow($workflowName)'s step($stepName)'s " + + "definition", + paths.joinToString(BluePrintConstants.PATH_DIVIDER), e.message!!, + "BlueprintWorkflowValidatorImpl" + ) + } + } + } + paths.removeAt(paths.lastIndex) + // Step Validation Ends + paths.removeAt(paths.lastIndex) + + paths.removeAt(paths.lastIndex) + } + + private fun validateInputs(workflow: Workflow) { + workflow.inputs?.let { + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, workflow.inputs!!) + } + } + + private fun validateOutputs(workflow: Workflow) { + workflow.outputs?.let { + + bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, workflow.outputs!!) + + PropertyAssignmentValidationUtils(bluePrintRuntimeService.bluePrintContext()) + .validatePropertyDefinitionNAssignments(workflow.outputs!!) + } + // Validate Value or Expression + workflow.outputs?.forEach { propertyName, propertyDefinition -> + } + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactDefinitionValidatorImpl.kt deleted file mode 100644 index d9f4db728..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactDefinitionValidatorImpl.kt +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service -import java.io.File - -@Service("default-artifact-definition-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintArtifactDefinitionValidatorImpl( - private val bluePrintTypeValidatorService: BlueprintTypeValidatorService -) : BlueprintArtifactDefinitionValidator { - - private val log = LoggerFactory.getLogger(BlueprintArtifactDefinitionValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - var paths: MutableList = arrayListOf() - - override fun validate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - artifactDefinition: ArtifactDefinition - ) { - - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - paths.add(name) - val type: String = artifactDefinition.type - log.trace("Validation ArtifactDefinition of type {$type}") - // Check Artifact Type - checkValidArtifactType(name, type) - - val file: String = artifactDefinition.file - - val completePath = bluePrintContext.rootPath.plus(File.separator).plus(file) - - check(File(completePath).exists()) { - throw BlueprintException("couldn't find file ($completePath)") - } - - // Perform Extension Validation - validateExtension("$type-artifact-definition-validator", name, artifactDefinition) - - paths.removeAt(paths.lastIndex) - } - - open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) { - - val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) - ?: throw BlueprintException("failed to get artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)") - - checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom) - } - - @Throws(BlueprintException::class) - open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition") - } - } - - private fun validateExtension(referencePrefix: String, name: String, artifactDefinition: ArtifactDefinition) { - - val customValidators = bluePrintTypeValidatorService - .bluePrintValidators(referencePrefix, BlueprintArtifactDefinitionValidator::class.java) - - customValidators?.let { - it.forEach { validator -> - validator.validate(bluePrintRuntimeService, name, artifactDefinition) - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactTypeValidatorImpl.kt deleted file mode 100644 index ebcdf9f52..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintArtifactTypeValidatorImpl.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.stereotype.Service - -@Service("default-artifact-type-validator") -open class BlueprintArtifactTypeValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintArtifactTypeValidator { - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, artifactType: ArtifactType) { - - artifactType.properties?.let { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, artifactType.properties!!) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintAttributeDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintAttributeDefinitionValidatorImpl.kt deleted file mode 100644 index ef02e84c3..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintAttributeDefinitionValidatorImpl.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.format -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-attribute-definition-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintAttributeDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintAttributeDefinitionValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun validate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - attributeDefinition: AttributeDefinition - ) { - - log.trace("Validating AttributeDefinition($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - val dataType: String = attributeDefinition.type - - when { - BlueprintTypes.validPrimitiveTypes().contains(dataType) -> { - // Do Nothing - } - BlueprintTypes.validComplexTypes().contains(dataType) -> { - // Do Nothing - } - BlueprintTypes.validCollectionTypes().contains(dataType) -> { - val entrySchemaType: String = attributeDefinition.entrySchema?.type - ?: throw BlueprintException("Entry schema for DataType ($dataType) for the property ($name) not found") - checkPrimitiveOrComplex(entrySchemaType, name) - } - else -> checkPropertyDataType(dataType, name) - } - } - - private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { - if (BlueprintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { - return true - } else { - throw BlueprintException("DataType($dataType) for the attribute($propertyName) is not valid") - } - } - - private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { - - val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName) - ?: throw BlueprintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) - - checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) - } - - private fun checkDataType(key: String): Boolean { - return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false - } - - open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ") - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDataTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDataTypeValidatorImpl.kt deleted file mode 100644 index 35680c2ac..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDataTypeValidatorImpl.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintDataTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.stereotype.Service - -@Service("default-data-type-validator") -open class BlueprintDataTypeValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : BlueprintDataTypeValidator { - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, dataType: DataType) { - dataType.properties?.let { - - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, dataType.properties!!) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorService.kt deleted file mode 100644 index aac1c2e97..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorService.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants -import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service -import java.io.File -import java.util.UUID - -@Service("bluePrintDesignTimeValidatorService") -open class BlueprintDesignTimeValidatorService( - private val bluePrintTypeValidatorService: BlueprintTypeValidatorService, - private val resourceDefinitionValidator: ResourceDefinitionValidator -) : - BlueprintValidatorService { - - private val log = LoggerFactory.getLogger(BlueprintDesignTimeValidatorService::class.toString()) - - override suspend fun validateBlueprints(basePath: String): Boolean { - - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime(UUID.randomUUID().toString(), basePath) - return validateBlueprints(bluePrintRuntimeService) - } - - override suspend fun validateBlueprints(bluePrintRuntimeService: BlueprintRuntimeService<*>): Boolean { - - bluePrintTypeValidatorService.validateServiceTemplate( - bluePrintRuntimeService, "service_template", - bluePrintRuntimeService.bluePrintContext().serviceTemplate - ) - - // Validate Resource Definitions - validateResourceDefinitions(bluePrintRuntimeService) - - bluePrintRuntimeService.getBlueprintError().allErrors().ifNotEmpty { - throw BlueprintException("failed in blueprint validation : ${this.joinToString("\n")}") - } - - return true - } - - private fun validateResourceDefinitions(bluePrintRuntimeService: BlueprintRuntimeService<*>) { - // Validate Resource Dictionary - val blueprintBasePath = bluePrintRuntimeService.bluePrintContext().rootPath - - val resourceDefinitionsPath = blueprintBasePath.plus(File.separator) - .plus(BlueprintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator) - .plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json") - - val resourceDefinitionFile = File(resourceDefinitionsPath) - - if (resourceDefinitionFile.exists()) { - val resourceDefinitionMap = JacksonUtils.getMapFromFile(resourceDefinitionFile, ResourceDefinition::class.java) - - resourceDefinitionMap.forEach { resourceDefinitionName, resourceDefinition -> - resourceDefinitionValidator.validate(bluePrintRuntimeService, resourceDefinitionName, resourceDefinition) - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTemplateValidatorImpl.kt deleted file mode 100644 index 0374424e8..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTemplateValidatorImpl.kt +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018-2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementAssignment -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-node-template-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTemplateValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintNodeTemplateValidator { - - private val log = LoggerFactory.getLogger(BlueprintNodeTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - lateinit var propertyAssignmentValidationUtils: PropertyAssignmentValidationUtils - var paths: MutableList = arrayListOf() - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { - log.debug("Validating NodeTemplate($name)") - - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - propertyAssignmentValidationUtils = PropertyAssignmentValidationUtils(bluePrintContext) - - paths.add(name) - - val type: String = nodeTemplate.type - - val nodeType: NodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(type) - ?: throw BlueprintException("Failed to get NodeType($type) definition for NodeTemplate($name)") - - nodeTemplate.properties?.let { - propertyAssignmentValidationUtils - .validatePropertyAssignments(nodeType.properties!!, nodeTemplate.properties!!) - } - nodeTemplate.capabilities?.let { validateCapabilityAssignments(nodeType, name, nodeTemplate) } - nodeTemplate.requirements?.let { validateRequirementAssignments(nodeType, name, nodeTemplate) } - nodeTemplate.interfaces?.let { validateInterfaceAssignments(nodeType, name, nodeTemplate) } - nodeTemplate.artifacts?.let { validateArtifactDefinitions(nodeTemplate.artifacts!!) } - - // Perform Extension Validation - validateExtension("$type-node-template-validator", name, nodeTemplate) - - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateArtifactDefinitions(artifacts: MutableMap) { - paths.add("artifacts") - artifacts.forEach { artifactDefinitionName, artifactDefinition -> - bluePrintTypeValidatorService.validateArtifactDefinition( - bluePrintRuntimeService, - artifactDefinitionName, artifactDefinition - ) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateCapabilityAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - val capabilities = nodeTemplate.capabilities - paths.add("capabilities") - capabilities?.forEach { capabilityName, capabilityAssignment -> - paths.add(capabilityName) - - val capabilityDefinition = nodeType.capabilities?.get(capabilityName) - ?: throw BlueprintException( - "Failed to get NodeTemplate($nodeTemplateName) capability definition ($capabilityName) " + - "from NodeType(${nodeTemplate.type})" - ) - - validateCapabilityAssignment(nodeTemplateName, capabilityName, capabilityDefinition, capabilityAssignment) - - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateCapabilityAssignment( - nodeTemplateName: String, - capabilityName: String, - capabilityDefinition: CapabilityDefinition, - capabilityAssignment: CapabilityAssignment - ) { - - capabilityAssignment.properties?.let { - propertyAssignmentValidationUtils - .validatePropertyAssignments(capabilityDefinition.properties!!, capabilityAssignment.properties!!) - } - } - - @Throws(BlueprintException::class) - open fun validateRequirementAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - val requirements = nodeTemplate.requirements - paths.add("requirements") - requirements?.forEach { requirementName, requirementAssignment -> - paths.add(requirementName) - val requirementDefinition = nodeType.requirements?.get(requirementName) - ?: throw BlueprintException( - "Failed to get NodeTemplate($nodeTemplateName) requirement definition ($requirementName) from" + - " NodeType(${nodeTemplate.type})" - ) - // Validate Requirement Assignment - validateRequirementAssignment(nodeTemplateName, requirementName, requirementDefinition, requirementAssignment) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateRequirementAssignment( - nodeTemplateName: String, - requirementAssignmentName: String, - requirementDefinition: RequirementDefinition, - requirementAssignment: RequirementAssignment - ) { - log.debug( - "Validating NodeTemplate({}) requirement assignment ({}) ", nodeTemplateName, - requirementAssignmentName - ) - val requirementNodeTemplateName = requirementAssignment.node!! - val capabilityName = requirementAssignment.capability - val relationship = requirementAssignment.relationship!! - - check(BlueprintTypes.validRelationShipDerivedFroms.contains(relationship)) { - throw BlueprintException("Failed to get relationship type ($relationship) for NodeTemplate($nodeTemplateName)'s requirement($requirementAssignmentName)") - } - - val relationShipNodeTemplate = bluePrintContext.serviceTemplate.topologyTemplate?.nodeTemplates?.get(requirementNodeTemplateName) - ?: throw BlueprintException( - "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " + - "for NodeTemplate($nodeTemplateName) requirement($requirementAssignmentName)" - ) - - relationShipNodeTemplate.capabilities?.get(capabilityName) - ?: throw BlueprintException( - "Failed to get requirement NodeTemplate($requirementNodeTemplateName)'s " + - "capability($capabilityName) for NodeTemplate ($nodeTemplateName)'s requirement($requirementAssignmentName)" - ) - } - - @Throws(BlueprintException::class) - open fun validateInterfaceAssignments(nodeType: NodeType, nodeTemplateName: String, nodeTemplate: NodeTemplate) { - - val interfaces = nodeTemplate.interfaces - paths.add("interfaces") - interfaces?.forEach { interfaceAssignmentName, interfaceAssignment -> - paths.add(interfaceAssignmentName) - val interfaceDefinition = nodeType.interfaces?.get(interfaceAssignmentName) - ?: throw BlueprintException( - "Failed to get NodeTemplate($nodeTemplateName) interface definition ($interfaceAssignmentName) from" + - " NodeType(${nodeTemplate.type})" - ) - - validateInterfaceAssignment( - nodeTemplateName, interfaceAssignmentName, interfaceDefinition, - interfaceAssignment - ) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - @Throws(BlueprintException::class) - open fun validateInterfaceAssignment( - nodeTemplateName: String, - interfaceAssignmentName: String, - interfaceDefinition: InterfaceDefinition, - interfaceAssignment: InterfaceAssignment - ) { - - val operations = interfaceAssignment.operations - operations?.let { - validateInterfaceOperationsAssignment( - nodeTemplateName, interfaceAssignmentName, interfaceDefinition, - interfaceAssignment - ) - } - } - - @Throws(BlueprintException::class) - open fun validateInterfaceOperationsAssignment( - nodeTemplateName: String, - interfaceAssignmentName: String, - interfaceDefinition: InterfaceDefinition, - interfaceAssignment: InterfaceAssignment - ) { - - val operations = interfaceAssignment.operations - operations?.let { - it.forEach { operationAssignmentName, operationAssignments -> - - val operationDefinition = interfaceDefinition.operations?.get(operationAssignmentName) - ?: throw BlueprintException("Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName)") - - log.debug( - "Validation NodeTemplate($nodeTemplateName) Interface($interfaceAssignmentName) Operation " + - "($operationAssignmentName)" - ) - - val inputs = operationAssignments.inputs - val outputs = operationAssignments.outputs - - inputs?.forEach { propertyName, propertyAssignment -> - val propertyDefinition = operationDefinition.inputs?.get(propertyName) - ?: throw BlueprintException( - "Failed to get NodeTemplate($nodeTemplateName) operation " + - "definition ($operationAssignmentName) property definition($propertyName)" - ) - // Check the property values with property definition - propertyAssignmentValidationUtils - .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) - } - - outputs?.forEach { propertyName, propertyAssignment -> - val propertyDefinition = operationDefinition.outputs?.get(propertyName) - ?: throw BlueprintException( - "Failed to get NodeTemplate($nodeTemplateName) operation definition ($operationAssignmentName) " + - "output property definition($propertyName)" - ) - // Check the property values with property definition - propertyAssignmentValidationUtils - .validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) - } - } - } - } - - private fun validateExtension(referencePrefix: String, name: String, nodeTemplate: NodeTemplate) { - val customValidator = bluePrintTypeValidatorService - .bluePrintValidator(referencePrefix, BlueprintNodeTemplateValidator::class.java) - - customValidator?.let { - it.validate(bluePrintRuntimeService, name, nodeTemplate) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTypeValidatorImpl.kt deleted file mode 100644 index b7ec2d150..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintNodeTypeValidatorImpl.kt +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.RequirementDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-node-type-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTypeValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : BlueprintNodeTypeValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - var paths: MutableList = arrayListOf() - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, nodeTypeName: String, nodeType: NodeType) { - log.trace("Validating NodeType($nodeTypeName)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - paths.add(nodeTypeName) - - val derivedFrom: String = nodeType.derivedFrom - // Check Derived From - checkValidNodeTypesDerivedFrom(nodeTypeName, derivedFrom) - - if (!BlueprintTypes.rootNodeTypes().contains(derivedFrom)) { - bluePrintContext.serviceTemplate.nodeTypes?.get(derivedFrom) - ?: throw BlueprintException("Failed to get derivedFrom NodeType($derivedFrom)'s for NodeType($nodeTypeName)") - } - - nodeType.attributes?.let { - bluePrintTypeValidatorService.validateAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) - } - - nodeType.properties?.let { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) - } - - nodeType.capabilities?.let { validateCapabilityDefinitions(nodeTypeName, nodeType) } - nodeType.requirements?.let { validateRequirementDefinitions(nodeTypeName, nodeType) } - nodeType.interfaces?.let { validateInterfaceDefinitions(nodeType.interfaces!!) } - - paths.removeAt(paths.lastIndex) - } - - fun checkValidNodeTypesDerivedFrom(nodeTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validNodeTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException("Failed to get node type ($nodeTypeName)'s derivedFrom($derivedFrom) definition ") - } - } - - open fun validateCapabilityDefinitions(nodeTypeName: String, nodeType: NodeType) { - val capabilities = nodeType.capabilities - paths.add("capabilities") - capabilities?.forEach { capabilityName, capabilityDefinition -> - paths.add(capabilityName) - - validateCapabilityDefinition(nodeTypeName, nodeType, capabilityName, capabilityDefinition) - - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - open fun validateCapabilityDefinition( - nodeTypeName: String, - nodeType: NodeType, - capabilityName: String, - capabilityDefinition: CapabilityDefinition - ) { - val capabilityType = capabilityDefinition.type - check(BlueprintTypes.validCapabilityTypes.contains(capabilityType)) { - throw BlueprintException("failed to get CapabilityType($capabilityType) for NodeType($nodeTypeName)") - } - } - - open fun validateRequirementDefinitions(nodeName: String, nodeType: NodeType) { - paths.add("requirements") - val requirements = nodeType.requirements - - requirements?.forEach { requirementDefinitionName, requirementDefinition -> - paths.add(requirementDefinitionName) - validateRequirementDefinition(nodeName, nodeType, requirementDefinitionName, requirementDefinition) - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - open fun validateRequirementDefinition( - nodeTypeName: String, - nodeType: NodeType, - requirementDefinitionName: String, - requirementDefinition: RequirementDefinition - ) { - - log.info("validating NodeType({}) RequirementDefinition ({}) ", nodeTypeName, requirementDefinitionName) - val requirementNodeTypeName = requirementDefinition.node!! - val capabilityName = requirementDefinition.capability - val relationship = requirementDefinition.relationship!! - - check(BlueprintTypes.validRelationShipDerivedFroms.contains(relationship)) { - throw BlueprintException("failed to get relationship($relationship) for NodeType($nodeTypeName)'s requirement($requirementDefinitionName)") - } - - val relationShipNodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(requirementNodeTypeName) - ?: throw BlueprintException("failed to get requirement NodeType($requirementNodeTypeName)'s for requirement($requirementDefinitionName) ") - - relationShipNodeType.capabilities?.get(capabilityName) - ?: throw BlueprintException( - "failed to get requirement NodeType($requirementNodeTypeName)'s " + - "capability($nodeTypeName) for NodeType ($capabilityName)'s requirement($requirementDefinitionName) " - ) - } - - open fun validateInterfaceDefinitions(interfaces: MutableMap) { - paths.add("interfaces") - interfaces.forEach { interfaceName, interfaceDefinition -> - paths.add(interfaceName) - interfaceDefinition.operations?.let { validateOperationDefinitions(interfaceDefinition.operations!!) } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - open fun validateOperationDefinitions(operations: MutableMap) { - paths.add("operations") - operations.forEach { opertaionName, operationDefinition -> - paths.add(opertaionName) - operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) } - - operationDefinition.inputs?.let { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.inputs!!) - } - - operationDefinition.outputs?.let { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.outputs!!) - } - paths.removeAt(paths.lastIndex) - } - paths.removeAt(paths.lastIndex) - } - - open fun validateImplementation(implementation: Implementation) { - checkNotEmpty(implementation.primary) { "couldn't get implementation" } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintPropertyDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintPropertyDefinitionValidatorImpl.kt deleted file mode 100644 index 4d69d3acd..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintPropertyDefinitionValidatorImpl.kt +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.format -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-property-definition-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintPropertyDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintPropertyDefinitionValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { - this.bluePrintRuntimeService = bluePrintRuntimeService - - log.trace("Validating PropertyDefinition($name)") - - val dataType: String = propertyDefinition.type - - when { - BlueprintTypes.validPrimitiveTypes().contains(dataType) -> { - // Do Nothing - } - BlueprintTypes.validComplexTypes().contains(dataType) -> { - // Do Nothing - } - BlueprintTypes.validCollectionTypes().contains(dataType) -> { - val entrySchemaType: String = propertyDefinition.entrySchema?.type - ?: throw BlueprintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, name)) - checkPrimitiveOrComplex(entrySchemaType, name) - } - else -> checkPropertyDataType(dataType, name) - } - } - - private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean { - if (BlueprintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) { - return true - } else { - throw BlueprintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName)) - } - } - - private fun checkPropertyDataType(dataTypeName: String, propertyName: String) { - - val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName) - ?: throw BlueprintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName)) - - checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) - } - - private fun checkDataType(key: String): Boolean { - return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false - } - - open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom)) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintServiceTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintServiceTemplateValidatorImpl.kt deleted file mode 100644 index 137e6e6b9..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintServiceTemplateValidatorImpl.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import com.google.common.base.Preconditions -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-service-template-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintServiceTemplateValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintServiceTemplateValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var error: BlueprintError - - var paths: MutableList = arrayListOf() - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) { - log.trace("Validating Service Template..") - try { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.error = bluePrintRuntimeService.getBlueprintError() - - serviceTemplate.metadata?.let { validateMetadata(serviceTemplate.metadata!!) } - serviceTemplate.dataTypes?.let { validateDataTypes(serviceTemplate.dataTypes!!) } - serviceTemplate.artifactTypes?.let { validateArtifactTypes(serviceTemplate.artifactTypes!!) } - serviceTemplate.nodeTypes?.let { validateNodeTypes(serviceTemplate.nodeTypes!!) } - serviceTemplate.topologyTemplate?.let { validateTopologyTemplate(serviceTemplate.topologyTemplate!!) } - } catch (e: Exception) { - log.error("failed in blueprint service template validation", e) - error.addError(BlueprintConstants.PATH_SERVICE_TEMPLATE, paths.joinToString(BlueprintConstants.PATH_DIVIDER), e.message!!, "BlueprintServiceTemplateValidator") - } - } - - fun validateMetadata(metaDataMap: MutableMap) { - - paths.add(BlueprintConstants.PATH_METADATA) - - val templateName = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_NAME] - val templateVersion = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_VERSION] - val templateTags = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_TAGS] - val templateAuthor = metaDataMap[BlueprintConstants.METADATA_TEMPLATE_AUTHOR] - - Preconditions.checkArgument(StringUtils.isNotBlank(templateName), "failed to get template name metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateVersion), "failed to get template version metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateTags), "failed to get template tags metadata") - Preconditions.checkArgument(StringUtils.isNotBlank(templateAuthor), "failed to get template author metadata") - - paths.removeAt(paths.lastIndex) - } - - fun validateDataTypes(dataTypes: MutableMap) { - - paths.add(BlueprintConstants.PATH_DATA_TYPES) - dataTypes.forEach { dataTypeName, dataType -> - // Validate Single Data Type - bluePrintTypeValidatorService.validateDataType(bluePrintRuntimeService, dataTypeName, dataType) - } - paths.removeAt(paths.lastIndex) - } - - fun validateArtifactTypes(artifactTypes: MutableMap) { - paths.add(BlueprintConstants.PATH_ARTIFACT_TYPES) - artifactTypes.forEach { artifactName, artifactType -> - // Validate Single Artifact Type - bluePrintTypeValidatorService.validateArtifactType(bluePrintRuntimeService, artifactName, artifactType) - } - paths.removeAt(paths.lastIndex) - } - - fun validateNodeTypes(nodeTypes: MutableMap) { - paths.add(BlueprintConstants.PATH_NODE_TYPES) - nodeTypes.forEach { nodeTypeName, nodeType -> - // Validate Single Node Type - bluePrintTypeValidatorService.validateNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) - } - paths.removeAt(paths.lastIndex) - } - - fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) { - paths.add(BlueprintConstants.PATH_TOPOLOGY_TEMPLATE) - bluePrintTypeValidatorService.validateTopologyTemplate(bluePrintRuntimeService, "topologyTemplate", topologyTemplate) - paths.removeAt(paths.lastIndex) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTopologyTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTopologyTemplateValidatorImpl.kt deleted file mode 100644 index d9bd51619..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTopologyTemplateValidatorImpl.kt +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-topology-template-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintTopologyTemplateValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintTopologyTemplateValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) { - log.trace("Validating Topology Template..") - this.bluePrintRuntimeService = bluePrintRuntimeService - - // Validate Inputs - topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) } - // Validate Node Templates - topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) } - // Validate Workflow - topologyTemplate.workflows?.let { validateWorkflows(topologyTemplate.workflows!!) } - } - - @Throws(BlueprintException::class) - fun validateInputs(inputs: MutableMap) { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, inputs) - } - - @Throws(BlueprintException::class) - fun validateNodeTemplates(nodeTemplates: MutableMap) { - - nodeTemplates.forEach { nodeTemplateName, nodeTemplate -> - // Validate Single Node Template - bluePrintTypeValidatorService.validateNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) - } - } - - @Throws(BlueprintException::class) - open fun validateWorkflows(workflows: MutableMap) { - - workflows.forEach { workflowName, workflow -> - // Validate Single workflow - bluePrintTypeValidatorService.validateWorkflow(bluePrintRuntimeService, workflowName, workflow) - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTypeValidatorServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTypeValidatorServiceImpl.kt deleted file mode 100644 index 4e5f0da16..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintTypeValidatorServiceImpl.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintDataTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowValidator -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service - -@Service -class BlueprintTypeValidatorServiceImpl : BlueprintTypeValidatorService { - - companion object { - - const val PREFIX_DEFAULT = "default" - } - - @Autowired - private lateinit var context: ApplicationContext - - override fun > bluePrintValidator(referenceName: String, classType: Class): T? { - return if (context.containsBean(referenceName)) { - context.getBean(referenceName, classType) - } else { - null - } - } - - override fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? { - return context.getBeansOfType(classType) - .filter { it.key.startsWith(referenceNamePrefix) } - .mapNotNull { it.value } - } - - override fun > bluePrintValidators(classType: Class): List? { - return context.getBeansOfType(classType).mapNotNull { it.value } - } - - override fun getServiceTemplateValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintServiceTemplateValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default ServiceTemplate validators") - } - - override fun getDataTypeValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintDataTypeValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default DataType validators") - } - - override fun getArtifactTypeValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintArtifactTypeValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default ArtifactType validators") - } - - override fun getArtifactDefinitionsValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintArtifactDefinitionValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default ArtifactDefinition validators") - } - - override fun getNodeTypeValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintNodeTypeValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default NodeType validators") - } - - override fun getTopologyTemplateValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintTopologyTemplateValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default TopologyTemplate validators") - } - - override fun getNodeTemplateValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintNodeTemplateValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default NodeTemplate validators") - } - - override fun getWorkflowValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintWorkflowValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default Workflow validators") - } - - override fun getPropertyDefinitionValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintPropertyDefinitionValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default PropertyDefinition validators") - } - - override fun getAttributeDefinitionValidators(): List { - return bluePrintValidators(PREFIX_DEFAULT, BlueprintAttributeDefinitionValidator::class.java) - ?: throw BlueprintProcessorException("failed to get default AttributeDefinition validators") - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintValidationConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintValidationConfiguration.kt deleted file mode 100644 index b4d2372d0..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintValidationConfiguration.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -open class BlueprintValidationConfiguration diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintWorkflowValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintWorkflowValidatorImpl.kt deleted file mode 100644 index bff09fc83..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintWorkflowValidatorImpl.kt +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowValidator -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.validation.utils.PropertyAssignmentValidationUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("default-workflow-validator") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintWorkflowValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : BlueprintWorkflowValidator { - - private val log = LoggerFactory.getLogger(BlueprintServiceTemplateValidatorImpl::class.toString()) - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - var paths: MutableList = arrayListOf() - - override fun validate(bluePrintRuntimeService: BlueprintRuntimeService<*>, workflowName: String, workflow: Workflow) { - log.info("Validating Workflow($workflowName)") - - this.bluePrintRuntimeService = bluePrintRuntimeService - - paths.add(workflowName) - paths.joinToString(BlueprintConstants.PATH_DIVIDER) - - // Validate Workflow Inputs - validateInputs(workflow) - - // Validate Workflow outputs - validateOutputs(workflow) - - // Step Validation Start - paths.add("steps") - workflow.steps?.forEach { stepName, step -> - paths.add(stepName) - paths.joinToString(BlueprintConstants.PATH_DIVIDER) - - // Validate target - step.target?.let { - try { - val nodeTemplate = bluePrintRuntimeService.bluePrintContext().nodeTemplateByName(it) - - val nodeTypeDerivedFrom = bluePrintRuntimeService.bluePrintContext().nodeTemplateNodeType(it).derivedFrom - - check( - nodeTypeDerivedFrom == BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW || - nodeTypeDerivedFrom == BlueprintConstants.MODEL_TYPE_NODE_COMPONENT - ) { - "NodeType(${nodeTemplate.type}) derived from is '$nodeTypeDerivedFrom', Expected " + - "'${BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW}' or '${BlueprintConstants.MODEL_TYPE_NODE_COMPONENT}'" - } - } catch (e: Exception) { - bluePrintRuntimeService.getBlueprintError() - .addError( - "Failed to validate Workflow($workflowName)'s step($stepName)'s " + - "definition", - paths.joinToString(BlueprintConstants.PATH_DIVIDER), e.message!!, - "BlueprintWorkflowValidatorImpl" - ) - } - } - } - paths.removeAt(paths.lastIndex) - // Step Validation Ends - paths.removeAt(paths.lastIndex) - - paths.removeAt(paths.lastIndex) - } - - private fun validateInputs(workflow: Workflow) { - workflow.inputs?.let { - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, workflow.inputs!!) - } - } - - private fun validateOutputs(workflow: Workflow) { - workflow.outputs?.let { - - bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, workflow.outputs!!) - - PropertyAssignmentValidationUtils(bluePrintRuntimeService.bluePrintContext()) - .validatePropertyDefinitionNAssignments(workflow.outputs!!) - } - // Validate Value or Expression - workflow.outputs?.forEach { propertyName, propertyDefinition -> - } - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt index d7dcd9713..78a5d379e 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt @@ -17,9 +17,9 @@ package org.onap.ccsdk.cds.controllerblueprints.validation.extension import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.service.ResourceAssignmentValidationServiceImpl @@ -28,13 +28,13 @@ import org.springframework.stereotype.Service import java.io.File @Service("artifact-mapping-resource-artifact-definition-validator") -open class ArtifactMappingResourceValidator(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : - BlueprintArtifactDefinitionValidator { +open class ArtifactMappingResourceValidator(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : + BluePrintArtifactDefinitionValidator { private val log = LoggerFactory.getLogger(ArtifactMappingResourceValidator::class.toString()) override fun validate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition ) { diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt index 044c5296b..dc5da2669 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt @@ -16,25 +16,25 @@ package org.onap.ccsdk.cds.controllerblueprints.validation.extension -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidator -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.slf4j.LoggerFactory import org.springframework.beans.factory.config.ConfigurableBeanFactory import org.springframework.context.annotation.Scope import org.springframework.stereotype.Service -interface ResourceDefinitionValidator : BlueprintValidator +interface ResourceDefinitionValidator : BluePrintValidator @Service @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class ResourceDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BlueprintTypeValidatorService) : ResourceDefinitionValidator { +open class ResourceDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : ResourceDefinitionValidator { private val log = LoggerFactory.getLogger(ResourceDefinitionValidatorImpl::class.java) override fun validate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, resourceDefinition: ResourceDefinition ) { diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt index 91d01c6a0..63aa7e537 100644 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt @@ -18,15 +18,15 @@ package org.onap.ccsdk.cds.controllerblueprints.validation.utils import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.format -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintExpressionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintExpressionService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -open class PropertyAssignmentValidationUtils(private val bluePrintContext: BlueprintContext) { +open class PropertyAssignmentValidationUtils(private val bluePrintContext: BluePrintContext) { // Property Definition holds both Definitons and Expression in same construct open fun validatePropertyDefinitionNAssignments(propertyDefinitions: MutableMap) { @@ -39,10 +39,10 @@ open class PropertyAssignmentValidationUtils(private val bluePrintContext: Bluep open fun validatePropertyDefinitionNAssignment(propertyName: String, propertyDefinition: PropertyDefinition) { // Check and Validate if Expression Node checkNotNull(propertyDefinition.value) { - throw BlueprintException("couldn't get 'value' property from PropertyDefinition($propertyName)") + throw BluePrintException("couldn't get 'value' property from PropertyDefinition($propertyName)") } val propertyAssignment = propertyDefinition.value!! - val expressionData = BlueprintExpressionService.getExpressionData(propertyAssignment) + val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment) if (!expressionData.isExpression) { checkPropertyValue(propertyName, propertyDefinition, propertyAssignment) } @@ -54,7 +54,7 @@ open class PropertyAssignmentValidationUtils(private val bluePrintContext: Bluep ) { properties.forEach { propertyName, propertyAssignment -> val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName] - ?: throw BlueprintException("validatePropertyAssignments failed to get definition for the property ($propertyName)") + ?: throw BluePrintException("validatePropertyAssignments failed to get definition for the property ($propertyName)") validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment) } @@ -66,7 +66,7 @@ open class PropertyAssignmentValidationUtils(private val bluePrintContext: Bluep propertyAssignment: JsonNode ) { // Check and Validate if Expression Node - val expressionData = BlueprintExpressionService.getExpressionData(propertyAssignment) + val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment) if (!expressionData.isExpression) { checkPropertyValue(propertyName, propertyDefinition, propertyAssignment) } @@ -76,16 +76,16 @@ open class PropertyAssignmentValidationUtils(private val bluePrintContext: Bluep val propertyType = propertyDefinition.type val isValid: Boolean - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType)) { + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) { isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment) - } else if (BlueprintTypes.validComplexTypes().contains(propertyType)) { + } else if (BluePrintTypes.validComplexTypes().contains(propertyType)) { isValid = true - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { val entrySchemaType = propertyDefinition.entrySchema?.type - ?: throw BlueprintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName)) + ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName)) - if (!BlueprintTypes.validPropertyTypes().contains(entrySchemaType)) { + if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) { checkPropertyDataType(entrySchemaType, propertyName) } isValid = JacksonUtils.checkJsonNodeValueOfCollectionType(propertyType, propertyAssignment) @@ -95,21 +95,21 @@ open class PropertyAssignmentValidationUtils(private val bluePrintContext: Bluep } check(isValid) { - throw BlueprintException("property($propertyName) defined of type($propertyType) is not compatible with the value ($propertyAssignment)") + throw BluePrintException("property($propertyName) defined of type($propertyType) is not compatible with the value ($propertyAssignment)") } } open fun checkPropertyDataType(dataTypeName: String, propertyName: String) { val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) - ?: throw BlueprintException("DataType ($dataTypeName) for the property ($propertyName) not found") + ?: throw BluePrintException("DataType ($dataTypeName) for the property ($propertyName) not found") checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom) } open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) { - check(BlueprintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { - throw BlueprintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ") + check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) { + throw BluePrintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ") } } } diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt new file mode 100644 index 000000000..fd39f8f95 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt @@ -0,0 +1,117 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class BluePrintDesignTimeValidatorServiceTest { + + private val blueprintBasePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + private val bluePrintRuntime = BluePrintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) + private val mockBluePrintTypeValidatorService = MockBluePrintTypeValidatorService() + private val resourceDefinitionValidator = mockk() + private val defaultBluePrintValidatorService = + BluePrintDesignTimeValidatorService(mockBluePrintTypeValidatorService, resourceDefinitionValidator) + private val workflowValidator = BluePrintWorkflowValidatorImpl(mockBluePrintTypeValidatorService) + + @Test + fun testValidateOfType() { + runBlocking { + every { resourceDefinitionValidator.validate(bluePrintRuntime, any(), any()) } returns Unit + + val valid = defaultBluePrintValidatorService.validateBluePrints(bluePrintRuntime) + assertTrue(valid, "failed in blueprint Validation") + } + } + + @Test + fun testValidateWorkflowFailToFoundNodeTemplate() { + val workflowName = "resource-assignment" + + val step = Step() + step.target = "TestCaseFailNoNodeTemplate" + val workflow = Workflow() + workflow.steps = mutableMapOf("test" to step) + workflowValidator.validate(bluePrintRuntime, workflowName, workflow) + + assertEquals(1, bluePrintRuntime.getBluePrintError().allErrors().size) + assertEquals( + "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : resource-assignment/steps/test : could't get node template for the name(TestCaseFailNoNodeTemplate)", + bluePrintRuntime.getBluePrintError().allErrors()[0] + ) + } + + @Test + fun testValidateWorkflowFailNodeTemplateNotDgGeneric() { + val workflowName = "resource-assignment" + val nodeTemplateName = "resource-assignment-process" + + val nodeTemplate = mockk() + every { nodeTemplate.type } returns "TestNodeType" + + val nodeType = mockk() + every { nodeType.derivedFrom } returns "tosca.nodes.TEST" + + val blueprintContext = mockk() + every { blueprintContext.nodeTemplateByName(nodeTemplateName) } returns nodeTemplate + every { blueprintContext.nodeTemplateNodeType(nodeTemplateName) } returns nodeType + + val bluePrintRuntime = mockk("1234") + + every { bluePrintRuntime.getBluePrintError() } returns BluePrintError() + every { bluePrintRuntime.bluePrintContext() } returns blueprintContext + + val step = Step() + step.target = nodeTemplateName + val workflow = Workflow() + workflow.steps = mutableMapOf("test" to step) + workflowValidator.validate(bluePrintRuntime, workflowName, workflow) + + assertEquals(1, bluePrintRuntime.getBluePrintError().allErrors().size) + assertEquals( + "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : " + + "resource-assignment/steps/test : NodeType(TestNodeType) derived from is 'tosca.nodes.TEST', " + + "Expected 'tosca.nodes.Workflow' or 'tosca.nodes.Component'", + bluePrintRuntime.getBluePrintError().allErrors()[0] + ) + } + + @Test + fun testValidateWorkflowSuccess() { + val workflowName = "resource-assignment" + workflowValidator.validate( + bluePrintRuntime, + workflowName, + bluePrintRuntime.bluePrintContext().workflowByName(workflowName) + ) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorServiceTest.kt deleted file mode 100644 index dd82ec5da..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorServiceTest.kt +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import io.mockk.every -import io.mockk.mockk -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class BlueprintDesignTimeValidatorServiceTest { - - private val blueprintBasePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - private val bluePrintRuntime = BlueprintMetadataUtils.bluePrintRuntime("1234", blueprintBasePath) - private val mockBlueprintTypeValidatorService = MockBlueprintTypeValidatorService() - private val resourceDefinitionValidator = mockk() - private val defaultBlueprintValidatorService = - BlueprintDesignTimeValidatorService(mockBlueprintTypeValidatorService, resourceDefinitionValidator) - private val workflowValidator = BlueprintWorkflowValidatorImpl(mockBlueprintTypeValidatorService) - - @Test - fun testValidateOfType() { - runBlocking { - every { resourceDefinitionValidator.validate(bluePrintRuntime, any(), any()) } returns Unit - - val valid = defaultBlueprintValidatorService.validateBlueprints(bluePrintRuntime) - assertTrue(valid, "failed in blueprint Validation") - } - } - - @Test - fun testValidateWorkflowFailToFoundNodeTemplate() { - val workflowName = "resource-assignment" - - val step = Step() - step.target = "TestCaseFailNoNodeTemplate" - val workflow = Workflow() - workflow.steps = mutableMapOf("test" to step) - workflowValidator.validate(bluePrintRuntime, workflowName, workflow) - - assertEquals(1, bluePrintRuntime.getBlueprintError().allErrors().size) - assertEquals( - "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : resource-assignment/steps/test : could't get node template for the name(TestCaseFailNoNodeTemplate)", - bluePrintRuntime.getBlueprintError().allErrors()[0] - ) - } - - @Test - fun testValidateWorkflowFailNodeTemplateNotDgGeneric() { - val workflowName = "resource-assignment" - val nodeTemplateName = "resource-assignment-process" - - val nodeTemplate = mockk() - every { nodeTemplate.type } returns "TestNodeType" - - val nodeType = mockk() - every { nodeType.derivedFrom } returns "tosca.nodes.TEST" - - val blueprintContext = mockk() - every { blueprintContext.nodeTemplateByName(nodeTemplateName) } returns nodeTemplate - every { blueprintContext.nodeTemplateNodeType(nodeTemplateName) } returns nodeType - - val bluePrintRuntime = mockk("1234") - - every { bluePrintRuntime.getBlueprintError() } returns BlueprintError() - every { bluePrintRuntime.bluePrintContext() } returns blueprintContext - - val step = Step() - step.target = nodeTemplateName - val workflow = Workflow() - workflow.steps = mutableMapOf("test" to step) - workflowValidator.validate(bluePrintRuntime, workflowName, workflow) - - assertEquals(1, bluePrintRuntime.getBlueprintError().allErrors().size) - assertEquals( - "Failed to validate Workflow(resource-assignment)'s step(test)'s definition : " + - "resource-assignment/steps/test : NodeType(TestNodeType) derived from is 'tosca.nodes.TEST', " + - "Expected 'tosca.nodes.Workflow' or 'tosca.nodes.Component'", - bluePrintRuntime.getBlueprintError().allErrors()[0] - ) - } - - @Test - fun testValidateWorkflowSuccess() { - val workflowName = "resource-assignment" - workflowValidator.validate( - bluePrintRuntime, - workflowName, - bluePrintRuntime.bluePrintContext().workflowByName(workflowName) - ) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt new file mode 100644 index 000000000..11c6c037c --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt @@ -0,0 +1,86 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.controllerblueprints.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator + +class MockBluePrintTypeValidatorService : BluePrintTypeValidatorService { + + override fun > bluePrintValidator(referenceName: String, classType: Class): T? { + return null + } + + override fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? { + return null + } + + override fun > bluePrintValidators(classType: Class): List? { + return null + } + + override fun getServiceTemplateValidators(): List { + return listOf(BluePrintServiceTemplateValidatorImpl(this)) + } + + override fun getDataTypeValidators(): List { + return listOf(BluePrintDataTypeValidatorImpl(this)) + } + + override fun getArtifactTypeValidators(): List { + return listOf(BluePrintArtifactTypeValidatorImpl(this)) + } + + override fun getArtifactDefinitionsValidators(): List { + return listOf(BluePrintArtifactDefinitionValidatorImpl(this)) + } + + override fun getNodeTypeValidators(): List { + return listOf(BluePrintNodeTypeValidatorImpl(this)) + } + + override fun getTopologyTemplateValidators(): List { + return listOf(BluePrintTopologyTemplateValidatorImpl(this)) + } + + override fun getNodeTemplateValidators(): List { + return listOf(BluePrintNodeTemplateValidatorImpl(this)) + } + + override fun getWorkflowValidators(): List { + return listOf(BluePrintWorkflowValidatorImpl(this)) + } + + override fun getPropertyDefinitionValidators(): List { + return listOf(BluePrintPropertyDefinitionValidatorImpl(this)) + } + + override fun getAttributeDefinitionValidators(): List { + return listOf(BluePrintAttributeDefinitionValidatorImpl(this)) + } +} diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBlueprintTypeValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBlueprintTypeValidatorService.kt deleted file mode 100644 index 69f57a0b9..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBlueprintTypeValidatorService.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.controllerblueprints.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintDataTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidator -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowValidator - -class MockBlueprintTypeValidatorService : BlueprintTypeValidatorService { - - override fun > bluePrintValidator(referenceName: String, classType: Class): T? { - return null - } - - override fun > bluePrintValidators(referenceNamePrefix: String, classType: Class): List? { - return null - } - - override fun > bluePrintValidators(classType: Class): List? { - return null - } - - override fun getServiceTemplateValidators(): List { - return listOf(BlueprintServiceTemplateValidatorImpl(this)) - } - - override fun getDataTypeValidators(): List { - return listOf(BlueprintDataTypeValidatorImpl(this)) - } - - override fun getArtifactTypeValidators(): List { - return listOf(BlueprintArtifactTypeValidatorImpl(this)) - } - - override fun getArtifactDefinitionsValidators(): List { - return listOf(BlueprintArtifactDefinitionValidatorImpl(this)) - } - - override fun getNodeTypeValidators(): List { - return listOf(BlueprintNodeTypeValidatorImpl(this)) - } - - override fun getTopologyTemplateValidators(): List { - return listOf(BlueprintTopologyTemplateValidatorImpl(this)) - } - - override fun getNodeTemplateValidators(): List { - return listOf(BlueprintNodeTemplateValidatorImpl(this)) - } - - override fun getWorkflowValidators(): List { - return listOf(BlueprintWorkflowValidatorImpl(this)) - } - - override fun getPropertyDefinitionValidators(): List { - return listOf(BlueprintPropertyDefinitionValidatorImpl(this)) - } - - override fun getAttributeDefinitionValidators(): List { - return listOf(BlueprintAttributeDefinitionValidatorImpl(this)) - } -} diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt index e6a0ab6e4..f8dea9871 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.controllerblueprints.resource.dict.factory -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.format import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping @@ -35,7 +35,7 @@ object ResourceSourceMappingFactory { fun getRegisterSourceMapping(sourceInstance: String): String { return resourceSourceMappings[sourceInstance] - ?: throw BlueprintException(format("failed to get source({}) mapping", sourceInstance)) + ?: throw BluePrintException(format("failed to get source({}) mapping", sourceInstance)) } fun getRegisterSourceMapping(): ResourceSourceMapping { diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt index e5d9f5f8b..b97492dc8 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt @@ -20,7 +20,7 @@ package org.onap.ccsdk.cds.controllerblueprints.resource.dict.service import org.apache.commons.collections.CollectionUtils import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.text.StrBuilder -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.utils.TopologicalSortingUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.slf4j.LoggerFactory @@ -33,7 +33,7 @@ import java.io.Serializable */ interface ResourceAssignmentValidationService : Serializable { - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) fun validate(resourceAssignments: List): Boolean } @@ -54,10 +54,10 @@ open class ResourceAssignmentValidationServiceImpl : ResourceAssignmentValidatio validateTemplateNDictionaryKeys(resourceAssignments) validateCyclicDependency(resourceAssignments) if (StringUtils.isNotBlank(validationMessage)) { - throw BlueprintException("Resource Assignment Validation Failure") + throw BluePrintException("Resource Assignment Validation Failure") } } catch (e: Exception) { - throw BlueprintException("Resource Assignment Validation :" + validationMessage.toString(), e) + throw BluePrintException("Resource Assignment Validation :" + validationMessage.toString(), e) } return true } @@ -85,7 +85,7 @@ open class ResourceAssignmentValidationServiceImpl : ResourceAssignmentValidatio } if (StringUtils.isNotBlank(validationMessage)) { - throw BlueprintException("Resource Assignment Validation Failure") + throw BluePrintException("Resource Assignment Validation Failure") } } diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt index 7da46f582..5117c4388 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils import org.apache.commons.collections.CollectionUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asListOfString import org.onap.ccsdk.cds.controllerblueprints.core.utils.TopologicalSortingUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -60,7 +60,7 @@ object BulkResourceSequencingUtils { } else if (CollectionUtils.isNotEmpty(resourceAssignment.dependencies)) { for (dependency in resourceAssignment.dependencies!!) { val ra = resourceAssignmentMap[dependency] - ?: throw BlueprintProcessorException( + ?: throw BluePrintProcessorException( "Couldn't get Resource Assignment dependency " + "Key($dependency)" ) diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.kt index 3833cbe93..c09474a2b 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.kt +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.kt @@ -20,10 +20,10 @@ import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.NullNode import org.apache.commons.collections.MapUtils import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition @@ -75,7 +75,7 @@ object ResourceDictionaryUtils { data.fields().forEach { field -> val valueNode: JsonNode = data.at("/".plus(field.key)) ?: NullNode.getInstance() - val path = BlueprintConstants.PATH_INPUTS.plus(BlueprintConstants.PATH_DIVIDER).plus(field.key) + val path = BluePrintConstants.PATH_INPUTS.plus(BluePrintConstants.PATH_DIVIDER).plus(field.key) log.trace("setting path ({}), values ({})", path, valueNode) context[path] = valueNode } @@ -83,7 +83,7 @@ object ResourceDictionaryUtils { fun getResourceAssignmentFromFile(filePath: String): List { return JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java) - ?: throw BlueprintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") + ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") } fun writeResourceDefinitionTypes(basePath: String, resourceDefinitions: List) { @@ -92,9 +92,9 @@ object ResourceDictionaryUtils { } fun writeResourceDefinitionTypes(basePath: String, resourceDefinitionMap: Map) { - val typePath = basePath.plus(File.separator).plus(BlueprintConstants.TOSCA_DEFINITIONS_DIR) + val typePath = basePath.plus(File.separator).plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR) .plus(File.separator).plus("${ResourceDictionaryConstants.PATH_RESOURCE_DEFINITION_TYPE}.json") val resourceDefinitionContent = JacksonUtils.getJson(resourceDefinitionMap.toSortedMap(), true) - BlueprintFileUtils.writeDefinitionFile(typePath, resourceDefinitionContent) + BluePrintFileUtils.writeDefinitionFile(typePath, resourceDefinitionContent) } } diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt index af0607763..66df5078c 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt @@ -19,7 +19,7 @@ package org.onap.ccsdk.cds.controllerblueprints.resource.dict.service import org.junit.Assert import org.junit.Before import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryTestUtils @@ -49,7 +49,7 @@ class ResourceAssignmentValidationServiceTest { Assert.assertTrue("Failed to Validate", result) } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testValidateDuplicate() { log.info(" **************** testValidateDuplicate *****************") val assignments = JacksonUtils.getListFromClassPathFile("validation/duplicate.json", ResourceAssignment::class.java) @@ -57,7 +57,7 @@ class ResourceAssignmentValidationServiceTest { resourceAssignmentValidator.validate(assignments!!) } - @Test(expected = BlueprintException::class) + @Test(expected = BluePrintException::class) fun testValidateCyclic() { log.info(" **************** testValidateCyclic *****************") val assignments = JacksonUtils.getListFromClassPathFile("validation/cyclic.json", ResourceAssignment::class.java) diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java index 79f21cfdf..862f1892d 100644 --- a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java +++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java @@ -20,7 +20,7 @@ package org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils; import com.fasterxml.jackson.databind.JsonNode; import org.junit.Assert; import org.junit.Test; -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants; +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants; import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate; import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils; import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment; @@ -93,7 +93,7 @@ public class ResourceDictionaryUtilsTest { JsonNode data = JacksonUtils.Companion.jsonNodeFromClassPathFile("data/resource-assignment-input.json"); Map context = new HashMap<>(); ResourceDictionaryUtils.assignInputs(data, context); - String path = BlueprintConstants.PATH_INPUTS.concat(BlueprintConstants.PATH_DIVIDER).concat("mapValue"); + String path = BluePrintConstants.PATH_INPUTS.concat(BluePrintConstants.PATH_DIVIDER).concat("mapValue"); log.info("populated context {}", context); Assert.assertTrue(String.format("failed to get variable : %s", path), context.containsKey(path)); diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt new file mode 100644 index 000000000..d4b3f807b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt @@ -0,0 +1,81 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Import +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate +import javax.sql.DataSource + +@Configuration +@Import( + BluePrintPropertyConfiguration::class, + BluePrintPropertiesService::class, + BluePrintCoreConfiguration::class +) +@EnableConfigurationProperties +open class BluePrintDBLibConfiguration(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + @Bean("primary-database-properties") + open fun getPrimaryProperties(): PrimaryDataSourceProperties { + return bluePrintPropertiesService.propertyBeanType( + DBLibConstants.PREFIX_DB, + PrimaryDataSourceProperties::class.java + ) + } + + @Bean("primaryNamedParameterJdbcTemplate") + open fun primaryNamedParameterJdbcTemplate(primaryDataSource: DataSource): NamedParameterJdbcTemplate { + return NamedParameterJdbcTemplate(primaryDataSource) + } +} + +/** + * Exposed Dependency Service by this SSH Lib Module + */ +fun BluePrintDependencyService.dbLibPropertyService(): BluePrintDBLibPropertyService = + instance(BluePrintDBLibPropertyService::class) + +fun BluePrintDependencyService.primaryDBLibGenericService(): BluePrintDBLibGenericService = + instance(PrimaryDBLibGenericService::class) + +class DBLibConstants { + companion object { + + const val PREFIX_DB: String = "blueprintsprocessor.db" + + // list of database + const val MARIA_DB: String = "maria-db" + const val PROCESSOR_DB: String = "processor-db" + const val MYSQL_DB: String = "mysql-db" + const val ORACLE_DB: String = "oracle-db" + const val POSTGRES_DB: String = "postgres-db" + + // List of database drivers + const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver" + const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver" + const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver" + const val DRIVER_POSTGRES_DB = "org.postgresql.Driver" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt new file mode 100644 index 000000000..7023106eb --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt @@ -0,0 +1,52 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +open class DBDataSourceProperties { + + var type: String = DBLibConstants.MARIA_DB + lateinit var url: String + lateinit var username: String + lateinit var password: String + open lateinit var driverClassName: String +} + +open class PrimaryDataSourceProperties : DBDataSourceProperties() { + + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var hibernateDialect: String +} + +open class MariaDataSourceProperties : DBDataSourceProperties() { + + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var hibernateDialect: String + override var driverClassName = DBLibConstants.DRIVER_MARIA_DB +} + +open class MySqlDataSourceProperties : DBDataSourceProperties() { + + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var hibernateDialect: String + override var driverClassName = DBLibConstants.DRIVER_MYSQL_DB +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt new file mode 100644 index 000000000..aeb87fd66 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate + +interface BluePrintDBLibGenericService { + + fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate + + fun query(sql: String, params: Map): List> + + fun update(sql: String, params: Map): Int +} + +abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) : + BluePrintDBLibGenericService { + + override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { + return namedParameterJdbcTemplate + } + + override fun query(sql: String, params: Map): List> { + return namedParameterJdbcTemplate.queryForList(sql, params) + } + + override fun update(sql: String, params: Map): Int { + return namedParameterJdbcTemplate.update(sql, params) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibConfiguration.kt deleted file mode 100644 index f11832beb..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibConfiguration.kt +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.db - -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BlueprintDBLibPropertyService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.Import -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate -import javax.sql.DataSource - -@Configuration -@Import( - BlueprintPropertyConfiguration::class, - BlueprintPropertiesService::class, - BlueprintCoreConfiguration::class -) -@EnableConfigurationProperties -open class BlueprintDBLibConfiguration(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - @Bean("primary-database-properties") - open fun getPrimaryProperties(): PrimaryDataSourceProperties { - return bluePrintPropertiesService.propertyBeanType( - DBLibConstants.PREFIX_DB, - PrimaryDataSourceProperties::class.java - ) - } - - @Bean("primaryNamedParameterJdbcTemplate") - open fun primaryNamedParameterJdbcTemplate(primaryDataSource: DataSource): NamedParameterJdbcTemplate { - return NamedParameterJdbcTemplate(primaryDataSource) - } -} - -/** - * Exposed Dependency Service by this SSH Lib Module - */ -fun BlueprintDependencyService.dbLibPropertyService(): BlueprintDBLibPropertyService = - instance(BlueprintDBLibPropertyService::class) - -fun BlueprintDependencyService.primaryDBLibGenericService(): BlueprintDBLibGenericService = - instance(PrimaryDBLibGenericService::class) - -class DBLibConstants { - companion object { - - const val PREFIX_DB: String = "blueprintsprocessor.db" - - // list of database - const val MARIA_DB: String = "maria-db" - const val PROCESSOR_DB: String = "processor-db" - const val MYSQL_DB: String = "mysql-db" - const val ORACLE_DB: String = "oracle-db" - const val POSTGRES_DB: String = "postgres-db" - - // List of database drivers - const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver" - const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver" - const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver" - const val DRIVER_POSTGRES_DB = "org.postgresql.Driver" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibData.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibData.kt deleted file mode 100644 index 7023106eb..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibData.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.db - -open class DBDataSourceProperties { - - var type: String = DBLibConstants.MARIA_DB - lateinit var url: String - lateinit var username: String - lateinit var password: String - open lateinit var driverClassName: String -} - -open class PrimaryDataSourceProperties : DBDataSourceProperties() { - - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var hibernateDialect: String -} - -open class MariaDataSourceProperties : DBDataSourceProperties() { - - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var hibernateDialect: String - override var driverClassName = DBLibConstants.DRIVER_MARIA_DB -} - -open class MySqlDataSourceProperties : DBDataSourceProperties() { - - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var hibernateDialect: String - override var driverClassName = DBLibConstants.DRIVER_MYSQL_DB -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibGenericService.kt deleted file mode 100644 index 6c382377d..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintDBLibGenericService.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.db - -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate - -interface BlueprintDBLibGenericService { - - fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate - - fun query(sql: String, params: Map): List> - - fun update(sql: String, params: Map): Int -} - -abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) : - BlueprintDBLibGenericService { - - override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { - return namedParameterJdbcTemplate - } - - override fun query(sql: String, params: Map): List> { - return namedParameterJdbcTemplate.queryForList(sql, params) - } - - override fun update(sql: String, params: Map): Int { - return namedParameterJdbcTemplate.update(sql, params) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSL.kt index fd51da152..34dd0a417 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -30,25 +30,25 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Types DSL for Database Producer */ fun ServiceTemplateBuilder.relationshipTypeConnectsToDb() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToDb() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToDb() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToDb(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToDb(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through Database." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -66,25 +66,25 @@ fun TopologyTemplateBuilder.relationshipTemplateDb( class DbRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB, description ) { fun mariaDb(block: DbMariaDataSourcePropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.mariaDbProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.mariaDbProperties(block)) } fun mySqlDb(block: DbMySqlDataSourcePropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.mySqlDbProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.mySqlDbProperties(block)) } } -fun BlueprintTypes.mariaDbProperties(block: DbMariaDataSourcePropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.mariaDbProperties(block: DbMariaDataSourcePropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = DbMariaDataSourcePropertiesAssignmentBuilder().apply(block).build() assignments[DBDataSourceProperties::type.name] = DBLibConstants.MARIA_DB.asJsonPrimitive() return assignments.asJsonNode() } -fun BlueprintTypes.mySqlDbProperties(block: DbMySqlDataSourcePropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.mySqlDbProperties(block: DbMySqlDataSourcePropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = DbMySqlDataSourcePropertiesAssignmentBuilder().apply(block).build() assignments[DBDataSourceProperties::type.name] = DBLibConstants.MYSQL_DB.asJsonPrimitive() return assignments.asJsonNode() diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt new file mode 100644 index 000000000..79f5c09bc --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt @@ -0,0 +1,79 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.DBDataSourceProperties +import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.MARIA_DB +import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.MYSQL_DB +import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.PROCESSOR_DB +import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties +import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service +class BluePrintDBLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + fun JdbcTemplate(jsonNode: JsonNode): BluePrintDBLibGenericService = + blueprintDBDataSourceService(dBDataSourceProperties(jsonNode)) + + fun JdbcTemplate(selector: String): BluePrintDBLibGenericService = + blueprintDBDataSourceService(dBDataSourceProperties("blueprintsprocessor.db.$selector")) + + private fun dBDataSourceProperties(jsonNode: JsonNode): DBDataSourceProperties = + when (val type = jsonNode.get("type").textValue()) { + MYSQL_DB -> JacksonUtils.readValue(jsonNode, MySqlDataSourceProperties::class.java) + MARIA_DB -> JacksonUtils.readValue(jsonNode, MariaDataSourceProperties::class.java) + else -> { + throw BluePrintProcessorException( + "DB type ($type) is not supported. Valid types: $MARIA_DB, $MYSQL_DB" + ) + } + }!! + + private fun dBDataSourceProperties(prefix: String): DBDataSourceProperties = + bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java).let { + return when (it) { + MARIA_DB, PROCESSOR_DB -> mariaDBConnectionProperties(prefix) + MYSQL_DB -> mySqlDBConnectionProperties(prefix) + else -> { + throw BluePrintProcessorException( + "DB type ($it) is not supported. Valid types: $MARIA_DB, $MYSQL_DB, $PROCESSOR_DB" + ) + } + } + } + + private fun blueprintDBDataSourceService(dBConnetionProperties: DBDataSourceProperties): BluePrintDBLibGenericService = + when (dBConnetionProperties) { + is MariaDataSourceProperties -> MariaDatabaseConfiguration(dBConnetionProperties) + is MySqlDataSourceProperties -> MySqlDatabaseConfiguration(dBConnetionProperties) + else -> throw BluePrintProcessorException( + "Failed to create db configuration for ${dBConnetionProperties.url}" + ) + } + + private fun mySqlDBConnectionProperties(prefix: String): MySqlDataSourceProperties = + bluePrintPropertiesService.propertyBeanType(prefix, MySqlDataSourceProperties::class.java) + + private fun mariaDBConnectionProperties(prefix: String): MariaDataSourceProperties = + bluePrintPropertiesService.propertyBeanType(prefix, MariaDataSourceProperties::class.java) +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BlueprintDBLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BlueprintDBLibPropertyService.kt deleted file mode 100644 index b272a9708..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BlueprintDBLibPropertyService.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright © 2019 Bell Canada Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.db.primary - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService -import org.onap.ccsdk.cds.blueprintsprocessor.db.DBDataSourceProperties -import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.MARIA_DB -import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.MYSQL_DB -import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants.Companion.PROCESSOR_DB -import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties -import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service -class BlueprintDBLibPropertyService(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - fun JdbcTemplate(jsonNode: JsonNode): BlueprintDBLibGenericService = - blueprintDBDataSourceService(dBDataSourceProperties(jsonNode)) - - fun JdbcTemplate(selector: String): BlueprintDBLibGenericService = - blueprintDBDataSourceService(dBDataSourceProperties("blueprintsprocessor.db.$selector")) - - private fun dBDataSourceProperties(jsonNode: JsonNode): DBDataSourceProperties = - when (val type = jsonNode.get("type").textValue()) { - MYSQL_DB -> JacksonUtils.readValue(jsonNode, MySqlDataSourceProperties::class.java) - MARIA_DB -> JacksonUtils.readValue(jsonNode, MariaDataSourceProperties::class.java) - else -> { - throw BlueprintProcessorException( - "DB type ($type) is not supported. Valid types: $MARIA_DB, $MYSQL_DB" - ) - } - }!! - - private fun dBDataSourceProperties(prefix: String): DBDataSourceProperties = - bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java).let { - return when (it) { - MARIA_DB, PROCESSOR_DB -> mariaDBConnectionProperties(prefix) - MYSQL_DB -> mySqlDBConnectionProperties(prefix) - else -> { - throw BlueprintProcessorException( - "DB type ($it) is not supported. Valid types: $MARIA_DB, $MYSQL_DB, $PROCESSOR_DB" - ) - } - } - } - - private fun blueprintDBDataSourceService(dBConnetionProperties: DBDataSourceProperties): BlueprintDBLibGenericService = - when (dBConnetionProperties) { - is MariaDataSourceProperties -> MariaDatabaseConfiguration(dBConnetionProperties) - is MySqlDataSourceProperties -> MySqlDatabaseConfiguration(dBConnetionProperties) - else -> throw BlueprintProcessorException( - "Failed to create db configuration for ${dBConnetionProperties.url}" - ) - } - - private fun mySqlDBConnectionProperties(prefix: String): MySqlDataSourceProperties = - bluePrintPropertiesService.propertyBeanType(prefix, MySqlDataSourceProperties::class.java) - - private fun mariaDBConnectionProperties(prefix: String): MariaDataSourceProperties = - bluePrintPropertiesService.propertyBeanType(prefix, MariaDataSourceProperties::class.java) -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt index 6132190c2..82895257a 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt @@ -16,14 +16,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties import org.slf4j.LoggerFactory import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.datasource.DriverManagerDataSource import javax.sql.DataSource -class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDataSourceProperties) : BlueprintDBLibGenericService { +class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDataSourceProperties) : BluePrintDBLibGenericService { val log = LoggerFactory.getLogger(MariaDatabaseConfiguration::class.java)!! diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt index ea13dfb83..0761b72d2 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt @@ -16,14 +16,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties import org.slf4j.LoggerFactory import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.jdbc.datasource.DriverManagerDataSource import javax.sql.DataSource -class MySqlDatabaseConfiguration(private val mySqlDataSourceProperties: MySqlDataSourceProperties) : BlueprintDBLibGenericService { +class MySqlDatabaseConfiguration(private val mySqlDataSourceProperties: MySqlDataSourceProperties) : BluePrintDBLibGenericService { override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { return mySqlNamedParameterJdbcTemplate(mySqlDataSource()) diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt index fe6da176b..9d1826395 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt @@ -18,16 +18,16 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.deCompress -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.slf4j.LoggerFactory import java.io.File import java.nio.file.Path @@ -35,9 +35,9 @@ import javax.persistence.MappedSuperclass @MappedSuperclass abstract class BlueprintCatalogServiceImpl( - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val blueprintValidator: BlueprintValidatorService -) : BlueprintCatalogService { + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintValidator: BluePrintValidatorService +) : BluePrintCatalogService { private val log = LoggerFactory.getLogger(BlueprintCatalogServiceImpl::class.java)!! @@ -51,8 +51,8 @@ abstract class BlueprintCatalogServiceImpl( workingDir = blueprintFile.absolutePath archiveFile = normalizedFile(bluePrintLoadConfiguration.blueprintArchivePath, processingId, "cba.zip") - if (!BlueprintArchiveUtils.compress(blueprintFile, archiveFile)) { - throw BlueprintException("Fail to compress blueprint") + if (!BluePrintArchiveUtils.compress(blueprintFile, archiveFile)) { + throw BluePrintException("Fail to compress blueprint") } } else { // Compressed File @@ -63,16 +63,16 @@ abstract class BlueprintCatalogServiceImpl( blueprintFile.deCompress(workingDir) } - var valid = BlueprintConstants.FLAG_N + var valid = BluePrintConstants.FLAG_N if (validate) { - blueprintValidator.validateBlueprints(workingDir!!) - valid = BlueprintConstants.FLAG_Y + blueprintValidator.validateBluePrints(workingDir!!) + valid = BluePrintConstants.FLAG_Y } - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime(processingId, workingDir!!) + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(processingId, workingDir!!) val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - metadata[BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = processingId - metadata[BlueprintConstants.PROPERTY_BLUEPRINT_VALID] = valid + metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = processingId + metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID] = valid save(metadata, archiveFile) @@ -83,7 +83,7 @@ abstract class BlueprintCatalogServiceImpl( name, version, extract ) - ?: throw BlueprintException("Could not find blueprint $name:$version from database") + ?: throw BluePrintException("Could not find blueprint $name:$version from database") override suspend fun deleteFromDatabase(name: String, version: String) = delete(name, version) diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt index 5b9853855..9c007da31 100755 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt @@ -23,21 +23,21 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.optionalClusterServic import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode import org.onap.ccsdk.cds.controllerblueprints.core.deCompress import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintCompileCache -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils import org.slf4j.LoggerFactory import org.springframework.dao.DataIntegrityViolationException import org.springframework.stereotype.Service @@ -51,8 +51,8 @@ import java.util.UUID */ @Service("blueprintsProcessorCatalogService") class BlueprintProcessorCatalogServiceImpl( - bluePrintRuntimeValidatorService: BlueprintValidatorService, - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, + bluePrintRuntimeValidatorService: BluePrintValidatorService, + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, private val blueprintModelRepository: BlueprintModelRepository ) : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) { @@ -61,7 +61,7 @@ class BlueprintProcessorCatalogServiceImpl( override suspend fun delete(name: String, version: String) { // Clean blueprint script cache - val cacheKey = BlueprintFileUtils + val cacheKey = BluePrintFileUtils .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version)) cleanClassLoader(cacheKey) log.info("removed cba file name($name), version($version) from cache") @@ -100,11 +100,11 @@ class BlueprintProcessorCatalogServiceImpl( } check(deployFile.exists() && deployFile.list().isNotEmpty()) { - throw BlueprintProcessorException("file check failed") + throw BluePrintProcessorException("file check failed") } } catch (e: Exception) { deleteNBDir(deployFile.absolutePath) - throw BlueprintProcessorException( + throw BluePrintProcessorException( "failed to get get cba file name($name), version($version) from db" + " : ${e.message}" ) @@ -121,11 +121,11 @@ class BlueprintProcessorCatalogServiceImpl( } override suspend fun save(metadata: MutableMap, archiveFile: File) { - val artifactName = metadata[BlueprintConstants.METADATA_TEMPLATE_NAME] - val artifactVersion = metadata[BlueprintConstants.METADATA_TEMPLATE_VERSION] + val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] check(archiveFile.isFile && !archiveFile.isDirectory) { - throw BlueprintException("Not a valid Archive file(${archiveFile.absolutePath})") + throw BluePrintException("Not a valid Archive file(${archiveFile.absolutePath})") } blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let { @@ -134,7 +134,7 @@ class BlueprintProcessorCatalogServiceImpl( val deployFile = normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion) - val cacheKey = BlueprintFileUtils.compileCacheKey(deployFile) + val cacheKey = BluePrintFileUtils.compileCacheKey(deployFile) cleanClassLoader(cacheKey) deleteNBDir(deployFile).let { @@ -144,20 +144,20 @@ class BlueprintProcessorCatalogServiceImpl( } val blueprintModel = BlueprintModel() - blueprintModel.id = metadata[BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL - blueprintModel.published = metadata[BlueprintConstants.PROPERTY_BLUEPRINT_VALID] - ?: BlueprintConstants.FLAG_N + blueprintModel.published = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID] + ?: BluePrintConstants.FLAG_N blueprintModel.artifactName = artifactName blueprintModel.artifactVersion = artifactVersion - blueprintModel.updatedBy = metadata[BlueprintConstants.METADATA_TEMPLATE_AUTHOR]!! - blueprintModel.tags = metadata[BlueprintConstants.METADATA_TEMPLATE_TAGS]!! + blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]!! + blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS]!! val description = - if (null != metadata[BlueprintConstants.METADATA_TEMPLATE_DESCRIPTION]) metadata[BlueprintConstants.METADATA_TEMPLATE_DESCRIPTION] else "" + if (null != metadata[BluePrintConstants.METADATA_TEMPLATE_DESCRIPTION]) metadata[BluePrintConstants.METADATA_TEMPLATE_DESCRIPTION] else "" blueprintModel.artifactDescription = description val blueprintModelContent = BlueprintModelContent() - blueprintModelContent.id = metadata[BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] blueprintModelContent.contentType = "CBA_ZIP" blueprintModelContent.name = "$artifactName:$artifactVersion" blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" @@ -169,7 +169,7 @@ class BlueprintProcessorCatalogServiceImpl( try { blueprintModelRepository.saveAndFlush(blueprintModel) } catch (ex: DataIntegrityViolationException) { - throw BlueprintException( + throw BluePrintException( ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " + "is already exist in database: ${ex.message}", @@ -179,10 +179,10 @@ class BlueprintProcessorCatalogServiceImpl( } private suspend fun cleanClassLoader(cacheKey: String) { - val clusterService = BlueprintDependencyService.optionalClusterService() + val clusterService = BluePrintDependencyService.optionalClusterService() if (clusterService != null && clusterService.clusterJoined()) { log.info("Sending ClusterMessage: Clean Classloader Cache") clusterService.sendMessage(BlueprintClusterTopic.BLUEPRINT_CLEAN_COMPILER_CACHE, cacheKey) - } else BlueprintCompileCache.cleanClassLoader(cacheKey) + } else BluePrintCompileCache.cleanClassLoader(cacheKey) } } diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt index 4084e156c..b7b1f78cf 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt @@ -20,16 +20,16 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.mock.MockBlueprintProcessorCatalogServiceImpl import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service.BlueprintCatalogServiceImpl import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service.BlueprintProcessorCatalogServiceImpl -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.compress import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.context.annotation.ComponentScan @@ -46,7 +46,7 @@ import kotlin.test.assertTrue @ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor"]) @ContextConfiguration( classes = [ - BlueprintProcessorCatalogServiceImpl::class, BlueprintCoreConfiguration::class, + BlueprintProcessorCatalogServiceImpl::class, BluePrintCoreConfiguration::class, MockBlueprintProcessorCatalogServiceImpl::class ] ) @@ -57,9 +57,9 @@ class BlueprintProcessorCatalogServiceImplTest { lateinit var blueprintsProcessorCatalogService: BlueprintCatalogServiceImpl @Autowired - lateinit var blueprintCoreConfiguration: BlueprintCoreConfiguration + lateinit var blueprintCoreConfiguration: BluePrintCoreConfiguration - private lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> + private lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> private val blueprintId = "1234" @@ -72,7 +72,7 @@ class BlueprintProcessorCatalogServiceImplTest { normalizedFile("./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") .compress(normalizedFile("./target/blueprints/generated-cba.zip")) - bluePrintRuntimeService = BlueprintMetadataUtils.bluePrintRuntime( + bluePrintRuntimeService = BluePrintMetadataUtils.bluePrintRuntime( blueprintId, "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -103,7 +103,7 @@ class BlueprintProcessorCatalogServiceImplTest { val file = normalizedFile("./target/blueprints/generated-cba.zip") assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - metadata[BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = blueprintId + metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = blueprintId blueprintsProcessorCatalogService.save(metadata, file) } @@ -115,7 +115,7 @@ class BlueprintProcessorCatalogServiceImplTest { val file = normalizedFile("./target/blueprints/generated-cba.zip") assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - metadata[BlueprintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = blueprintId + metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] = blueprintId blueprintsProcessorCatalogService.save(metadata, file) blueprintsProcessorCatalogService.get("baseconfiguration", "1.0.0", true) diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSLTest.kt index d182651af..dd84e5b02 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/DatabasePropertiesDSLTest.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import kotlin.test.assertEquals @@ -68,12 +68,12 @@ class DatabasePropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_DB}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt index 38a8ef427..d8192acfa 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt @@ -27,7 +27,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.db.primary"], entityManagerFactoryRef = "primaryEntityManager", diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt index 6135f5bbd..248181f16 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.mock import io.mockk.coEvery import io.mockk.mockk -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @@ -26,10 +26,10 @@ import org.springframework.context.annotation.Configuration open class MockBlueprintProcessorCatalogServiceImpl { @Bean(name = ["bluePrintRuntimeValidatorService"]) - open fun bluePrintRuntimeValidatorService(): BlueprintValidatorService { - val bluePrintValidatorService = mockk() - coEvery { bluePrintValidatorService.validateBlueprints(any()) } returns true - coEvery { bluePrintValidatorService.validateBlueprints(any>()) } returns true + open fun bluePrintRuntimeValidatorService(): BluePrintValidatorService { + val bluePrintValidatorService = mockk() + coEvery { bluePrintValidatorService.validateBluePrints(any()) } returns true + coEvery { bluePrintValidatorService.validateBluePrints(any>()) } returns true return bluePrintValidatorService } } diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt index 587e020a4..dfe95733f 100644 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt @@ -30,7 +30,7 @@ import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher class AafAuthDmaapClientService( private val clientProps: AafAuthDmaapClientProperties ) : - BlueprintDmaapClientService { + BluePrintDmaapClientService { /** * The constructed DMAAP client. diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt new file mode 100644 index 000000000..82c3f3a80 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.att.nsa.mr.client.MRBatchingPublisher +import com.att.nsa.mr.client.MRPublisher +import org.slf4j.LoggerFactory +import java.io.IOException +import java.util.concurrent.TimeUnit + +/** + * Abstraction of DMAAP client services that could form DMAAP client from the + * properties provided. This abstraction also provides a mechanism to send + * messages with the given partition in a session and closing the same. + */ +interface BluePrintDmaapClientService { + + /** + * Static variable for logging. + */ + companion object { + + var log = LoggerFactory.getLogger( + BluePrintDmaapClientService::class.java + )!! + } + + /** + * Returns the properly constructed DMAAP client with the type. + */ + fun getDmaapClient(): MutableList + + /** + * Sends messages to the sessions created by the information provided from + * application.properties and event.properties file + */ + fun sendMessage(msgs: Collection): Boolean { + var success = true + val clients = getDmaapClient() + val dmaapMsgs = mutableListOf() + for (m in msgs) { + dmaapMsgs.add(MRPublisher.message("1", m)) + } + log.info("Sending messages to the DMAAP Server") + for (client in clients) { + try { + client.send(dmaapMsgs) + } catch (e: IOException) { + success = false + log.error(e.message, e) + } + } + return success + } + + /** + * Sends message to the sessions created by the information provided from + * application.properties and event.properties file + */ + fun sendMessage(msg: String): Boolean { + val msgs = mutableListOf() + msgs.add(msg) + return sendMessage(msgs) + } + + /** + * Closes the opened session that was used for sending messages. + */ + fun close(timeout: Long): MutableList>? { + log.debug("Closing the DMAAP producer clients") + var msgs: MutableList> = + mutableListOf() + val clients = getDmaapClient() + for (client in clients) { + try { + var ms = client.close(timeout, TimeUnit.SECONDS) + msgs.add(ms) + } catch (e: IOException) { + log.warn( + "Unable to cleanly close the connection from the " + + "client $client", + e + ) + } + } + return msgs + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt new file mode 100644 index 000000000..20d9afdef --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +/** + * Representation of DMAAP lib configuration to load the required property + * files into the application context. + */ +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintDmaapLibConfiguration + +/** + * Util constants required for DMAAP library to use. + */ +class DmaapLibConstants { + + companion object { + + const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" + + "-dmaap-lib-property-service" + const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH" + const val TYPE_HTTP_AAF_AUTH = "HTTPAAF" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt new file mode 100644 index 000000000..e5c9d432f --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_AAF_AUTH +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_NO_AUTH +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.PropertySource +import org.springframework.context.annotation.PropertySources +import org.springframework.core.env.ConfigurableEnvironment +import org.springframework.core.env.Environment +import org.springframework.core.io.support.ResourcePropertySource +import org.springframework.stereotype.Service +import java.util.Properties + +/** + * Representation of DMAAP lib property service to load the properties + * according to the connection type to the DMAAP server and returning back + * the appropriate DMAAP client to send messages DMAAP client. + */ +@Service(SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY) +@Configuration +@PropertySources(PropertySource("classpath:event.properties")) +open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + /** + * Static variable for logging. + */ + companion object { + + var log = LoggerFactory.getLogger( + BluePrintDmaapLibPropertyService::class.java + )!! + } + + /** + * Environment entity to derive it from the system to load a specific + * property file. + */ + @Autowired + lateinit var env: Environment + + /** + * Returns the DMAAP client by providing the input properties as a JSON + * node. + */ + fun blueprintDmaapClientService(jsonNode: JsonNode): + BluePrintDmaapClientService { + val dmaapProps = dmaapClientProperties(jsonNode) + return blueprintDmaapClientService(dmaapProps) + } + + /** + * Returns the DMAAP client by providing the input properties as a + * selector string. + */ + fun blueprintDmaapClientService(selector: String): + BluePrintDmaapClientService { + val prefix = "blueprintsprocessor.dmaapclient.$selector" + val dmaapProps = dmaapClientProperties(prefix) + return blueprintDmaapClientService(dmaapProps) + } + + /** + * Returns the DMAAP client properties from the type of connection it + * requires. + */ + fun dmaapClientProperties(prefix: String): DmaapClientProperties { + val type = bluePrintPropertiesService.propertyBeanType( + "$prefix.type", String::class.java + ) + val clientProps: DmaapClientProperties + + when (type) { + TYPE_HTTP_NO_AUTH -> { + clientProps = bluePrintPropertiesService.propertyBeanType( + prefix, HttpNoAuthDmaapClientProperties::class.java + ) + clientProps.props = parseEventProps() + } + + TYPE_HTTP_AAF_AUTH -> { + clientProps = bluePrintPropertiesService.propertyBeanType( + prefix, AafAuthDmaapClientProperties::class.java + ) + clientProps.props = parseEventProps() + } + + else -> { + throw BluePrintProcessorException( + "DMAAP adaptor($type) is " + + "not supported" + ) + } + } + return clientProps + } + + /** + * Returns the DMAAP client properties from the type of connection it + * requires. + */ + fun dmaapClientProperties(jsonNode: JsonNode): DmaapClientProperties { + val type = jsonNode.get("type").textValue() + val clientProps: DmaapClientProperties + + when (type) { + TYPE_HTTP_NO_AUTH -> { + clientProps = JacksonUtils.readValue( + jsonNode, + HttpNoAuthDmaapClientProperties::class.java + )!! + clientProps.props = parseEventProps() + } + + TYPE_HTTP_AAF_AUTH -> { + clientProps = JacksonUtils.readValue( + jsonNode, + AafAuthDmaapClientProperties::class.java + )!! + clientProps.props = parseEventProps() + } + + else -> { + throw BluePrintProcessorException( + "DMAAP adaptor($type) is " + + "not supported" + ) + } + } + return clientProps + } + + /** + * Returns DMAAP client service according to the type of client properties. + */ + private fun blueprintDmaapClientService(clientProps: DmaapClientProperties): + BluePrintDmaapClientService { + when (clientProps) { + is HttpNoAuthDmaapClientProperties -> { + return HttpNoAuthDmaapClientService(clientProps) + } + + is AafAuthDmaapClientProperties -> { + return AafAuthDmaapClientService(clientProps) + } + + else -> { + throw BluePrintProcessorException( + "Unable to get the DMAAP " + + "client" + ) + } + } + } + + /** + * Parses the event.properties file which contains the default values for + * the connection required. + */ + private fun parseEventProps(): Properties { + val prodProps = Properties() + val proProps = (env as ConfigurableEnvironment).propertySources.get( + "class path resource [event.properties]" + ) + + if (proProps != null) { + val entries = (proProps as ResourcePropertySource).source.entries + for (e in entries) { + prodProps.put(e.key, e.value) + } + } else { + log.error("Unable to load the event.properties file") + } + return prodProps + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapClientService.kt deleted file mode 100644 index c275e7e8b..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapClientService.kt +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.dmaap - -import com.att.nsa.mr.client.MRBatchingPublisher -import com.att.nsa.mr.client.MRPublisher -import org.slf4j.LoggerFactory -import java.io.IOException -import java.util.concurrent.TimeUnit - -/** - * Abstraction of DMAAP client services that could form DMAAP client from the - * properties provided. This abstraction also provides a mechanism to send - * messages with the given partition in a session and closing the same. - */ -interface BlueprintDmaapClientService { - - /** - * Static variable for logging. - */ - companion object { - - var log = LoggerFactory.getLogger( - BlueprintDmaapClientService::class.java - )!! - } - - /** - * Returns the properly constructed DMAAP client with the type. - */ - fun getDmaapClient(): MutableList - - /** - * Sends messages to the sessions created by the information provided from - * application.properties and event.properties file - */ - fun sendMessage(msgs: Collection): Boolean { - var success = true - val clients = getDmaapClient() - val dmaapMsgs = mutableListOf() - for (m in msgs) { - dmaapMsgs.add(MRPublisher.message("1", m)) - } - log.info("Sending messages to the DMAAP Server") - for (client in clients) { - try { - client.send(dmaapMsgs) - } catch (e: IOException) { - success = false - log.error(e.message, e) - } - } - return success - } - - /** - * Sends message to the sessions created by the information provided from - * application.properties and event.properties file - */ - fun sendMessage(msg: String): Boolean { - val msgs = mutableListOf() - msgs.add(msg) - return sendMessage(msgs) - } - - /** - * Closes the opened session that was used for sending messages. - */ - fun close(timeout: Long): MutableList>? { - log.debug("Closing the DMAAP producer clients") - var msgs: MutableList> = - mutableListOf() - val clients = getDmaapClient() - for (client in clients) { - try { - var ms = client.close(timeout, TimeUnit.SECONDS) - msgs.add(ms) - } catch (e: IOException) { - log.warn( - "Unable to cleanly close the connection from the " + - "client $client", - e - ) - } - } - return msgs - } -} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibConfiguration.kt deleted file mode 100644 index c64c33231..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibConfiguration.kt +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.dmaap - -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -/** - * Representation of DMAAP lib configuration to load the required property - * files into the application context. - */ -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BlueprintDmaapLibConfiguration - -/** - * Util constants required for DMAAP library to use. - */ -class DmaapLibConstants { - - companion object { - - const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" + - "-dmaap-lib-property-service" - const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH" - const val TYPE_HTTP_AAF_AUTH = "HTTPAAF" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibPropertyService.kt deleted file mode 100644 index 7bc9d605f..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BlueprintDmaapLibPropertyService.kt +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.dmaap - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY -import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_AAF_AUTH -import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_NO_AUTH -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.PropertySource -import org.springframework.context.annotation.PropertySources -import org.springframework.core.env.ConfigurableEnvironment -import org.springframework.core.env.Environment -import org.springframework.core.io.support.ResourcePropertySource -import org.springframework.stereotype.Service -import java.util.Properties - -/** - * Representation of DMAAP lib property service to load the properties - * according to the connection type to the DMAAP server and returning back - * the appropriate DMAAP client to send messages DMAAP client. - */ -@Service(SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY) -@Configuration -@PropertySources(PropertySource("classpath:event.properties")) -open class BlueprintDmaapLibPropertyService(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - /** - * Static variable for logging. - */ - companion object { - - var log = LoggerFactory.getLogger( - BlueprintDmaapLibPropertyService::class.java - )!! - } - - /** - * Environment entity to derive it from the system to load a specific - * property file. - */ - @Autowired - lateinit var env: Environment - - /** - * Returns the DMAAP client by providing the input properties as a JSON - * node. - */ - fun blueprintDmaapClientService(jsonNode: JsonNode): - BlueprintDmaapClientService { - val dmaapProps = dmaapClientProperties(jsonNode) - return blueprintDmaapClientService(dmaapProps) - } - - /** - * Returns the DMAAP client by providing the input properties as a - * selector string. - */ - fun blueprintDmaapClientService(selector: String): - BlueprintDmaapClientService { - val prefix = "blueprintsprocessor.dmaapclient.$selector" - val dmaapProps = dmaapClientProperties(prefix) - return blueprintDmaapClientService(dmaapProps) - } - - /** - * Returns the DMAAP client properties from the type of connection it - * requires. - */ - fun dmaapClientProperties(prefix: String): DmaapClientProperties { - val type = bluePrintPropertiesService.propertyBeanType( - "$prefix.type", String::class.java - ) - val clientProps: DmaapClientProperties - - when (type) { - TYPE_HTTP_NO_AUTH -> { - clientProps = bluePrintPropertiesService.propertyBeanType( - prefix, HttpNoAuthDmaapClientProperties::class.java - ) - clientProps.props = parseEventProps() - } - - TYPE_HTTP_AAF_AUTH -> { - clientProps = bluePrintPropertiesService.propertyBeanType( - prefix, AafAuthDmaapClientProperties::class.java - ) - clientProps.props = parseEventProps() - } - - else -> { - throw BlueprintProcessorException( - "DMAAP adaptor($type) is " + - "not supported" - ) - } - } - return clientProps - } - - /** - * Returns the DMAAP client properties from the type of connection it - * requires. - */ - fun dmaapClientProperties(jsonNode: JsonNode): DmaapClientProperties { - val type = jsonNode.get("type").textValue() - val clientProps: DmaapClientProperties - - when (type) { - TYPE_HTTP_NO_AUTH -> { - clientProps = JacksonUtils.readValue( - jsonNode, - HttpNoAuthDmaapClientProperties::class.java - )!! - clientProps.props = parseEventProps() - } - - TYPE_HTTP_AAF_AUTH -> { - clientProps = JacksonUtils.readValue( - jsonNode, - AafAuthDmaapClientProperties::class.java - )!! - clientProps.props = parseEventProps() - } - - else -> { - throw BlueprintProcessorException( - "DMAAP adaptor($type) is " + - "not supported" - ) - } - } - return clientProps - } - - /** - * Returns DMAAP client service according to the type of client properties. - */ - private fun blueprintDmaapClientService(clientProps: DmaapClientProperties): - BlueprintDmaapClientService { - when (clientProps) { - is HttpNoAuthDmaapClientProperties -> { - return HttpNoAuthDmaapClientService(clientProps) - } - - is AafAuthDmaapClientProperties -> { - return AafAuthDmaapClientService(clientProps) - } - - else -> { - throw BlueprintProcessorException( - "Unable to get the DMAAP " + - "client" - ) - } - } - } - - /** - * Parses the event.properties file which contains the default values for - * the connection required. - */ - private fun parseEventProps(): Properties { - val prodProps = Properties() - val proProps = (env as ConfigurableEnvironment).propertySources.get( - "class path resource [event.properties]" - ) - - if (proProps != null) { - val entries = (proProps as ResourcePropertySource).source.entries - for (e in entries) { - prodProps.put(e.key, e.value) - } - } else { - log.error("Unable to load the event.properties file") - } - return prodProps - } -} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt index 4f9f89ae2..d4adfcaac 100644 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt @@ -31,7 +31,7 @@ class HttpNoAuthDmaapClientService( private val clientProps: HttpNoAuthDmaapClientProperties ) : - BlueprintDmaapClientService { + BluePrintDmaapClientService { /** * The constructed DMAAP client. diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt index c44f6a4a3..e6043caae 100644 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt @@ -23,10 +23,10 @@ package org.ccsdk.apps.blueprintprocessor.dmaap import com.fasterxml.jackson.databind.ObjectMapper import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BlueprintDmaapLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BlueprintDmaapLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BluePrintDmaapLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BluePrintDmaapLibPropertyService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration @@ -51,8 +51,8 @@ import kotlin.test.assertNotNull @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @ContextConfiguration( classes = [ - BlueprintDmaapLibConfiguration::class, TestController::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintDmaapLibConfiguration::class, TestController::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -69,7 +69,7 @@ import kotlin.test.assertNotNull class TestDmaapEventPublisher { @Autowired - lateinit var dmaapService: BlueprintDmaapLibPropertyService + lateinit var dmaapService: BluePrintDmaapLibPropertyService /** * Tests the event properties being set properly and sent as request. diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt new file mode 100644 index 000000000..97b462a3c --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt @@ -0,0 +1,27 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc + +import io.grpc.Metadata + +fun Metadata.getStringKey(key: String): String? { + return this.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER)) +} + +fun Metadata.putStringKeyValue(key: String, value: String) { + this.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value) +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt new file mode 100644 index 000000000..e94400d9b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt @@ -0,0 +1,55 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +open class BluePrintGrpcLibConfiguration + +/** + * Exposed Dependency Service by this GRPC Lib Module + */ +fun BluePrintDependencyService.grpcLibPropertyService(): BluePrintGrpcLibPropertyService = + instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY) + +fun BluePrintDependencyService.grpcClientService(selector: String): BluePrintGrpcClientService { + return grpcLibPropertyService().blueprintGrpcClientService(selector) +} + +fun BluePrintDependencyService.grpcClientService(jsonNode: JsonNode): BluePrintGrpcClientService { + return grpcLibPropertyService().blueprintGrpcClientService(jsonNode) +} + +class GRPCLibConstants { + companion object { + + const val SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY = "blueprint-grpc-lib-property-service" + const val PROPERTY_GRPC_CLIENT_PREFIX = "blueprintsprocessor.grpcclient." + const val PROPERTY_GRPC_SERVER_PREFIX = "blueprintsprocessor.grpcserver." + const val TYPE_TOKEN_AUTH = "token-auth" + const val TYPE_BASIC_AUTH = "basic-auth" + const val TYPE_TLS_AUTH = "tls-auth" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt new file mode 100644 index 000000000..ebb9a5b32 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc + +/** GRPC Server Properties */ +open class GrpcServerProperties { + + lateinit var type: String + var port: Int = -1 +} + +open class TokenAuthGrpcServerProperties : GrpcServerProperties() { + + lateinit var token: String +} + +open class TLSAuthGrpcServerProperties : GrpcServerProperties() { + + lateinit var certChain: String + lateinit var privateKey: String + + /** Below Used only for Mutual TLS */ + var trustCertCollection: String? = null +} + +/** GRPC Client Properties */ +open class GrpcClientProperties { + + lateinit var type: String + lateinit var host: String + var port: Int = -1 +} + +open class TokenAuthGrpcClientProperties : GrpcClientProperties() { + + lateinit var token: String +} + +open class TLSAuthGrpcClientProperties : GrpcClientProperties() { + + var trustCertCollection: String? = null + + /** Below Used only for Mutual TLS */ + var clientCertChain: String? = null + var clientPrivateKey: String? = null +} + +open class BasicAuthGrpcClientProperties : GrpcClientProperties() { + + lateinit var username: String + lateinit var password: String +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcExtensions.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcExtensions.kt deleted file mode 100644 index 97b462a3c..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcExtensions.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc - -import io.grpc.Metadata - -fun Metadata.getStringKey(key: String): String? { - return this.get(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER)) -} - -fun Metadata.putStringKeyValue(key: String, value: String) { - this.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value) -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibConfiguration.kt deleted file mode 100644 index 806e4c6f2..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibConfiguration.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcClientService -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcLibPropertyService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -open class BlueprintGrpcLibConfiguration - -/** - * Exposed Dependency Service by this GRPC Lib Module - */ -fun BlueprintDependencyService.grpcLibPropertyService(): BlueprintGrpcLibPropertyService = - instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY) - -fun BlueprintDependencyService.grpcClientService(selector: String): BlueprintGrpcClientService { - return grpcLibPropertyService().blueprintGrpcClientService(selector) -} - -fun BlueprintDependencyService.grpcClientService(jsonNode: JsonNode): BlueprintGrpcClientService { - return grpcLibPropertyService().blueprintGrpcClientService(jsonNode) -} - -class GRPCLibConstants { - companion object { - - const val SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY = "blueprint-grpc-lib-property-service" - const val PROPERTY_GRPC_CLIENT_PREFIX = "blueprintsprocessor.grpcclient." - const val PROPERTY_GRPC_SERVER_PREFIX = "blueprintsprocessor.grpcserver." - const val TYPE_TOKEN_AUTH = "token-auth" - const val TYPE_BASIC_AUTH = "basic-auth" - const val TYPE_TLS_AUTH = "tls-auth" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibData.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibData.kt deleted file mode 100644 index ebb9a5b32..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BlueprintGrpcLibData.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc - -/** GRPC Server Properties */ -open class GrpcServerProperties { - - lateinit var type: String - var port: Int = -1 -} - -open class TokenAuthGrpcServerProperties : GrpcServerProperties() { - - lateinit var token: String -} - -open class TLSAuthGrpcServerProperties : GrpcServerProperties() { - - lateinit var certChain: String - lateinit var privateKey: String - - /** Below Used only for Mutual TLS */ - var trustCertCollection: String? = null -} - -/** GRPC Client Properties */ -open class GrpcClientProperties { - - lateinit var type: String - lateinit var host: String - var port: Int = -1 -} - -open class TokenAuthGrpcClientProperties : GrpcClientProperties() { - - lateinit var token: String -} - -open class TLSAuthGrpcClientProperties : GrpcClientProperties() { - - var trustCertCollection: String? = null - - /** Below Used only for Mutual TLS */ - var clientCertChain: String? = null - var clientPrivateKey: String? = null -} - -open class BasicAuthGrpcClientProperties : GrpcClientProperties() { - - lateinit var username: String - lateinit var password: String -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSL.kt index 853f74930..8063e8909 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -30,48 +30,48 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Types DSL for GRPC Server Producer */ fun ServiceTemplateBuilder.relationshipTypeConnectsToGrpcServer() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToGrpcServer() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToGrpcServer() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToGrpcServer(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToGrpcServer(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through GRPC Server." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } fun ServiceTemplateBuilder.relationshipTypeConnectsToGrpcClient() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToGrpcClient() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToGrpcClient() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToGrpcClient(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToGrpcClient(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through GRPC Client." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -89,25 +89,25 @@ fun TopologyTemplateBuilder.relationshipTemplateGrpcServer( class GrpcServerRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER, description ) { fun tokenAuth(block: GrpcServerTokenAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tokenAuthGrpcServerProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tokenAuthGrpcServerProperties(block)) } fun tlsAuth(block: GrpcServerTLSAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tlsAuthGrpcServerProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tlsAuthGrpcServerProperties(block)) } } -fun BlueprintTypes.tokenAuthGrpcServerProperties(block: GrpcServerTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tokenAuthGrpcServerProperties(block: GrpcServerTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = GrpcServerTokenAuthPropertiesAssignmentBuilder().apply(block).build() assignments[GrpcServerProperties::type.name] = GRPCLibConstants.TYPE_TOKEN_AUTH.asJsonPrimitive() return assignments.asJsonNode() } -fun BlueprintTypes.tlsAuthGrpcServerProperties(block: GrpcServerTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tlsAuthGrpcServerProperties(block: GrpcServerTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = GrpcServerTLSAuthPropertiesAssignmentBuilder().apply(block).build() assignments[GrpcServerProperties::type.name] = GRPCLibConstants.TYPE_TLS_AUTH.asJsonPrimitive() return assignments.asJsonNode() @@ -158,35 +158,35 @@ fun TopologyTemplateBuilder.relationshipTemplateGrpcClient( class GrpcClientRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT, description ) { fun basicAuth(block: GrpcClientBasicAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.basicAuthGrpcClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.basicAuthGrpcClientProperties(block)) } fun tokenAuth(block: GrpcClientTokenAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tokenAuthGrpcClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tokenAuthGrpcClientProperties(block)) } fun tlsAuth(block: GrpcClientTLSAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tlsAuthGrpcClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tlsAuthGrpcClientProperties(block)) } } -fun BlueprintTypes.basicAuthGrpcClientProperties(block: GrpcClientBasicAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.basicAuthGrpcClientProperties(block: GrpcClientBasicAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = GrpcClientBasicAuthPropertiesAssignmentBuilder().apply(block).build() assignments[GrpcClientProperties::type.name] = GRPCLibConstants.TYPE_BASIC_AUTH.asJsonPrimitive() return assignments.asJsonNode() } -fun BlueprintTypes.tokenAuthGrpcClientProperties(block: GrpcClientTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tokenAuthGrpcClientProperties(block: GrpcClientTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = GrpcClientTokenAuthPropertiesAssignmentBuilder().apply(block).build() assignments[GrpcClientProperties::type.name] = GRPCLibConstants.TYPE_TOKEN_AUTH.asJsonPrimitive() return assignments.asJsonNode() } -fun BlueprintTypes.tlsAuthGrpcClientProperties(block: GrpcClientTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tlsAuthGrpcClientProperties(block: GrpcClientTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = GrpcClientTLSAuthPropertiesAssignmentBuilder().apply(block).build() assignments[GrpcClientProperties::type.name] = GRPCLibConstants.TYPE_TLS_AUTH.asJsonPrimitive() return assignments.asJsonNode() diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt index 7465ba044..aaa4d5f26 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt @@ -23,11 +23,11 @@ import io.grpc.ServerCall import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.GrpcLoggerService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintDownloadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintRemoveInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput import org.slf4j.MDC @@ -62,22 +62,22 @@ class GrpcServerLoggingInterceptor : ServerInterceptor { when (message) { is ExecutionServiceInput -> { val commonHeader = message.commonHeader - ?: throw BlueprintProcessorException("missing common header in request") + ?: throw BluePrintProcessorException("missing common header in request") loggingService.grpcRequesting(call, commonHeader, next) } - is BlueprintUploadInput -> { + is BluePrintUploadInput -> { val commonHeader = message.commonHeader - ?: throw BlueprintProcessorException("missing common header in request") + ?: throw BluePrintProcessorException("missing common header in request") loggingService.grpcRequesting(call, commonHeader, next) } - is BlueprintDownloadInput -> { + is BluePrintDownloadInput -> { val commonHeader = message.commonHeader - ?: throw BlueprintProcessorException("missing common header in request") + ?: throw BluePrintProcessorException("missing common header in request") loggingService.grpcRequesting(call, commonHeader, next) } - is BlueprintRemoveInput -> { + is BluePrintRemoveInput -> { val commonHeader = message.commonHeader - ?: throw BlueprintProcessorException("missing common header in request") + ?: throw BluePrintProcessorException("missing common header in request") loggingService.grpcRequesting(call, commonHeader, next) } else -> { diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt index 72453f596..f7be8c66d 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt @@ -22,7 +22,7 @@ import io.grpc.netty.NettyChannelBuilder import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties open class BasicAuthGrpcClientService(private val basicAuthGrpcClientProperties: BasicAuthGrpcClientProperties) : - BlueprintGrpcClientService { + BluePrintGrpcClientService { override suspend fun channel(): ManagedChannel { val managedChannel = NettyChannelBuilder diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt new file mode 100644 index 000000000..a102ee6da --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt @@ -0,0 +1,182 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcServerProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcServerProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY) +open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + fun blueprintGrpcServerService(jsonNode: JsonNode): BluePrintGrpcServerService { + val grpcServerProperties = grpcServerProperties(jsonNode) + return blueprintGrpcServerService(grpcServerProperties) + } + + fun blueprintGrpcServerService(selector: String): BluePrintGrpcServerService { + val prefix = "${GRPCLibConstants.PROPERTY_GRPC_SERVER_PREFIX}$selector" + val grpcServerProperties = grpcServerProperties(prefix) + return blueprintGrpcServerService(grpcServerProperties) + } + + /** GRPC Server Lib Property Service */ + fun grpcServerProperties(jsonNode: JsonNode): GrpcServerProperties { + return when (val type = jsonNode.get("type").textValue()) { + GRPCLibConstants.TYPE_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, TokenAuthGrpcServerProperties::class.java)!! + } + GRPCLibConstants.TYPE_TLS_AUTH -> { + JacksonUtils.readValue(jsonNode, TLSAuthGrpcServerProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Grpc type($type) not supported") + } + } + } + + fun grpcServerProperties(prefix: String): GrpcServerProperties { + val type = bluePrintPropertiesService.propertyBeanType( + "$prefix.type", String::class.java + ) + return when (type) { + GRPCLibConstants.TYPE_TOKEN_AUTH -> { + tokenAuthGrpcServerProperties(prefix) + } + GRPCLibConstants.TYPE_TLS_AUTH -> { + tlsAuthGrpcServerProperties(prefix) + } + else -> { + throw BluePrintProcessorException("Grpc type($type) not supported") + } + } + } + + private fun tokenAuthGrpcServerProperties(prefix: String): TokenAuthGrpcServerProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthGrpcServerProperties::class.java) + } + + private fun tlsAuthGrpcServerProperties(prefix: String): TLSAuthGrpcServerProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcServerProperties::class.java) + } + + private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties): + BluePrintGrpcServerService { + when (grpcServerProperties) { + is TLSAuthGrpcServerProperties -> { + return TLSAuthGrpcServerService(grpcServerProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get grpc client service for properties $grpcServerProperties") + } + } + } + + /** GRPC Client Lib Property Service */ + + fun blueprintGrpcClientService(jsonNode: JsonNode): BluePrintGrpcClientService { + val restClientProperties = grpcClientProperties(jsonNode) + return blueprintGrpcClientService(restClientProperties) + } + + fun blueprintGrpcClientService(selector: String): BluePrintGrpcClientService { + val prefix = "${GRPCLibConstants.PROPERTY_GRPC_CLIENT_PREFIX}$selector" + val restClientProperties = grpcClientProperties(prefix) + return blueprintGrpcClientService(restClientProperties) + } + + fun grpcClientProperties(jsonNode: JsonNode): GrpcClientProperties { + val type = jsonNode.get("type").returnNullIfMissing()?.textValue() + ?: BluePrintProcessorException("missing type property") + return when (type) { + GRPCLibConstants.TYPE_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, TokenAuthGrpcClientProperties::class.java)!! + } + GRPCLibConstants.TYPE_TLS_AUTH -> { + JacksonUtils.readValue(jsonNode, TLSAuthGrpcClientProperties::class.java)!! + } + GRPCLibConstants.TYPE_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, BasicAuthGrpcClientProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Grpc type($type) not supported") + } + } + } + + fun grpcClientProperties(prefix: String): GrpcClientProperties { + val type = bluePrintPropertiesService.propertyBeanType( + "$prefix.type", String::class.java + ) + return when (type) { + GRPCLibConstants.TYPE_TOKEN_AUTH -> { + tokenAuthGrpcClientProperties(prefix) + } + GRPCLibConstants.TYPE_TLS_AUTH -> { + tlsAuthGrpcClientProperties(prefix) + } + GRPCLibConstants.TYPE_BASIC_AUTH -> { + basicAuthGrpcClientProperties(prefix) + } + else -> { + throw BluePrintProcessorException("Grpc type($type) not supported") + } + } + } + + fun blueprintGrpcClientService(grpcClientProperties: GrpcClientProperties): + BluePrintGrpcClientService { + return when (grpcClientProperties) { + is TokenAuthGrpcClientProperties -> { + TokenAuthGrpcClientService(grpcClientProperties) + } + is TLSAuthGrpcClientProperties -> { + TLSAuthGrpcClientService(grpcClientProperties) + } + is BasicAuthGrpcClientProperties -> { + BasicAuthGrpcClientService(grpcClientProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get grpc service for type(${grpcClientProperties.type})") + } + } + } + + private fun tokenAuthGrpcClientProperties(prefix: String): TokenAuthGrpcClientProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthGrpcClientProperties::class.java) + } + + private fun tlsAuthGrpcClientProperties(prefix: String): TLSAuthGrpcClientProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcClientProperties::class.java) + } + + private fun basicAuthGrpcClientProperties(prefix: String): BasicAuthGrpcClientProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, BasicAuthGrpcClientProperties::class.java) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt new file mode 100644 index 000000000..d2db14a53 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt @@ -0,0 +1,31 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service + +import io.grpc.ManagedChannel +import io.grpc.netty.NettyServerBuilder + +interface BluePrintGrpcServerService { + + fun serverBuilder(): NettyServerBuilder +} + +interface BluePrintGrpcClientService { + + suspend fun channel(): ManagedChannel +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyService.kt deleted file mode 100644 index 9b95edfc3..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyService.kt +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcServerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcServerProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY) -open class BlueprintGrpcLibPropertyService(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - fun blueprintGrpcServerService(jsonNode: JsonNode): BlueprintGrpcServerService { - val grpcServerProperties = grpcServerProperties(jsonNode) - return blueprintGrpcServerService(grpcServerProperties) - } - - fun blueprintGrpcServerService(selector: String): BlueprintGrpcServerService { - val prefix = "${GRPCLibConstants.PROPERTY_GRPC_SERVER_PREFIX}$selector" - val grpcServerProperties = grpcServerProperties(prefix) - return blueprintGrpcServerService(grpcServerProperties) - } - - /** GRPC Server Lib Property Service */ - fun grpcServerProperties(jsonNode: JsonNode): GrpcServerProperties { - return when (val type = jsonNode.get("type").textValue()) { - GRPCLibConstants.TYPE_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, TokenAuthGrpcServerProperties::class.java)!! - } - GRPCLibConstants.TYPE_TLS_AUTH -> { - JacksonUtils.readValue(jsonNode, TLSAuthGrpcServerProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException("Grpc type($type) not supported") - } - } - } - - fun grpcServerProperties(prefix: String): GrpcServerProperties { - val type = bluePrintPropertiesService.propertyBeanType( - "$prefix.type", String::class.java - ) - return when (type) { - GRPCLibConstants.TYPE_TOKEN_AUTH -> { - tokenAuthGrpcServerProperties(prefix) - } - GRPCLibConstants.TYPE_TLS_AUTH -> { - tlsAuthGrpcServerProperties(prefix) - } - else -> { - throw BlueprintProcessorException("Grpc type($type) not supported") - } - } - } - - private fun tokenAuthGrpcServerProperties(prefix: String): TokenAuthGrpcServerProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthGrpcServerProperties::class.java) - } - - private fun tlsAuthGrpcServerProperties(prefix: String): TLSAuthGrpcServerProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcServerProperties::class.java) - } - - private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties): - BlueprintGrpcServerService { - when (grpcServerProperties) { - is TLSAuthGrpcServerProperties -> { - return TLSAuthGrpcServerService(grpcServerProperties) - } - else -> { - throw BlueprintProcessorException("couldn't get grpc client service for properties $grpcServerProperties") - } - } - } - - /** GRPC Client Lib Property Service */ - - fun blueprintGrpcClientService(jsonNode: JsonNode): BlueprintGrpcClientService { - val restClientProperties = grpcClientProperties(jsonNode) - return blueprintGrpcClientService(restClientProperties) - } - - fun blueprintGrpcClientService(selector: String): BlueprintGrpcClientService { - val prefix = "${GRPCLibConstants.PROPERTY_GRPC_CLIENT_PREFIX}$selector" - val restClientProperties = grpcClientProperties(prefix) - return blueprintGrpcClientService(restClientProperties) - } - - fun grpcClientProperties(jsonNode: JsonNode): GrpcClientProperties { - val type = jsonNode.get("type").returnNullIfMissing()?.textValue() - ?: BlueprintProcessorException("missing type property") - return when (type) { - GRPCLibConstants.TYPE_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, TokenAuthGrpcClientProperties::class.java)!! - } - GRPCLibConstants.TYPE_TLS_AUTH -> { - JacksonUtils.readValue(jsonNode, TLSAuthGrpcClientProperties::class.java)!! - } - GRPCLibConstants.TYPE_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, BasicAuthGrpcClientProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException("Grpc type($type) not supported") - } - } - } - - fun grpcClientProperties(prefix: String): GrpcClientProperties { - val type = bluePrintPropertiesService.propertyBeanType( - "$prefix.type", String::class.java - ) - return when (type) { - GRPCLibConstants.TYPE_TOKEN_AUTH -> { - tokenAuthGrpcClientProperties(prefix) - } - GRPCLibConstants.TYPE_TLS_AUTH -> { - tlsAuthGrpcClientProperties(prefix) - } - GRPCLibConstants.TYPE_BASIC_AUTH -> { - basicAuthGrpcClientProperties(prefix) - } - else -> { - throw BlueprintProcessorException("Grpc type($type) not supported") - } - } - } - - fun blueprintGrpcClientService(grpcClientProperties: GrpcClientProperties): - BlueprintGrpcClientService { - return when (grpcClientProperties) { - is TokenAuthGrpcClientProperties -> { - TokenAuthGrpcClientService(grpcClientProperties) - } - is TLSAuthGrpcClientProperties -> { - TLSAuthGrpcClientService(grpcClientProperties) - } - is BasicAuthGrpcClientProperties -> { - BasicAuthGrpcClientService(grpcClientProperties) - } - else -> { - throw BlueprintProcessorException("couldn't get grpc service for type(${grpcClientProperties.type})") - } - } - } - - private fun tokenAuthGrpcClientProperties(prefix: String): TokenAuthGrpcClientProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthGrpcClientProperties::class.java) - } - - private fun tlsAuthGrpcClientProperties(prefix: String): TLSAuthGrpcClientProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcClientProperties::class.java) - } - - private fun basicAuthGrpcClientProperties(prefix: String): BasicAuthGrpcClientProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, BasicAuthGrpcClientProperties::class.java) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcService.kt deleted file mode 100644 index a9485b3c3..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcService.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service - -import io.grpc.ManagedChannel -import io.grpc.netty.NettyServerBuilder - -interface BlueprintGrpcServerService { - - fun serverBuilder(): NettyServerBuilder -} - -interface BlueprintGrpcClientService { - - suspend fun channel(): ManagedChannel -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt index a2be05d4d..732f4fecf 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt @@ -23,11 +23,11 @@ import io.grpc.ServerCallHandler import org.onap.ccsdk.cds.blueprintsprocessor.grpc.getStringKey import org.onap.ccsdk.cds.blueprintsprocessor.grpc.putStringKeyValue import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_INVOCATION_ID -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_PARTNER_NAME -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_REQUEST_ID -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_INVOCATION_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_PARTNER_NAME +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_REQUEST_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.defaultToEmpty import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID import org.onap.ccsdk.cds.controllerblueprints.core.logger @@ -75,7 +75,7 @@ class GrpcLoggerService { val localhost = InetAddress.getLocalHost() val clientSocketAddress = call.attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) as? InetSocketAddress - ?: throw BlueprintProcessorException("failed to get client address") + ?: throw BluePrintProcessorException("failed to get client address") val serviceName = call.methodDescriptor.fullMethodName MDC.put("InvokeTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)) @@ -94,7 +94,7 @@ class GrpcLoggerService { fun grpcInvoking(requestHeader: Metadata) { requestHeader.putStringKeyValue(ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID()) requestHeader.putStringKeyValue(ONAP_INVOCATION_ID, UUID.randomUUID().toString()) - requestHeader.putStringKeyValue(ONAP_PARTNER_NAME, BlueprintConstants.APP_NAME) + requestHeader.putStringKeyValue(ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME) } /** Used when server returns response */ diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt index a8374d6e7..44df5fbe5 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt @@ -26,7 +26,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLogging import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthGrpcClientProperties) : - BlueprintGrpcClientService { + BluePrintGrpcClientService { override suspend fun channel(): ManagedChannel { diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt index c5f8df425..915ea1730 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt @@ -25,7 +25,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthGrpcServerProperties) : - BlueprintGrpcServerService { + BluePrintGrpcServerService { override fun serverBuilder(): NettyServerBuilder { return NettyServerBuilder diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt index b14e1d6ad..4c991df1f 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt @@ -30,7 +30,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLoggingInterceptor class TokenAuthGrpcClientService(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) : - BlueprintGrpcClientService { + BluePrintGrpcClientService { override suspend fun channel(): ManagedChannel { val target = diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSLTest.kt index 1e7000e37..3de857fa5 100644 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/GrpcPropertiesDSLTest.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import kotlin.test.assertEquals @@ -60,12 +60,12 @@ class GrpcPropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_SERVER}" ) } @@ -115,12 +115,12 @@ class GrpcPropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_GRPC_CLIENT}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt new file mode 100644 index 000000000..30722c8e3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt @@ -0,0 +1,218 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BluePrintGrpcLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintGrpcLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class + ] +) +@TestPropertySource( + properties = + [ + "blueprintsprocessor.grpcclient.sample.type=basic-auth", + "blueprintsprocessor.grpcclient.sample.host=127.0.0.1", + "blueprintsprocessor.grpcclient.sample.port=50505", + "blueprintsprocessor.grpcclient.sample.username=sampleuser", + "blueprintsprocessor.grpcclient.sample.password=sampleuser", + + "blueprintsprocessor.grpcclient.token.type=token-auth", + "blueprintsprocessor.grpcclient.token.host=127.0.0.1", + "blueprintsprocessor.grpcclient.token.port=50505", + "blueprintsprocessor.grpcclient.token.username=sampleuser", + "blueprintsprocessor.grpcclient.token.password=sampleuser", + + "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth", + "blueprintsprocessor.grpcserver.tls-sample.port=50505", + "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem", + "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key", + "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem", + + "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth", + "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1", + "blueprintsprocessor.grpcclient.tls-sample.port=50505", + "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem", + "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem", + "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key" + ] +) +class BluePrintGrpcLibPropertyServiceTest { + + @Autowired + lateinit var bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService + + /** + * Tests the GRPC client properties with selector for basic auth. + */ + @Test + fun testGrpcClientProperties() { + val properties = bluePrintGrpcLibPropertyService.grpcClientProperties( + "blueprintsprocessor.grpcclient.sample" + ) + as BasicAuthGrpcClientProperties + assertNotNull(properties, "failed to create property bean") + assertNotNull( + properties.host, "failed to get host property in property bean" + ) + assertNotNull( + properties.port, "failed to get host property in property bean" + ) + assertNotNull( + properties.username, "failed to get host property in property bean" + ) + assertNotNull( + properties.password, "failed to get host property in property bean" + ) + } + + /** + * Tests the GRPC client properties with JSON node for token auth. + */ + @Test + fun testGrpcClientPropertiesWithJson() { + val json: String = "{\n" + + " \"type\" : \"token-auth\",\n" + + " \"host\" : \"127.0.0.1\",\n" + + " \"port\" : \"50505\"\n" + + "}" + val mapper = ObjectMapper() + val actualObj: JsonNode = mapper.readTree(json) + val properties = bluePrintGrpcLibPropertyService.grpcClientProperties( + actualObj + ) as TokenAuthGrpcClientProperties + assertNotNull(properties, "failed to create property bean") + assertEquals(properties.host, "127.0.0.1") + assertNotNull(properties.port, "50505") + } + + /** + * Tests the GRPC client service with selector for basic auth. + */ + @Test + fun testGrpcClientServiceBasic() { + val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService( + "sample" + ) + assertTrue(svc is BasicAuthGrpcClientService) + } + + /** + * Tests the GRPC client service with selector for token auth. + */ + @Test + fun testGrpcClientServiceToken() { + val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService( + "token" + ) + assertTrue(svc is TokenAuthGrpcClientService) + } + + /** + * Tests the GRPC client service with JSON node for basic auth. + */ + @Test + fun testGrpcClientServiceWithJson() { + val json: String = "{\n" + + " \"type\" : \"basic-auth\",\n" + + " \"host\" : \"127.0.0.1\",\n" + + " \"port\" : \"50505\",\n" + + " \"username\" : \"sampleuser\",\n" + + " \"password\" : \"samplepwd\"\n" + + "}" + val mapper = ObjectMapper() + val actualObj: JsonNode = mapper.readTree(json) + val svc = bluePrintGrpcLibPropertyService + .blueprintGrpcClientService(actualObj) + assertTrue(svc is BasicAuthGrpcClientService) + } + + @Test + fun testGrpcClientTLSProperties() { + val properties = bluePrintGrpcLibPropertyService + .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties + assertNotNull(properties, "failed to create property bean") + assertNotNull(properties.host, "failed to get host property in property bean") + assertNotNull(properties.port, "failed to get host property in property bean") + assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean") + assertNotNull(properties.clientCertChain, "failed to get clientCertChain property in property bean") + assertNotNull(properties.clientPrivateKey, "failed to get clientPrivateKey property in property bean") + + val configDsl = """{ + "type" : "tls-auth", + "host" : "localhost", + "port" : "50505", + "trustCertCollection" : "server1.pem", + "clientCertChain" : "server1.key", + "clientPrivateKey" : "ca.pem" + } + """.trimIndent() + val jsonProperties = bluePrintGrpcLibPropertyService + .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties + assertNotNull(jsonProperties, "failed to create property bean from json") + } + + @Test + fun testGrpcServerTLSProperties() { + val properties = bluePrintGrpcLibPropertyService + .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties + assertNotNull(properties, "failed to create property bean") + assertNotNull(properties.port, "failed to get host property in property bean") + assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean") + assertNotNull(properties.certChain, "failed to get certChain property in property bean") + assertNotNull(properties.privateKey, "failed to get privateKey property in property bean") + + val configDsl = """{ + "type" : "tls-auth", + "port" : "50505", + "certChain" : "server1.pem", + "privateKey" : "server1.key", + "trustCertCollection" : "ca.pem" + } + """.trimIndent() + val jsonProperties = bluePrintGrpcLibPropertyService + .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties + assertNotNull(jsonProperties, "failed to create property bean from json") + + val grpcServerService = bluePrintGrpcLibPropertyService.blueprintGrpcServerService("tls-sample") + assertNotNull(grpcServerService, "failed to get grpc server service") + Assert.assertEquals(TLSAuthGrpcServerService::class.java, grpcServerService.javaClass) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt new file mode 100644 index 000000000..026fe5af5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt @@ -0,0 +1,110 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service + +import com.github.marcoferrer.krotoplus.coroutines.client.clientCallBidiStreaming +import com.google.protobuf.util.JsonFormat +import kotlinx.coroutines.channels.consumeEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import java.util.UUID +import kotlin.test.Test +import kotlin.test.assertNotNull + +class BluePrintGrpcServerTest { + + private val tlsAuthGrpcServerProperties = TLSAuthGrpcServerProperties().apply { + port = 50052 + type = GRPCLibConstants.TYPE_TLS_AUTH + certChain = "src/test/resources/tls-manual/py-executor-chain.pem" + privateKey = "src/test/resources/tls-manual/py-executor-key.pem" + } + + private val tlsAuthGrpcClientProperties = TLSAuthGrpcClientProperties().apply { + host = "localhost" + port = 50052 + type = GRPCLibConstants.TYPE_TLS_AUTH + trustCertCollection = "src/test/resources/tls-manual/py-executor-chain.pem" + } + + @Test + fun testGrpcTLSContext() { + val tlsAuthGrpcServerService = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties) + val sslContext = tlsAuthGrpcServerService.sslContext() + assertNotNull(sslContext, "failed to create grpc server ssl context") + + val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties) + val clientSslContext = tlsAuthGrpcClientService.sslContext() + assertNotNull(clientSslContext, "failed to create grpc client ssl context") + } + + /** TLS Client Integration testing, GRPC TLS Junit testing is not supported. */ + // @Test + fun testGrpcTLSServerIntegration() { + runBlocking { + val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties) + val grpcChannel = tlsAuthGrpcClientService.channel() + /** Get Send and Receive Channel for bidirectional process method*/ + val (reqChannel, resChannel) = clientCallBidiStreaming( + BluePrintProcessingServiceGrpc.getProcessMethod(), + grpcChannel + ) + launch { + resChannel.consumeEach { + log.info("Received Response") + if (it.status.eventType == EventType.EVENT_COMPONENT_EXECUTED) { + resChannel.cancel() + } + } + } + val request = getRequest("12345") + reqChannel.send(request) + } + } + + private fun getRequest(requestId: String): ExecutionServiceInput { + val commonHeader = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(requestId) + .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build() + val actionIdentifier = ActionIdentifiers.newBuilder() + .setActionName("SampleScript") + .setBlueprintName("sample-cba") + .setBlueprintVersion("1.0.0") + .setMode(ACTION_MODE_SYNC) + .build() + val jsonContent = """{ "key1" : "value1" }""" + val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder + JsonFormat.parser().merge(jsonContent, payloadBuilder) + + return ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers(actionIdentifier) + .setPayload(payloadBuilder.build()) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyServiceTest.kt deleted file mode 100644 index 40e245ade..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcLibPropertyServiceTest.kt +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BlueprintGrpcLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintGrpcLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class - ] -) -@TestPropertySource( - properties = - [ - "blueprintsprocessor.grpcclient.sample.type=basic-auth", - "blueprintsprocessor.grpcclient.sample.host=127.0.0.1", - "blueprintsprocessor.grpcclient.sample.port=50505", - "blueprintsprocessor.grpcclient.sample.username=sampleuser", - "blueprintsprocessor.grpcclient.sample.password=sampleuser", - - "blueprintsprocessor.grpcclient.token.type=token-auth", - "blueprintsprocessor.grpcclient.token.host=127.0.0.1", - "blueprintsprocessor.grpcclient.token.port=50505", - "blueprintsprocessor.grpcclient.token.username=sampleuser", - "blueprintsprocessor.grpcclient.token.password=sampleuser", - - "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth", - "blueprintsprocessor.grpcserver.tls-sample.port=50505", - "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem", - "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key", - "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem", - - "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth", - "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1", - "blueprintsprocessor.grpcclient.tls-sample.port=50505", - "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem", - "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem", - "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key" - ] -) -class BlueprintGrpcLibPropertyServiceTest { - - @Autowired - lateinit var bluePrintGrpcLibPropertyService: BlueprintGrpcLibPropertyService - - /** - * Tests the GRPC client properties with selector for basic auth. - */ - @Test - fun testGrpcClientProperties() { - val properties = bluePrintGrpcLibPropertyService.grpcClientProperties( - "blueprintsprocessor.grpcclient.sample" - ) - as BasicAuthGrpcClientProperties - assertNotNull(properties, "failed to create property bean") - assertNotNull( - properties.host, "failed to get host property in property bean" - ) - assertNotNull( - properties.port, "failed to get host property in property bean" - ) - assertNotNull( - properties.username, "failed to get host property in property bean" - ) - assertNotNull( - properties.password, "failed to get host property in property bean" - ) - } - - /** - * Tests the GRPC client properties with JSON node for token auth. - */ - @Test - fun testGrpcClientPropertiesWithJson() { - val json: String = "{\n" + - " \"type\" : \"token-auth\",\n" + - " \"host\" : \"127.0.0.1\",\n" + - " \"port\" : \"50505\"\n" + - "}" - val mapper = ObjectMapper() - val actualObj: JsonNode = mapper.readTree(json) - val properties = bluePrintGrpcLibPropertyService.grpcClientProperties( - actualObj - ) as TokenAuthGrpcClientProperties - assertNotNull(properties, "failed to create property bean") - assertEquals(properties.host, "127.0.0.1") - assertNotNull(properties.port, "50505") - } - - /** - * Tests the GRPC client service with selector for basic auth. - */ - @Test - fun testGrpcClientServiceBasic() { - val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService( - "sample" - ) - assertTrue(svc is BasicAuthGrpcClientService) - } - - /** - * Tests the GRPC client service with selector for token auth. - */ - @Test - fun testGrpcClientServiceToken() { - val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService( - "token" - ) - assertTrue(svc is TokenAuthGrpcClientService) - } - - /** - * Tests the GRPC client service with JSON node for basic auth. - */ - @Test - fun testGrpcClientServiceWithJson() { - val json: String = "{\n" + - " \"type\" : \"basic-auth\",\n" + - " \"host\" : \"127.0.0.1\",\n" + - " \"port\" : \"50505\",\n" + - " \"username\" : \"sampleuser\",\n" + - " \"password\" : \"samplepwd\"\n" + - "}" - val mapper = ObjectMapper() - val actualObj: JsonNode = mapper.readTree(json) - val svc = bluePrintGrpcLibPropertyService - .blueprintGrpcClientService(actualObj) - assertTrue(svc is BasicAuthGrpcClientService) - } - - @Test - fun testGrpcClientTLSProperties() { - val properties = bluePrintGrpcLibPropertyService - .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties - assertNotNull(properties, "failed to create property bean") - assertNotNull(properties.host, "failed to get host property in property bean") - assertNotNull(properties.port, "failed to get host property in property bean") - assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean") - assertNotNull(properties.clientCertChain, "failed to get clientCertChain property in property bean") - assertNotNull(properties.clientPrivateKey, "failed to get clientPrivateKey property in property bean") - - val configDsl = """{ - "type" : "tls-auth", - "host" : "localhost", - "port" : "50505", - "trustCertCollection" : "server1.pem", - "clientCertChain" : "server1.key", - "clientPrivateKey" : "ca.pem" - } - """.trimIndent() - val jsonProperties = bluePrintGrpcLibPropertyService - .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties - assertNotNull(jsonProperties, "failed to create property bean from json") - } - - @Test - fun testGrpcServerTLSProperties() { - val properties = bluePrintGrpcLibPropertyService - .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties - assertNotNull(properties, "failed to create property bean") - assertNotNull(properties.port, "failed to get host property in property bean") - assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean") - assertNotNull(properties.certChain, "failed to get certChain property in property bean") - assertNotNull(properties.privateKey, "failed to get privateKey property in property bean") - - val configDsl = """{ - "type" : "tls-auth", - "port" : "50505", - "certChain" : "server1.pem", - "privateKey" : "server1.key", - "trustCertCollection" : "ca.pem" - } - """.trimIndent() - val jsonProperties = bluePrintGrpcLibPropertyService - .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties - assertNotNull(jsonProperties, "failed to create property bean from json") - - val grpcServerService = bluePrintGrpcLibPropertyService.blueprintGrpcServerService("tls-sample") - assertNotNull(grpcServerService, "failed to get grpc server service") - Assert.assertEquals(TLSAuthGrpcServerService::class.java, grpcServerService.javaClass) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcServerTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcServerTest.kt deleted file mode 100644 index 130175e64..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BlueprintGrpcServerTest.kt +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service - -import com.github.marcoferrer.krotoplus.coroutines.client.clientCallBidiStreaming -import com.google.protobuf.util.JsonFormat -import kotlinx.coroutines.channels.consumeEach -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import java.util.UUID -import kotlin.test.Test -import kotlin.test.assertNotNull - -class BlueprintGrpcServerTest { - - private val tlsAuthGrpcServerProperties = TLSAuthGrpcServerProperties().apply { - port = 50052 - type = GRPCLibConstants.TYPE_TLS_AUTH - certChain = "src/test/resources/tls-manual/py-executor-chain.pem" - privateKey = "src/test/resources/tls-manual/py-executor-key.pem" - } - - private val tlsAuthGrpcClientProperties = TLSAuthGrpcClientProperties().apply { - host = "localhost" - port = 50052 - type = GRPCLibConstants.TYPE_TLS_AUTH - trustCertCollection = "src/test/resources/tls-manual/py-executor-chain.pem" - } - - @Test - fun testGrpcTLSContext() { - val tlsAuthGrpcServerService = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties) - val sslContext = tlsAuthGrpcServerService.sslContext() - assertNotNull(sslContext, "failed to create grpc server ssl context") - - val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties) - val clientSslContext = tlsAuthGrpcClientService.sslContext() - assertNotNull(clientSslContext, "failed to create grpc client ssl context") - } - - /** TLS Client Integration testing, GRPC TLS Junit testing is not supported. */ - // @Test - fun testGrpcTLSServerIntegration() { - runBlocking { - val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties) - val grpcChannel = tlsAuthGrpcClientService.channel() - /** Get Send and Receive Channel for bidirectional process method*/ - val (reqChannel, resChannel) = clientCallBidiStreaming( - BlueprintProcessingServiceGrpc.getProcessMethod(), - grpcChannel - ) - launch { - resChannel.consumeEach { - log.info("Received Response") - if (it.status.eventType == EventType.EVENT_COMPONENT_EXECUTED) { - resChannel.cancel() - } - } - } - val request = getRequest("12345") - reqChannel.send(request) - } - } - - private fun getRequest(requestId: String): ExecutionServiceInput { - val commonHeader = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(requestId) - .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build() - val actionIdentifier = ActionIdentifiers.newBuilder() - .setActionName("SampleScript") - .setBlueprintName("sample-cba") - .setBlueprintVersion("1.0.0") - .setMode(ACTION_MODE_SYNC) - .build() - val jsonContent = """{ "key1" : "value1" }""" - val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder - JsonFormat.parser().merge(jsonContent, payloadBuilder) - - return ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers(actionIdentifier) - .setPayload(payloadBuilder.build()) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt new file mode 100644 index 000000000..78fa27d3a --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service + +import io.grpc.stub.StreamObserver +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcServerLoggingInterceptor +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput + +val log = logger(MockTLSBluePrintProcessingServer::class) + +/** For Integration testing stat this server, Set the working path to run this method */ +fun main() { + try { + val tlsAuthGrpcServerProperties = TLSAuthGrpcServerProperties().apply { + port = 50052 + type = GRPCLibConstants.TYPE_TLS_AUTH + certChain = "src/test/resources/tls-manual/py-executor-chain.pem" + privateKey = "src/test/resources/tls-manual/py-executor-key.pem" + } + val server = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties).serverBuilder() + .intercept(GrpcServerLoggingInterceptor()) + .addService(MockTLSBluePrintProcessingServer()) + .build() + server.start() + log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...") + server.awaitTermination() + } catch (e: Exception) { + log.error("Failed to start tls grpc integration server", e) + } +} + +class MockTLSBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { + + override fun process(responseObserver: StreamObserver): StreamObserver { + + return object : StreamObserver { + override fun onNext(executionServiceInput: ExecutionServiceInput) { + log.info( + "Received requestId(${executionServiceInput.commonHeader.requestId}) " + + "subRequestId(${executionServiceInput.commonHeader.subRequestId})" + ) + responseObserver.onNext(buildResponse(executionServiceInput)) + responseObserver.onCompleted() + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + responseObserver.onError( + io.grpc.Status.INTERNAL + .withDescription(error.message) + .asException() + ) + } + + override fun onCompleted() { + log.info("Completed") + } + } + } + + private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput { + val status = Status.newBuilder().setCode(200) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .build() + return ExecutionServiceOutput.newBuilder() + .setCommonHeader(input.commonHeader) + .setActionIdentifiers(input.actionIdentifiers) + .setStatus(status) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBlueprintProcessingServer.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBlueprintProcessingServer.kt deleted file mode 100644 index 5426d7327..000000000 --- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBlueprintProcessingServer.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service - -import io.grpc.stub.StreamObserver -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcServerLoggingInterceptor -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput - -val log = logger(MockTLSBlueprintProcessingServer::class) - -/** For Integration testing stat this server, Set the working path to run this method */ -fun main() { - try { - val tlsAuthGrpcServerProperties = TLSAuthGrpcServerProperties().apply { - port = 50052 - type = GRPCLibConstants.TYPE_TLS_AUTH - certChain = "src/test/resources/tls-manual/py-executor-chain.pem" - privateKey = "src/test/resources/tls-manual/py-executor-key.pem" - } - val server = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties).serverBuilder() - .intercept(GrpcServerLoggingInterceptor()) - .addService(MockTLSBlueprintProcessingServer()) - .build() - server.start() - log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...") - server.awaitTermination() - } catch (e: Exception) { - log.error("Failed to start tls grpc integration server", e) - } -} - -class MockTLSBlueprintProcessingServer : BlueprintProcessingServiceGrpc.BlueprintProcessingServiceImplBase() { - - override fun process(responseObserver: StreamObserver): StreamObserver { - - return object : StreamObserver { - override fun onNext(executionServiceInput: ExecutionServiceInput) { - log.info( - "Received requestId(${executionServiceInput.commonHeader.requestId}) " + - "subRequestId(${executionServiceInput.commonHeader.subRequestId})" - ) - responseObserver.onNext(buildResponse(executionServiceInput)) - responseObserver.onCompleted() - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - responseObserver.onError( - io.grpc.Status.INTERNAL - .withDescription(error.message) - .asException() - ) - } - - override fun onCompleted() { - log.info("Completed") - } - } - } - - private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput { - val status = Status.newBuilder().setCode(200) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .build() - return ExecutionServiceOutput.newBuilder() - .setCommonHeader(input.commonHeader) - .setActionIdentifiers(input.actionIdentifiers) - .setStatus(status) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt new file mode 100644 index 000000000..509689eca --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt @@ -0,0 +1,31 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.message + +import org.apache.kafka.common.header.Headers +import org.apache.kafka.common.header.internals.RecordHeader +import java.nio.charset.Charset + +fun T?.toMap(): MutableMap { + val map: MutableMap = hashMapOf() + this?.forEach { map[it.key()] = String(it.value(), Charset.defaultCharset()) } + return map +} + +fun Headers.addHeader(key: String, value: String) { + this.add(RecordHeader(key, value.toByteArray())) +} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt new file mode 100644 index 000000000..659295a6b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt @@ -0,0 +1,71 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.message + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageProducerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintMessageLibConfiguration + +/** + * Exposed Dependency Service by this Message Lib Module + */ +fun BluePrintDependencyService.messageLibPropertyService(): BluePrintMessageLibPropertyService = + instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY) + +/** Extension functions for message producer service **/ +fun BluePrintDependencyService.messageProducerService(selector: String): BlueprintMessageProducerService { + return messageLibPropertyService().blueprintMessageProducerService(selector) +} + +fun BluePrintDependencyService.messageProducerService(jsonNode: JsonNode): BlueprintMessageProducerService { + return messageLibPropertyService().blueprintMessageProducerService(jsonNode) +} + +/** Extension functions for message consumer service **/ +fun BluePrintDependencyService.messageConsumerService(selector: String): BlueprintMessageConsumerService { + return messageLibPropertyService().blueprintMessageConsumerService(selector) +} + +fun BluePrintDependencyService.messageConsumerService(jsonNode: JsonNode): BlueprintMessageConsumerService { + return messageLibPropertyService().blueprintMessageConsumerService(jsonNode) +} + +class MessageLibConstants { + companion object { + + const val SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY = "blueprint-message-lib-property-service" + const val PROPERTY_MESSAGE_CONSUMER_PREFIX = "blueprintsprocessor.messageconsumer." + const val PROPERTY_MESSAGE_PRODUCER_PREFIX = "blueprintsprocessor.messageproducer." + const val TYPE_KAFKA_BASIC_AUTH = "kafka-basic-auth" + const val TYPE_KAFKA_SCRAM_SSL_AUTH = "kafka-scram-ssl-auth" + const val TYPE_KAFKA_SSL_AUTH = "kafka-ssl-auth" + const val TYPE_KAFKA_STREAMS_BASIC_AUTH = "kafka-streams-basic-auth" + const val TYPE_KAFKA_STREAMS_SSL_AUTH = "kafka-streams-ssl-auth" + const val TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH = "kafka-streams-scram-ssl-auth" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt new file mode 100644 index 000000000..67dba1f19 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt @@ -0,0 +1,264 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.message + +import org.apache.kafka.clients.CommonClientConfigs +import org.apache.kafka.clients.consumer.ConsumerConfig +import org.apache.kafka.clients.producer.ProducerConfig +import org.apache.kafka.common.config.SaslConfigs +import org.apache.kafka.common.config.SslConfigs +import org.apache.kafka.common.security.auth.SecurityProtocol +import org.apache.kafka.common.security.scram.ScramLoginModule +import org.apache.kafka.common.serialization.ByteArrayDeserializer +import org.apache.kafka.common.serialization.ByteArraySerializer +import org.apache.kafka.common.serialization.StringDeserializer +import org.apache.kafka.common.serialization.StringSerializer +import org.apache.kafka.streams.StreamsConfig + +/** Common Properties **/ +abstract class CommonProperties { + + lateinit var type: String + lateinit var topic: String + lateinit var bootstrapServers: String + + open fun getConfig(): HashMap { + val configProps = hashMapOf() + configProps[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers + return configProps + } +} + +/** Message Producer */ +/** Message Producer Properties **/ +abstract class MessageProducerProperties : CommonProperties() + +/** Basic Auth */ +open class KafkaBasicAuthMessageProducerProperties : MessageProducerProperties() { + + var clientId: String? = null + var acks: String = "all" // strongest producing guarantee + var maxBlockMs: Int = 250 // max blocking time in ms to send a message + var reconnectBackOffMs: Int = 60 * 60 * 1000 // time in ms before retrying connection (1 hour) + var enableIdempotence: Boolean = true // ensure we don't push duplicates + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java + configProps[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = ByteArraySerializer::class.java + configProps[ProducerConfig.ACKS_CONFIG] = acks + configProps[ProducerConfig.MAX_BLOCK_MS_CONFIG] = maxBlockMs + configProps[ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG] = reconnectBackOffMs + configProps[ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG] = enableIdempotence + if (clientId != null) { + configProps[ProducerConfig.CLIENT_ID_CONFIG] = clientId!! + } + return configProps + } +} + +/** SSL Auth */ +open class KafkaSslAuthMessageProducerProperties : KafkaBasicAuthMessageProducerProperties() { + + lateinit var truststore: String + lateinit var truststorePassword: String + var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE + var keystore: String? = null + var keystorePassword: String? = null + var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE + var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() + configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType + configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! + configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! + if (keystore != null) { + configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! + configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType + configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! + } + configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm + + return configProps + } +} + +/** (SASL) SCRAM SSL Auth */ +class KafkaScramSslAuthMessageProducerProperties : KafkaSslAuthMessageProducerProperties() { + + var saslMechanism: String = "SCRAM-SHA-512" + lateinit var scramUsername: String + lateinit var scramPassword: String + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() + configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism + configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + + "username=\"${scramUsername}\" " + + "password=\"${scramPassword}\";" + return configProps + } +} + +/** Consumer */ +abstract class MessageConsumerProperties : CommonProperties() +/** Kafka Streams */ +/** Streams properties */ + +/** Basic Auth */ +open class KafkaStreamsBasicAuthConsumerProperties : MessageConsumerProperties() { + + lateinit var applicationId: String + var autoOffsetReset: String = "latest" + var processingGuarantee: String = StreamsConfig.EXACTLY_ONCE + + override fun getConfig(): HashMap { + val configProperties = super.getConfig() + configProperties[StreamsConfig.APPLICATION_ID_CONFIG] = applicationId + configProperties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = autoOffsetReset + configProperties[StreamsConfig.PROCESSING_GUARANTEE_CONFIG] = processingGuarantee + return configProperties + } +} + +/** SSL Auth */ +open class KafkaStreamsSslAuthConsumerProperties : KafkaStreamsBasicAuthConsumerProperties() { + + lateinit var truststore: String + lateinit var truststorePassword: String + var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE + var keystore: String? = null + var keystorePassword: String? = null + var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE + var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() + configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType + configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! + configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! + if (keystore != null) { + configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! + configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType + configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! + } + configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm + return configProps + } +} + +/** (SASL) SCRAM SSL Auth */ +class KafkaStreamsScramSslAuthConsumerProperties : KafkaStreamsSslAuthConsumerProperties() { + + var saslMechanism: String = "SCRAM-SHA-512" + lateinit var scramUsername: String + lateinit var scramPassword: String + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() + configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism + configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + + "username=\"${scramUsername}\" " + + "password=\"${scramPassword}\";" + return configProps + } +} + +/** Message Consumer */ +/** Message Consumer Properties **/ +/** Basic Auth */ +open class KafkaBasicAuthMessageConsumerProperties : MessageConsumerProperties() { + + lateinit var groupId: String + lateinit var clientId: String + var autoCommit: Boolean = true + var autoOffsetReset: String = "latest" + var pollMillSec: Long = 1000 + var pollRecords: Int = -1 + + override fun getConfig(): HashMap { + val configProperties = super.getConfig() + configProperties[ConsumerConfig.GROUP_ID_CONFIG] = groupId + configProperties[ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG] = autoCommit + /** + * earliest: automatically reset the offset to the earliest offset + * latest: automatically reset the offset to the latest offset + */ + configProperties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = autoOffsetReset + configProperties[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java + configProperties[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = ByteArrayDeserializer::class.java + configProperties[ConsumerConfig.CLIENT_ID_CONFIG] = clientId + + /** To handle Back pressure, Get only configured record for processing */ + if (pollRecords > 0) { + configProperties[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = pollRecords + } + + return configProperties + } +} + +/** SSL Auth */ +open class KafkaSslAuthMessageConsumerProperties : KafkaBasicAuthMessageConsumerProperties() { + + lateinit var truststore: String + lateinit var truststorePassword: String + var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE + var keystore: String? = null + var keystorePassword: String? = null + var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE + var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() + configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType + configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! + configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! + if (keystore != null) { + configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! + configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType + configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! + } + configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm + return configProps + } +} + +/** (SASL) SCRAM SSL Auth */ +class KafkaScramSslAuthMessageConsumerProperties : KafkaSslAuthMessageConsumerProperties() { + + var saslMechanism: String = "SCRAM-SHA-512" + lateinit var scramUsername: String + lateinit var scramPassword: String + + override fun getConfig(): HashMap { + val configProps = super.getConfig() + configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() + configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism + configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + + "username=\"${scramUsername}\" " + + "password=\"${scramPassword}\";" + return configProps + } +} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageExtensions.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageExtensions.kt deleted file mode 100644 index 509689eca..000000000 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageExtensions.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.message - -import org.apache.kafka.common.header.Headers -import org.apache.kafka.common.header.internals.RecordHeader -import java.nio.charset.Charset - -fun T?.toMap(): MutableMap { - val map: MutableMap = hashMapOf() - this?.forEach { map[it.key()] = String(it.value(), Charset.defaultCharset()) } - return map -} - -fun Headers.addHeader(key: String, value: String) { - this.add(RecordHeader(key, value.toByteArray())) -} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibConfiguration.kt deleted file mode 100644 index 88931d13f..000000000 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibConfiguration.kt +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.message - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageProducerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BlueprintMessageLibConfiguration - -/** - * Exposed Dependency Service by this Message Lib Module - */ -fun BlueprintDependencyService.messageLibPropertyService(): BlueprintMessageLibPropertyService = - instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY) - -/** Extension functions for message producer service **/ -fun BlueprintDependencyService.messageProducerService(selector: String): BlueprintMessageProducerService { - return messageLibPropertyService().blueprintMessageProducerService(selector) -} - -fun BlueprintDependencyService.messageProducerService(jsonNode: JsonNode): BlueprintMessageProducerService { - return messageLibPropertyService().blueprintMessageProducerService(jsonNode) -} - -/** Extension functions for message consumer service **/ -fun BlueprintDependencyService.messageConsumerService(selector: String): BlueprintMessageConsumerService { - return messageLibPropertyService().blueprintMessageConsumerService(selector) -} - -fun BlueprintDependencyService.messageConsumerService(jsonNode: JsonNode): BlueprintMessageConsumerService { - return messageLibPropertyService().blueprintMessageConsumerService(jsonNode) -} - -class MessageLibConstants { - companion object { - - const val SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY = "blueprint-message-lib-property-service" - const val PROPERTY_MESSAGE_CONSUMER_PREFIX = "blueprintsprocessor.messageconsumer." - const val PROPERTY_MESSAGE_PRODUCER_PREFIX = "blueprintsprocessor.messageproducer." - const val TYPE_KAFKA_BASIC_AUTH = "kafka-basic-auth" - const val TYPE_KAFKA_SCRAM_SSL_AUTH = "kafka-scram-ssl-auth" - const val TYPE_KAFKA_SSL_AUTH = "kafka-ssl-auth" - const val TYPE_KAFKA_STREAMS_BASIC_AUTH = "kafka-streams-basic-auth" - const val TYPE_KAFKA_STREAMS_SSL_AUTH = "kafka-streams-ssl-auth" - const val TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH = "kafka-streams-scram-ssl-auth" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibData.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibData.kt deleted file mode 100644 index 67dba1f19..000000000 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BlueprintMessageLibData.kt +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.message - -import org.apache.kafka.clients.CommonClientConfigs -import org.apache.kafka.clients.consumer.ConsumerConfig -import org.apache.kafka.clients.producer.ProducerConfig -import org.apache.kafka.common.config.SaslConfigs -import org.apache.kafka.common.config.SslConfigs -import org.apache.kafka.common.security.auth.SecurityProtocol -import org.apache.kafka.common.security.scram.ScramLoginModule -import org.apache.kafka.common.serialization.ByteArrayDeserializer -import org.apache.kafka.common.serialization.ByteArraySerializer -import org.apache.kafka.common.serialization.StringDeserializer -import org.apache.kafka.common.serialization.StringSerializer -import org.apache.kafka.streams.StreamsConfig - -/** Common Properties **/ -abstract class CommonProperties { - - lateinit var type: String - lateinit var topic: String - lateinit var bootstrapServers: String - - open fun getConfig(): HashMap { - val configProps = hashMapOf() - configProps[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers - return configProps - } -} - -/** Message Producer */ -/** Message Producer Properties **/ -abstract class MessageProducerProperties : CommonProperties() - -/** Basic Auth */ -open class KafkaBasicAuthMessageProducerProperties : MessageProducerProperties() { - - var clientId: String? = null - var acks: String = "all" // strongest producing guarantee - var maxBlockMs: Int = 250 // max blocking time in ms to send a message - var reconnectBackOffMs: Int = 60 * 60 * 1000 // time in ms before retrying connection (1 hour) - var enableIdempotence: Boolean = true // ensure we don't push duplicates - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java - configProps[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = ByteArraySerializer::class.java - configProps[ProducerConfig.ACKS_CONFIG] = acks - configProps[ProducerConfig.MAX_BLOCK_MS_CONFIG] = maxBlockMs - configProps[ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG] = reconnectBackOffMs - configProps[ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG] = enableIdempotence - if (clientId != null) { - configProps[ProducerConfig.CLIENT_ID_CONFIG] = clientId!! - } - return configProps - } -} - -/** SSL Auth */ -open class KafkaSslAuthMessageProducerProperties : KafkaBasicAuthMessageProducerProperties() { - - lateinit var truststore: String - lateinit var truststorePassword: String - var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE - var keystore: String? = null - var keystorePassword: String? = null - var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE - var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() - configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType - configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! - configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! - if (keystore != null) { - configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! - configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType - configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! - } - configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm - - return configProps - } -} - -/** (SASL) SCRAM SSL Auth */ -class KafkaScramSslAuthMessageProducerProperties : KafkaSslAuthMessageProducerProperties() { - - var saslMechanism: String = "SCRAM-SHA-512" - lateinit var scramUsername: String - lateinit var scramPassword: String - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() - configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism - configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + - "username=\"${scramUsername}\" " + - "password=\"${scramPassword}\";" - return configProps - } -} - -/** Consumer */ -abstract class MessageConsumerProperties : CommonProperties() -/** Kafka Streams */ -/** Streams properties */ - -/** Basic Auth */ -open class KafkaStreamsBasicAuthConsumerProperties : MessageConsumerProperties() { - - lateinit var applicationId: String - var autoOffsetReset: String = "latest" - var processingGuarantee: String = StreamsConfig.EXACTLY_ONCE - - override fun getConfig(): HashMap { - val configProperties = super.getConfig() - configProperties[StreamsConfig.APPLICATION_ID_CONFIG] = applicationId - configProperties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = autoOffsetReset - configProperties[StreamsConfig.PROCESSING_GUARANTEE_CONFIG] = processingGuarantee - return configProperties - } -} - -/** SSL Auth */ -open class KafkaStreamsSslAuthConsumerProperties : KafkaStreamsBasicAuthConsumerProperties() { - - lateinit var truststore: String - lateinit var truststorePassword: String - var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE - var keystore: String? = null - var keystorePassword: String? = null - var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE - var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() - configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType - configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! - configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! - if (keystore != null) { - configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! - configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType - configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! - } - configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm - return configProps - } -} - -/** (SASL) SCRAM SSL Auth */ -class KafkaStreamsScramSslAuthConsumerProperties : KafkaStreamsSslAuthConsumerProperties() { - - var saslMechanism: String = "SCRAM-SHA-512" - lateinit var scramUsername: String - lateinit var scramPassword: String - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() - configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism - configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + - "username=\"${scramUsername}\" " + - "password=\"${scramPassword}\";" - return configProps - } -} - -/** Message Consumer */ -/** Message Consumer Properties **/ -/** Basic Auth */ -open class KafkaBasicAuthMessageConsumerProperties : MessageConsumerProperties() { - - lateinit var groupId: String - lateinit var clientId: String - var autoCommit: Boolean = true - var autoOffsetReset: String = "latest" - var pollMillSec: Long = 1000 - var pollRecords: Int = -1 - - override fun getConfig(): HashMap { - val configProperties = super.getConfig() - configProperties[ConsumerConfig.GROUP_ID_CONFIG] = groupId - configProperties[ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG] = autoCommit - /** - * earliest: automatically reset the offset to the earliest offset - * latest: automatically reset the offset to the latest offset - */ - configProperties[ConsumerConfig.AUTO_OFFSET_RESET_CONFIG] = autoOffsetReset - configProperties[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java - configProperties[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = ByteArrayDeserializer::class.java - configProperties[ConsumerConfig.CLIENT_ID_CONFIG] = clientId - - /** To handle Back pressure, Get only configured record for processing */ - if (pollRecords > 0) { - configProperties[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = pollRecords - } - - return configProperties - } -} - -/** SSL Auth */ -open class KafkaSslAuthMessageConsumerProperties : KafkaBasicAuthMessageConsumerProperties() { - - lateinit var truststore: String - lateinit var truststorePassword: String - var truststoreType: String = SslConfigs.DEFAULT_SSL_TRUSTSTORE_TYPE - var keystore: String? = null - var keystorePassword: String? = null - var keystoreType: String = SslConfigs.DEFAULT_SSL_KEYSTORE_TYPE - var sslEndpointIdentificationAlgorithm: String = SslConfigs.DEFAULT_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SSL.toString() - configProps[SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG] = truststoreType - configProps[SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG] = truststore!! - configProps[SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG] = truststorePassword!! - if (keystore != null) { - configProps[SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG] = keystore!! - configProps[SslConfigs.SSL_KEYSTORE_TYPE_CONFIG] = keystoreType - configProps[SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG] = keystorePassword!! - } - configProps[SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG] = sslEndpointIdentificationAlgorithm - return configProps - } -} - -/** (SASL) SCRAM SSL Auth */ -class KafkaScramSslAuthMessageConsumerProperties : KafkaSslAuthMessageConsumerProperties() { - - var saslMechanism: String = "SCRAM-SHA-512" - lateinit var scramUsername: String - lateinit var scramPassword: String - - override fun getConfig(): HashMap { - val configProps = super.getConfig() - configProps[CommonClientConfigs.SECURITY_PROTOCOL_CONFIG] = SecurityProtocol.SASL_SSL.toString() - configProps[SaslConfigs.SASL_MECHANISM] = saslMechanism - configProps[SaslConfigs.SASL_JAAS_CONFIG] = "${ScramLoginModule::class.java.canonicalName} required " + - "username=\"${scramUsername}\" " + - "password=\"${scramPassword}\";" - return configProps - } -} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSL.kt index 527374f02..8b31de9b9 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -30,48 +30,48 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Types DSL for Message Producer */ fun ServiceTemplateBuilder.relationshipTypeConnectsToMessageProducer() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToMessageProducer() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToMessageProducer() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToMessageProducer(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToMessageProducer(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through message producer." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } fun ServiceTemplateBuilder.relationshipTypeConnectsToMessageConsumer() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToMessageConsumer() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToMessageConsumer() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToMessageConsumer(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToMessageConsumer(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship type connects to message consumer." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -90,46 +90,46 @@ fun TopologyTemplateBuilder.relationshipTemplateMessageProducer( class MessageProducerRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER, description ) { fun kafkaBasicAuth(block: KafkaBasicAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaBasicAuthMessageProducerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaBasicAuthMessageProducerProperties(block) ) } fun kafkaSslAuth(block: KafkaSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaSslAuthMessageProducerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaSslAuthMessageProducerProperties(block) ) } fun kafkaScramSslAuth(block: KafkaScramSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaScramSslAuthMessageProducerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaScramSslAuthMessageProducerProperties(block) ) } } -fun BlueprintTypes.kafkaBasicAuthMessageProducerProperties(block: KafkaBasicAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaBasicAuthMessageProducerProperties(block: KafkaBasicAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaBasicAuthMessageProducerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaBasicAuthMessageProducerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_BASIC_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaSslAuthMessageProducerProperties(block: KafkaSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaSslAuthMessageProducerProperties(block: KafkaSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaSslAuthMessageProducerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaSslAuthMessageProducerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_SSL_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaScramSslAuthMessageProducerProperties(block: KafkaScramSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaScramSslAuthMessageProducerProperties(block: KafkaScramSslAuthMessageProducerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaScramSslAuthMessageProducerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaScramSslAuthMessageProducerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH.asJsonPrimitive() @@ -245,88 +245,88 @@ fun TopologyTemplateBuilder.relationshipTemplateMessageConsumer( class MessageConsumerRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER, description ) { fun kafkaBasicAuth(block: KafkaBasicAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaBasicAuthMessageConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaBasicAuthMessageConsumerProperties(block) ) } fun kafkaSslAuth(block: KafkaSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaSslAuthMessageConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaSslAuthMessageConsumerProperties(block) ) } fun kafkaScramSslAuth(block: KafkaScramSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaScramSslAuthMessageConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaScramSslAuthMessageConsumerProperties(block) ) } fun kafkaStreamsBasicAuth(block: KafkaStreamsBasicAuthConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaStreamsBasicAuthConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaStreamsBasicAuthConsumerProperties(block) ) } fun kafkaStreamsSslAuth(block: KafkaStreamsSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaStreamsSslAuthConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaStreamsSslAuthConsumerProperties(block) ) } fun kafkaStreamsScramSslAuth(block: KafkaStreamsScramSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintTypes.kafkaStreamsScramSslAuthConsumerProperties(block) + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintTypes.kafkaStreamsScramSslAuthConsumerProperties(block) ) } } -fun BlueprintTypes.kafkaBasicAuthMessageConsumerProperties(block: KafkaBasicAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaBasicAuthMessageConsumerProperties(block: KafkaBasicAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaBasicAuthMessageConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaBasicAuthMessageConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_BASIC_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaSslAuthMessageConsumerProperties(block: KafkaSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaSslAuthMessageConsumerProperties(block: KafkaSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaSslAuthMessageConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaSslAuthMessageConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_SSL_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaScramSslAuthMessageConsumerProperties(block: KafkaScramSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaScramSslAuthMessageConsumerProperties(block: KafkaScramSslAuthMessageConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaScramSslAuthMessageConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaScramSslAuthMessageConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaStreamsBasicAuthConsumerProperties(block: KafkaStreamsBasicAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaStreamsBasicAuthConsumerProperties(block: KafkaStreamsBasicAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaStreamsBasicAuthConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaStreamsBasicAuthConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaStreamsSslAuthConsumerProperties(block: KafkaStreamsSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaStreamsSslAuthConsumerProperties(block: KafkaStreamsSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaStreamsSslAuthConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaStreamsSslAuthConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.kafkaStreamsScramSslAuthConsumerProperties(block: KafkaStreamsScramSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.kafkaStreamsScramSslAuthConsumerProperties(block: KafkaStreamsScramSslAuthConsumerPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = KafkaStreamsScramSslAuthConsumerPropertiesAssignmentBuilder().apply(block).build() assignments[KafkaStreamsScramSslAuthConsumerProperties::type.name] = MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH.asJsonPrimitive() diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt index 23eca18a3..72a70893a 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt @@ -24,9 +24,9 @@ import org.apache.kafka.streams.processor.Punctuator import org.onap.ccsdk.cds.controllerblueprints.core.logger /** CDS Kafka Stream Processor abstract class to implement */ -abstract class AbstractBlueprintMessageProcessor : Processor { +abstract class AbstractBluePrintMessageProcessor : Processor { - private val log = logger(AbstractBlueprintMessageProcessor::class) + private val log = logger(AbstractBluePrintMessageProcessor::class) lateinit var processorContext: ProcessorContext @@ -51,7 +51,7 @@ abstract class AbstractBlueprintMessageProcessor : Processor { } /** CDS Kafka Stream Punctuator abstract class to implement */ -abstract class AbstractBlueprintMessagePunctuator : Punctuator { +abstract class AbstractBluePrintMessagePunctuator : Punctuator { lateinit var processorContext: ProcessorContext diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/KafkaJDBCStores.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/KafkaJDBCStores.kt index ecf5870ab..86ccd74a2 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/KafkaJDBCStores.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/KafkaJDBCStores.kt @@ -21,10 +21,10 @@ import org.apache.kafka.streams.processor.ProcessorContext import org.apache.kafka.streams.processor.StateStore import org.apache.kafka.streams.state.StoreBuilder import org.apache.kafka.streams.state.StoreSupplier -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService import org.onap.ccsdk.cds.blueprintsprocessor.db.primaryDBLibGenericService import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import java.util.* @@ -32,7 +32,7 @@ class KafkaJDBCKeyStoreSupplier(private val name: String) : StoreSupplier { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaBasicAuthMessageProducerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaSslAuthMessageProducerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaScramSslAuthMessageProducerProperties::class.java + ) + } + else -> { + throw BluePrintProcessorException("Message adaptor($type) is not supported") + } + } + } + + fun messageProducerProperties(jsonNode: JsonNode): MessageProducerProperties { + val type = jsonNode.get("type").textValue() + return when (type) { + MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaBasicAuthMessageProducerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaSslAuthMessageProducerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaScramSslAuthMessageProducerProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Message adaptor($type) is not supported") + } + } + } + + /** Consumer Property Lib Service Implementation **/ + + /** Return Message Consumer Service for [jsonNode] definitions. */ + fun blueprintMessageConsumerService(jsonNode: JsonNode): BlueprintMessageConsumerService { + val messageConsumerProperties = messageConsumerProperties(jsonNode) + return blueprintMessageConsumerService(messageConsumerProperties) + } + + /** Return Message Consumer Service for [selector] definitions. */ + fun blueprintMessageConsumerService(selector: String): BlueprintMessageConsumerService { + val prefix = "${MessageLibConstants.PROPERTY_MESSAGE_CONSUMER_PREFIX}$selector" + val messageClientProperties = messageConsumerProperties(prefix) + return blueprintMessageConsumerService(messageClientProperties) + } + + /** Return Message Consumer Properties for [prefix] definitions. */ + fun messageConsumerProperties(prefix: String): MessageConsumerProperties { + val type = bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java) + return when (type) { + /** Message Consumer */ + MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaBasicAuthMessageConsumerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaSslAuthMessageConsumerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaScramSslAuthMessageConsumerProperties::class.java + ) + } + /** Stream Consumer */ + MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaStreamsBasicAuthConsumerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaStreamsSslAuthConsumerProperties::class.java + ) + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { + bluePrintPropertiesService.propertyBeanType( + prefix, KafkaStreamsScramSslAuthConsumerProperties::class.java + ) + } + else -> { + throw BluePrintProcessorException("Message adaptor($type) is not supported") + } + } + } + + fun messageConsumerProperties(jsonNode: JsonNode): MessageConsumerProperties { + val type = jsonNode.get("type").textValue() + return when (type) { + /** Message Consumer */ + MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaBasicAuthMessageConsumerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaSslAuthMessageConsumerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaScramSslAuthMessageConsumerProperties::class.java)!! + } + /** Stream Consumer */ + MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaStreamsBasicAuthConsumerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaStreamsSslAuthConsumerProperties::class.java)!! + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { + JacksonUtils.readValue(jsonNode, KafkaStreamsScramSslAuthConsumerProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Message adaptor($type) is not supported") + } + } + } + + private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties): + BlueprintMessageConsumerService { + + when (messageConsumerProperties.type) { + /** Message Consumer */ + MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { + return KafkaMessageConsumerService( + messageConsumerProperties as KafkaBasicAuthMessageConsumerProperties, + meterRegistry + ) + } + MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { + return KafkaMessageConsumerService( + messageConsumerProperties as KafkaSslAuthMessageConsumerProperties, + meterRegistry + ) + } + MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { + return KafkaMessageConsumerService( + messageConsumerProperties as KafkaScramSslAuthMessageConsumerProperties, + meterRegistry + ) + } + /** Stream Consumer */ + MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { + return KafkaStreamsConsumerService( + messageConsumerProperties as KafkaStreamsBasicAuthConsumerProperties + ) + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { + return KafkaStreamsConsumerService( + messageConsumerProperties as KafkaStreamsSslAuthConsumerProperties + ) + } + MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { + return KafkaStreamsConsumerService( + messageConsumerProperties as KafkaStreamsScramSslAuthConsumerProperties + ) + } + else -> { + throw BluePrintProcessorException("couldn't get message client service for ${messageConsumerProperties.type}") + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt index 887a7a7b8..b39d89bfd 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt @@ -23,7 +23,7 @@ import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.clients.consumer.ConsumerRecords import org.apache.kafka.streams.Topology import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException /** Consumer Function Interfaces */ interface ConsumerFunction @@ -47,7 +47,7 @@ interface BlueprintMessageConsumerService { /** Consume with [additionalConfig], so that we can execute dynamic function [consumerFunction] */ suspend fun consume(additionalConfig: Map?, consumerFunction: ConsumerFunction) { - throw BlueprintProcessorException("Not Implemented") + throw BluePrintProcessorException("Not Implemented") } /** Consume the [topics] with [additionalConfig], so that we can execute dynamic function [consumerFunction] */ @@ -56,7 +56,7 @@ interface BlueprintMessageConsumerService { additionalConfig: Map?, consumerFunction: ConsumerFunction ) { - throw BlueprintProcessorException("Not Implemented") + throw BluePrintProcessorException("Not Implemented") } /** close the channel, consumer and other resources */ diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageLibPropertyService.kt deleted file mode 100644 index cb0bc3225..000000000 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageLibPropertyService.kt +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2018-2021 AT&T, Bell Canada Intellectual Property - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.message.service - -import com.fasterxml.jackson.databind.JsonNode -import io.micrometer.core.instrument.MeterRegistry -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageProducerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaScramSslAuthMessageConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaScramSslAuthMessageProducerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaSslAuthMessageConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaSslAuthMessageProducerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsScramSslAuthConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsSslAuthConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties -import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageProducerProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY) -open class BlueprintMessageLibPropertyService( - private var bluePrintPropertiesService: BlueprintPropertiesService, - private val meterRegistry: MeterRegistry -) { - - fun blueprintMessageProducerService(jsonNode: JsonNode): BlueprintMessageProducerService { - val messageClientProperties = messageProducerProperties(jsonNode) - return KafkaMessageProducerService(messageClientProperties, meterRegistry) - } - - fun blueprintMessageProducerService(selector: String): BlueprintMessageProducerService { - val prefix = "${MessageLibConstants.PROPERTY_MESSAGE_PRODUCER_PREFIX}$selector" - val messageClientProperties = messageProducerProperties(prefix) - return KafkaMessageProducerService(messageClientProperties, meterRegistry) - } - - fun messageProducerProperties(prefix: String): MessageProducerProperties { - val type = bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaBasicAuthMessageProducerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaSslAuthMessageProducerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaScramSslAuthMessageProducerProperties::class.java - ) - } - else -> { - throw BlueprintProcessorException("Message adaptor($type) is not supported") - } - } - } - - fun messageProducerProperties(jsonNode: JsonNode): MessageProducerProperties { - val type = jsonNode.get("type").textValue() - return when (type) { - MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaBasicAuthMessageProducerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaSslAuthMessageProducerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaScramSslAuthMessageProducerProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException("Message adaptor($type) is not supported") - } - } - } - - /** Consumer Property Lib Service Implementation **/ - - /** Return Message Consumer Service for [jsonNode] definitions. */ - fun blueprintMessageConsumerService(jsonNode: JsonNode): BlueprintMessageConsumerService { - val messageConsumerProperties = messageConsumerProperties(jsonNode) - return blueprintMessageConsumerService(messageConsumerProperties) - } - - /** Return Message Consumer Service for [selector] definitions. */ - fun blueprintMessageConsumerService(selector: String): BlueprintMessageConsumerService { - val prefix = "${MessageLibConstants.PROPERTY_MESSAGE_CONSUMER_PREFIX}$selector" - val messageClientProperties = messageConsumerProperties(prefix) - return blueprintMessageConsumerService(messageClientProperties) - } - - /** Return Message Consumer Properties for [prefix] definitions. */ - fun messageConsumerProperties(prefix: String): MessageConsumerProperties { - val type = bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - /** Message Consumer */ - MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaBasicAuthMessageConsumerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaSslAuthMessageConsumerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaScramSslAuthMessageConsumerProperties::class.java - ) - } - /** Stream Consumer */ - MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaStreamsBasicAuthConsumerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaStreamsSslAuthConsumerProperties::class.java - ) - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { - bluePrintPropertiesService.propertyBeanType( - prefix, KafkaStreamsScramSslAuthConsumerProperties::class.java - ) - } - else -> { - throw BlueprintProcessorException("Message adaptor($type) is not supported") - } - } - } - - fun messageConsumerProperties(jsonNode: JsonNode): MessageConsumerProperties { - val type = jsonNode.get("type").textValue() - return when (type) { - /** Message Consumer */ - MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaBasicAuthMessageConsumerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaSslAuthMessageConsumerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaScramSslAuthMessageConsumerProperties::class.java)!! - } - /** Stream Consumer */ - MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaStreamsBasicAuthConsumerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaStreamsSslAuthConsumerProperties::class.java)!! - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { - JacksonUtils.readValue(jsonNode, KafkaStreamsScramSslAuthConsumerProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException("Message adaptor($type) is not supported") - } - } - } - - private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties): - BlueprintMessageConsumerService { - - when (messageConsumerProperties.type) { - /** Message Consumer */ - MessageLibConstants.TYPE_KAFKA_BASIC_AUTH -> { - return KafkaMessageConsumerService( - messageConsumerProperties as KafkaBasicAuthMessageConsumerProperties, - meterRegistry - ) - } - MessageLibConstants.TYPE_KAFKA_SSL_AUTH -> { - return KafkaMessageConsumerService( - messageConsumerProperties as KafkaSslAuthMessageConsumerProperties, - meterRegistry - ) - } - MessageLibConstants.TYPE_KAFKA_SCRAM_SSL_AUTH -> { - return KafkaMessageConsumerService( - messageConsumerProperties as KafkaScramSslAuthMessageConsumerProperties, - meterRegistry - ) - } - /** Stream Consumer */ - MessageLibConstants.TYPE_KAFKA_STREAMS_BASIC_AUTH -> { - return KafkaStreamsConsumerService( - messageConsumerProperties as KafkaStreamsBasicAuthConsumerProperties - ) - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SSL_AUTH -> { - return KafkaStreamsConsumerService( - messageConsumerProperties as KafkaStreamsSslAuthConsumerProperties - ) - } - MessageLibConstants.TYPE_KAFKA_STREAMS_SCRAM_SSL_AUTH -> { - return KafkaStreamsConsumerService( - messageConsumerProperties as KafkaStreamsScramSslAuthConsumerProperties - ) - } - else -> { - throw BlueprintProcessorException("couldn't get message client service for ${messageConsumerProperties.type}") - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerService.kt index beaa995df..4340e4815 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerService.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerService.kt @@ -20,7 +20,7 @@ import kotlinx.coroutines.channels.Channel import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.streams.KafkaStreams import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger import java.util.Properties @@ -41,11 +41,11 @@ open class KafkaStreamsConsumerService(private val messageConsumerProperties: Me } override suspend fun subscribe(additionalConfig: Map?): Channel> { - throw BlueprintProcessorException("not implemented") + throw BluePrintProcessorException("not implemented") } override suspend fun subscribe(topics: List, additionalConfig: Map?): Channel> { - throw BlueprintProcessorException("not implemented") + throw BluePrintProcessorException("not implemented") } override suspend fun consume(additionalConfig: Map?, consumerFunction: ConsumerFunction) { diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt index 7e5f35d15..90b850017 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt @@ -21,7 +21,7 @@ import org.apache.kafka.common.header.Headers import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader import org.onap.ccsdk.cds.blueprintsprocessor.message.addHeader import org.onap.ccsdk.cds.blueprintsprocessor.message.toMap -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.defaultToEmpty import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID import org.onap.ccsdk.cds.controllerblueprints.core.logger @@ -46,9 +46,9 @@ class MessageLoggerService { fun messageConsuming(consumerRecord: ConsumerRecord<*, *>) { val headers = consumerRecord.headers().toMap() - val requestID = headers[BlueprintConstants.ONAP_REQUEST_ID].defaultToUUID() - val invocationID = headers[BlueprintConstants.ONAP_INVOCATION_ID].defaultToUUID() - val partnerName = headers[BlueprintConstants.ONAP_PARTNER_NAME] ?: "UNKNOWN" + val requestID = headers[BluePrintConstants.ONAP_REQUEST_ID].defaultToUUID() + val invocationID = headers[BluePrintConstants.ONAP_INVOCATION_ID].defaultToUUID() + val partnerName = headers[BluePrintConstants.ONAP_PARTNER_NAME] ?: "UNKNOWN" messageConsuming(requestID, invocationID, partnerName, consumerRecord) } @@ -83,9 +83,9 @@ class MessageLoggerService { */ fun messageProducing(requestHeader: Headers) { val localhost = InetAddress.getLocalHost() - requestHeader.addHeader(BlueprintConstants.ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID()) - requestHeader.addHeader(BlueprintConstants.ONAP_INVOCATION_ID, UUID.randomUUID().toString()) - requestHeader.addHeader(BlueprintConstants.ONAP_PARTNER_NAME, BlueprintConstants.APP_NAME) + requestHeader.addHeader(BluePrintConstants.ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID()) + requestHeader.addHeader(BluePrintConstants.ONAP_INVOCATION_ID, UUID.randomUUID().toString()) + requestHeader.addHeader(BluePrintConstants.ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME) requestHeader.addHeader("ClientIPAddress", localhost.hostAddress) } diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtils.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtils.kt index 7431998d9..795d386f3 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtils.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtils.kt @@ -17,13 +17,13 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message.utils import io.micrometer.core.instrument.Tag -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants class BlueprintMessageUtils { companion object { fun kafkaMetricTag(topic: String): MutableList = mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_TOPIC, topic) + Tag.of(BluePrintConstants.METRIC_TAG_TOPIC, topic) ) } } diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSLTest.kt index 8130016a8..b68678baf 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/MessagePropertiesDSLTest.kt @@ -18,7 +18,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message import org.apache.kafka.streams.StreamsConfig import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import kotlin.test.assertEquals @@ -67,12 +67,12 @@ class MessagePropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_PRODUCER}" ) } @@ -138,12 +138,12 @@ class MessagePropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_MESSAGE_CONSUMER}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt index fb53ff45b..aa9171d2c 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt @@ -41,9 +41,9 @@ import org.apache.kafka.common.serialization.ByteArrayDeserializer import org.apache.kafka.common.serialization.StringDeserializer import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.BluePrintMessageLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageLibConstants import org.onap.ccsdk.cds.controllerblueprints.core.logger @@ -62,8 +62,8 @@ import kotlin.test.assertTrue @DirtiesContext @ContextConfiguration( classes = [ - BlueprintMessageLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintMessageLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -100,7 +100,7 @@ open class BlueprintMessageConsumerServiceTest { val log = logger(BlueprintMessageConsumerServiceTest::class) @Autowired - lateinit var bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService + lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService @MockBean lateinit var meterRegistry: MeterRegistry diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt index 1490a3311..54601cec4 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt @@ -34,9 +34,9 @@ import org.apache.kafka.common.security.scram.ScramLoginModule import org.apache.kafka.common.serialization.ByteArraySerializer import org.apache.kafka.common.serialization.StringSerializer import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.BluePrintMessageLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageLibConstants import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean @@ -53,8 +53,8 @@ import kotlin.test.assertTrue @DirtiesContext @ContextConfiguration( classes = [ - BlueprintMessageLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintMessageLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -75,7 +75,7 @@ import kotlin.test.assertTrue open class BlueprintMessageProducerServiceTest { @Autowired - lateinit var bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService + lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService @MockBean lateinit var meterRegistry: MeterRegistry @@ -93,11 +93,11 @@ open class BlueprintMessageProducerServiceTest { every { mockKafkaTemplate.send(any(), any()) } returns responseMock - val spyBlueprintMessageProducerService = spyk(blueprintMessageProducerService, recordPrivateCalls = true) + val spyBluePrintMessageProducerService = spyk(blueprintMessageProducerService, recordPrivateCalls = true) - every { spyBlueprintMessageProducerService.messageTemplate(any()) } returns mockKafkaTemplate + every { spyBluePrintMessageProducerService.messageTemplate(any()) } returns mockKafkaTemplate - val response = spyBlueprintMessageProducerService.sendMessage("mykey", "Testing message") + val response = spyBluePrintMessageProducerService.sendMessage("mykey", "Testing message") assertTrue(response, "failed to get command response") } } diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerServiceTest.kt index b93cd42d4..657cf64ff 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsConsumerServiceTest.kt @@ -28,9 +28,9 @@ import org.apache.kafka.streams.processor.ProcessorSupplier import org.apache.kafka.streams.state.Stores import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.BluePrintMessageLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties import org.springframework.beans.factory.annotation.Autowired @@ -45,8 +45,8 @@ import kotlin.test.assertNotNull @DirtiesContext @ContextConfiguration( classes = [ - BlueprintMessageLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintMessageLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -75,7 +75,7 @@ import kotlin.test.assertNotNull class KafkaStreamsConsumerServiceTest { @Autowired - lateinit var bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService + lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService @MockBean lateinit var meterRegistry: MeterRegistry diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt index dc36ac675..3dce3344f 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt @@ -23,7 +23,7 @@ import org.apache.kafka.common.header.internals.RecordHeaders import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader import org.onap.ccsdk.cds.blueprintsprocessor.message.toMap -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.slf4j.MDC import kotlin.test.assertEquals @@ -51,7 +51,7 @@ class MessageLoggerServiceTest { val mockHeaders = RecordHeaders() messageLoggerService.messageProducing(mockHeaders) val map = mockHeaders.toMap() - assertEquals("1234-12", map[BlueprintConstants.ONAP_REQUEST_ID]) + assertEquals("1234-12", map[BluePrintConstants.ONAP_REQUEST_ID]) messageLoggerService.messageConsumingExisting() } diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt index 97a81f1cd..aa38b6e5c 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt @@ -22,7 +22,7 @@ import org.apache.kafka.common.serialization.Serializer import org.apache.kafka.streams.processor.Processor import org.apache.kafka.streams.processor.ProcessorContext import org.apache.kafka.streams.state.KeyValueStore -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -48,7 +48,7 @@ open class PriorityMessageSerde : Serde { return object : Deserializer { override fun deserialize(topic: String, data: ByteArray): PriorityMessage { return JacksonUtils.readValue(String(data), PriorityMessage::class.java) - ?: throw BlueprintProcessorException("failed to convert") + ?: throw BluePrintProcessorException("failed to convert") } override fun configure(configs: MutableMap?, isKey: Boolean) { diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtilsTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtilsTest.kt index 849a411a6..09c338702 100644 --- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtilsTest.kt +++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/utils/BlueprintMessageUtilsTest.kt @@ -18,7 +18,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message.utils import io.micrometer.core.instrument.Tag import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import kotlin.test.assertEquals class BlueprintMessageUtilsTest { @@ -26,7 +26,7 @@ class BlueprintMessageUtilsTest { @Test fun testKafkaMetricTag() { val expected = mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_TOPIC, "my-topic") + Tag.of(BluePrintConstants.METRIC_TAG_TOPIC, "my-topic") ) val tags = BlueprintMessageUtils.kafkaMetricTag("my-topic") diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsExtensions.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsExtensions.kt new file mode 100644 index 000000000..a585c972b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsExtensions.kt @@ -0,0 +1,36 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType + +fun io.nats.client.Message.strData(): String { + return String(this.data) +} + +fun io.nats.streaming.Message.strData(): String { + return String(this.data) +} + +fun io.nats.client.Message.asJsonType(): JsonNode { + return this.data.asJsonType() +} + +fun io.nats.streaming.Message.asJsonType(): JsonNode { + return this.data.asJsonType() +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibConfiguration.kt new file mode 100644 index 000000000..a47dd8918 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibConfiguration.kt @@ -0,0 +1,49 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats + +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BluePrintNatsService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +open class BluePrintNatsLibConfiguration + +/** + * Exposed Dependency Service by this NATS Lib Module + */ +fun BluePrintDependencyService.natsLibPropertyService(): BluePrintNatsLibPropertyService = + instance(NatsLibConstants.SERVICE_BLUEPRINT_NATS_LIB_PROPERTY) + +fun BluePrintDependencyService.controllerNatsService(): BluePrintNatsService { + return natsLibPropertyService().bluePrintNatsService(NatsLibConstants.DEFULT_NATS_SELECTOR) +} + +class NatsLibConstants { + companion object { + + const val SERVICE_BLUEPRINT_NATS_LIB_PROPERTY = "blueprint-nats-lib-property-service" + const val DEFULT_NATS_SELECTOR = "cds-controller" + const val PROPERTY_NATS_PREFIX = "blueprintsprocessor.nats." + const val PROPERTY_NATS_CLUSTER_ID = "NATS_CLUSTER_ID" + const val TYPE_TOKEN_AUTH = "token-auth" + const val TYPE_TLS_AUTH = "tls-auth" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibData.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibData.kt new file mode 100644 index 000000000..a989dcf1e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BluePrintNatsLibData.kt @@ -0,0 +1,45 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats + +import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.NatsClusterUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils + +open class NatsConnectionProperties { + + lateinit var type: String + var clusterId: String = NatsClusterUtils.clusterId() + var clientId: String = ClusterUtils.clusterNodeId() + lateinit var host: String + + /** Rest endpoint selector to access Monitoring API */ + var monitoringSelector: String? = null +} + +open class TokenAuthNatsConnectionProperties : NatsConnectionProperties() { + + lateinit var token: String +} + +open class TLSAuthNatsConnectionProperties : NatsConnectionProperties() { + + var trustCertCollection: String? = null + + /** Below Used only for Mutual TLS */ + var clientCertChain: String? = null + var clientPrivateKey: String? = null +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsExtensions.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsExtensions.kt deleted file mode 100644 index a585c972b..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsExtensions.kt +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType - -fun io.nats.client.Message.strData(): String { - return String(this.data) -} - -fun io.nats.streaming.Message.strData(): String { - return String(this.data) -} - -fun io.nats.client.Message.asJsonType(): JsonNode { - return this.data.asJsonType() -} - -fun io.nats.streaming.Message.asJsonType(): JsonNode { - return this.data.asJsonType() -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibConfiguration.kt deleted file mode 100644 index c83906c3f..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibConfiguration.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats - -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.nats.service.BlueprintNatsService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -open class BlueprintNatsLibConfiguration - -/** - * Exposed Dependency Service by this NATS Lib Module - */ -fun BlueprintDependencyService.natsLibPropertyService(): BlueprintNatsLibPropertyService = - instance(NatsLibConstants.SERVICE_BLUEPRINT_NATS_LIB_PROPERTY) - -fun BlueprintDependencyService.controllerNatsService(): BlueprintNatsService { - return natsLibPropertyService().bluePrintNatsService(NatsLibConstants.DEFULT_NATS_SELECTOR) -} - -class NatsLibConstants { - companion object { - - const val SERVICE_BLUEPRINT_NATS_LIB_PROPERTY = "blueprint-nats-lib-property-service" - const val DEFULT_NATS_SELECTOR = "cds-controller" - const val PROPERTY_NATS_PREFIX = "blueprintsprocessor.nats." - const val PROPERTY_NATS_CLUSTER_ID = "NATS_CLUSTER_ID" - const val TYPE_TOKEN_AUTH = "token-auth" - const val TYPE_TLS_AUTH = "tls-auth" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibData.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibData.kt deleted file mode 100644 index a989dcf1e..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/BlueprintNatsLibData.kt +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats - -import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.NatsClusterUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils - -open class NatsConnectionProperties { - - lateinit var type: String - var clusterId: String = NatsClusterUtils.clusterId() - var clientId: String = ClusterUtils.clusterNodeId() - lateinit var host: String - - /** Rest endpoint selector to access Monitoring API */ - var monitoringSelector: String? = null -} - -open class TokenAuthNatsConnectionProperties : NatsConnectionProperties() { - - lateinit var token: String -} - -open class TLSAuthNatsConnectionProperties : NatsConnectionProperties() { - - var trustCertCollection: String? = null - - /** Below Used only for Mutual TLS */ - var clientCertChain: String? = null - var clientPrivateKey: String? = null -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSL.kt index 9e771a6e5..4c5471796 100644 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.nats import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -30,25 +30,25 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Types DSL for NATS Producer */ fun ServiceTemplateBuilder.relationshipTypeConnectsToNats() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToNats() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToNats() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToNats(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToNats(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through NATS Client." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -66,25 +66,25 @@ fun TopologyTemplateBuilder.relationshipTemplateNats( class NatsRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS, description ) { fun tokenAuth(block: NatsTokenAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tokenAuthNatsProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tokenAuthNatsProperties(block)) } fun tlsAuth(block: NatsTLSAuthPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tlsAuthNatsProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tlsAuthNatsProperties(block)) } } -fun BlueprintTypes.tokenAuthNatsProperties(block: NatsTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tokenAuthNatsProperties(block: NatsTokenAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = NatsTokenAuthPropertiesAssignmentBuilder().apply(block).build() assignments[NatsConnectionProperties::type.name] = NatsLibConstants.TYPE_TOKEN_AUTH.asJsonPrimitive() return assignments.asJsonNode() } -fun BlueprintTypes.tlsAuthNatsProperties(block: NatsTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tlsAuthNatsProperties(block: NatsTLSAuthPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = NatsTLSAuthPropertiesAssignmentBuilder().apply(block).build() assignments[NatsConnectionProperties::type.name] = NatsLibConstants.TYPE_TLS_AUTH.asJsonPrimitive() return assignments.asJsonNode() diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyService.kt new file mode 100644 index 000000000..1ac44bc94 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyService.kt @@ -0,0 +1,95 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsConnectionProperties +import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.nats.TLSAuthNatsConnectionProperties +import org.onap.ccsdk.cds.blueprintsprocessor.nats.TokenAuthNatsConnectionProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service(NatsLibConstants.SERVICE_BLUEPRINT_NATS_LIB_PROPERTY) +open class BluePrintNatsLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + fun bluePrintNatsService(jsonNode: JsonNode): BluePrintNatsService { + val natsConnectionProperties = natsConnectionProperties(jsonNode) + return bluePrintNatsService(natsConnectionProperties) + } + + fun bluePrintNatsService(selector: String): BluePrintNatsService { + val prefix = "${NatsLibConstants.PROPERTY_NATS_PREFIX}$selector" + val natsConnectionProperties = natsConnectionProperties(prefix) + return bluePrintNatsService(natsConnectionProperties) + } + + /** NATS Lib Property Service */ + fun natsConnectionProperties(jsonNode: JsonNode): NatsConnectionProperties { + return when (val type = jsonNode.get("type").textValue()) { + NatsLibConstants.TYPE_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, TokenAuthNatsConnectionProperties::class.java)!! + } + NatsLibConstants.TYPE_TLS_AUTH -> { + JacksonUtils.readValue(jsonNode, TLSAuthNatsConnectionProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("NATS type($type) not supported") + } + } + } + + fun natsConnectionProperties(prefix: String): NatsConnectionProperties { + val type = bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java) + return when (type) { + NatsLibConstants.TYPE_TOKEN_AUTH -> { + tokenAuthNatsConnectionProperties(prefix) + } + NatsLibConstants.TYPE_TLS_AUTH -> { + tlsAuthNatsConnectionProperties(prefix) + } + else -> { + throw BluePrintProcessorException("NATS type($type) not supported") + } + } + } + + private fun tokenAuthNatsConnectionProperties(prefix: String): TokenAuthNatsConnectionProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthNatsConnectionProperties::class.java) + } + + private fun tlsAuthNatsConnectionProperties(prefix: String): TLSAuthNatsConnectionProperties { + return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthNatsConnectionProperties::class.java) + } + + fun bluePrintNatsService(natsConnectionProperties: NatsConnectionProperties): + BluePrintNatsService { + return when (natsConnectionProperties) { + is TokenAuthNatsConnectionProperties -> { + TokenAuthNatsService(natsConnectionProperties) + } + is TLSAuthNatsConnectionProperties -> { + TLSAuthNatsService(natsConnectionProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get NATS service for properties $natsConnectionProperties") + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsService.kt new file mode 100644 index 000000000..9548fe78d --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsService.kt @@ -0,0 +1,143 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:Suppress("BlockingMethodInNonBlockingContext") + +package org.onap.ccsdk.cds.blueprintsprocessor.nats.service + +import io.nats.client.Dispatcher +import io.nats.streaming.MessageHandler +import io.nats.streaming.StreamingConnection +import io.nats.streaming.Subscription +import io.nats.streaming.SubscriptionOptions +import java.time.Duration + +interface BluePrintNatsService { + + /** Create and Return the NATS streaming connection */ + suspend fun connection(): StreamingConnection + + /** Send one request [message] to the [subject] and get only one reply + * The request message subscriber may be multi instances consumer or load balance consumer. + * If it is multi instances consumer, then we will get only first responses from subscribers. + * + */ + suspend fun requestAndGetOneReply(subject: String, message: ByteArray, timeout: Long): io.nats.client.Message { + return connection().natsConnection.request(subject, message, Duration.ofMillis(timeout)) + } + + /** Send one request [message] to the [subject] and get multiple replies in [replySubject] with [messageHandler] + * The request message subscriber may be multi instances consumer or load balance consumer. + * If it is multi instances consumer, then we will get multiple responses from subscribers. + * Include the unSubscribe logic's in [messageHandler] implementation. + */ + suspend fun requestAndGetMultipleReplies( + subject: String, + replySubject: String, + message: ByteArray, + messageHandler: io.nats.client.MessageHandler + ) { + val natsConnection = connection().natsConnection + val dispatcher = natsConnection.createDispatcher(messageHandler) + /** Reply subject consumer */ + dispatcher.subscribe(replySubject) + + /** Publish the request message and expect the reply messages in reply subject consumer */ + natsConnection.publish(subject, replySubject, message) + } + + /** Synchronous reply Subscribe the [subject] with the [messageHandler]. + * This is used only the message has to be consumed by all instances in the cluster and message handler must reply. + */ + suspend fun replySubscribe( + subject: String, + messageHandler: io.nats.client.MessageHandler + ): Dispatcher { + val natsConnection = connection().natsConnection + val dispatcher = natsConnection.createDispatcher(messageHandler) + return dispatcher.subscribe(subject) + } + + /** + * Synchronous reply Subscriber will listen for [subject] with [loadBalanceGroup]. + * This is used only the message has to be consumed by only one instance in the cluster. + * server will now load balance messages between the members of the queue group and message handler must reply. + */ + suspend fun loadBalanceReplySubscribe( + subject: String, + loadBalanceGroup: String, + messageHandler: io.nats.client.MessageHandler + ): Dispatcher { + val natsConnection = connection().natsConnection + val dispatcher = natsConnection.createDispatcher(messageHandler) + return dispatcher.subscribe(subject, loadBalanceGroup) + } + + /** Publish the [message] to all subscribers on the [subject] */ + suspend fun publish(subject: String, message: ByteArray) { + connection().publish(subject, message) + } + + /** Subscribe the [subject] with the [messageHandler]. + * This is used only the message has to be consumed by all instances in the cluster. + */ + suspend fun subscribe( + subject: String, + messageHandler: MessageHandler + ): Subscription { + return connection().subscribe(subject, messageHandler) + } + + /** Subscribe the [subject] with the [messageHandler] and [subscriptionOptions]. + * This is used only the message has to be consumed by all instances in the cluster. + */ + suspend fun subscribe( + subject: String, + messageHandler: MessageHandler, + subscriptionOptions: SubscriptionOptions + ): Subscription { + return connection().subscribe(subject, messageHandler, subscriptionOptions) + } + + /** + * https://docs.nats.io/developing-with-nats/receiving/queues + * subscribers will listen for [subject] with [loadBalanceGroup]. + * This is used only the message has to be consumed by only one instance in the cluster. + * server will now load balance messages between the members of the queue group. + */ + suspend fun loadBalanceSubscribe( + subject: String, + loadBalanceGroup: String, + messageHandler: MessageHandler + ): Subscription { + return connection().subscribe(subject, loadBalanceGroup, messageHandler) + } + + /** + * https://docs.nats.io/developing-with-nats/receiving/queues + * subscribers will listen for [subject] with [loadBalanceGroup] and [subscriptionOptions]. + * This is used only the message has to be consumed by only one instance in the cluster. + * server will now load balance messages between the members of the queue group. + */ + suspend fun loadBalanceSubscribe( + subject: String, + loadBalanceGroup: String, + messageHandler: MessageHandler, + subscriptionOptions: SubscriptionOptions + ): Subscription { + return connection().subscribe(subject, loadBalanceGroup, messageHandler, subscriptionOptions) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyService.kt deleted file mode 100644 index 457bf8703..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyService.kt +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsConnectionProperties -import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.nats.TLSAuthNatsConnectionProperties -import org.onap.ccsdk.cds.blueprintsprocessor.nats.TokenAuthNatsConnectionProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(NatsLibConstants.SERVICE_BLUEPRINT_NATS_LIB_PROPERTY) -open class BlueprintNatsLibPropertyService(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - fun bluePrintNatsService(jsonNode: JsonNode): BlueprintNatsService { - val natsConnectionProperties = natsConnectionProperties(jsonNode) - return bluePrintNatsService(natsConnectionProperties) - } - - fun bluePrintNatsService(selector: String): BlueprintNatsService { - val prefix = "${NatsLibConstants.PROPERTY_NATS_PREFIX}$selector" - val natsConnectionProperties = natsConnectionProperties(prefix) - return bluePrintNatsService(natsConnectionProperties) - } - - /** NATS Lib Property Service */ - fun natsConnectionProperties(jsonNode: JsonNode): NatsConnectionProperties { - return when (val type = jsonNode.get("type").textValue()) { - NatsLibConstants.TYPE_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, TokenAuthNatsConnectionProperties::class.java)!! - } - NatsLibConstants.TYPE_TLS_AUTH -> { - JacksonUtils.readValue(jsonNode, TLSAuthNatsConnectionProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException("NATS type($type) not supported") - } - } - } - - fun natsConnectionProperties(prefix: String): NatsConnectionProperties { - val type = bluePrintPropertiesService.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - NatsLibConstants.TYPE_TOKEN_AUTH -> { - tokenAuthNatsConnectionProperties(prefix) - } - NatsLibConstants.TYPE_TLS_AUTH -> { - tlsAuthNatsConnectionProperties(prefix) - } - else -> { - throw BlueprintProcessorException("NATS type($type) not supported") - } - } - } - - private fun tokenAuthNatsConnectionProperties(prefix: String): TokenAuthNatsConnectionProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TokenAuthNatsConnectionProperties::class.java) - } - - private fun tlsAuthNatsConnectionProperties(prefix: String): TLSAuthNatsConnectionProperties { - return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthNatsConnectionProperties::class.java) - } - - fun bluePrintNatsService(natsConnectionProperties: NatsConnectionProperties): - BlueprintNatsService { - return when (natsConnectionProperties) { - is TokenAuthNatsConnectionProperties -> { - TokenAuthNatsService(natsConnectionProperties) - } - is TLSAuthNatsConnectionProperties -> { - TLSAuthNatsService(natsConnectionProperties) - } - else -> { - throw BlueprintProcessorException("couldn't get NATS service for properties $natsConnectionProperties") - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsService.kt deleted file mode 100644 index 67de95133..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsService.kt +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@file:Suppress("BlockingMethodInNonBlockingContext") - -package org.onap.ccsdk.cds.blueprintsprocessor.nats.service - -import io.nats.client.Dispatcher -import io.nats.streaming.MessageHandler -import io.nats.streaming.StreamingConnection -import io.nats.streaming.Subscription -import io.nats.streaming.SubscriptionOptions -import java.time.Duration - -interface BlueprintNatsService { - - /** Create and Return the NATS streaming connection */ - suspend fun connection(): StreamingConnection - - /** Send one request [message] to the [subject] and get only one reply - * The request message subscriber may be multi instances consumer or load balance consumer. - * If it is multi instances consumer, then we will get only first responses from subscribers. - * - */ - suspend fun requestAndGetOneReply(subject: String, message: ByteArray, timeout: Long): io.nats.client.Message { - return connection().natsConnection.request(subject, message, Duration.ofMillis(timeout)) - } - - /** Send one request [message] to the [subject] and get multiple replies in [replySubject] with [messageHandler] - * The request message subscriber may be multi instances consumer or load balance consumer. - * If it is multi instances consumer, then we will get multiple responses from subscribers. - * Include the unSubscribe logic's in [messageHandler] implementation. - */ - suspend fun requestAndGetMultipleReplies( - subject: String, - replySubject: String, - message: ByteArray, - messageHandler: io.nats.client.MessageHandler - ) { - val natsConnection = connection().natsConnection - val dispatcher = natsConnection.createDispatcher(messageHandler) - /** Reply subject consumer */ - dispatcher.subscribe(replySubject) - - /** Publish the request message and expect the reply messages in reply subject consumer */ - natsConnection.publish(subject, replySubject, message) - } - - /** Synchronous reply Subscribe the [subject] with the [messageHandler]. - * This is used only the message has to be consumed by all instances in the cluster and message handler must reply. - */ - suspend fun replySubscribe( - subject: String, - messageHandler: io.nats.client.MessageHandler - ): Dispatcher { - val natsConnection = connection().natsConnection - val dispatcher = natsConnection.createDispatcher(messageHandler) - return dispatcher.subscribe(subject) - } - - /** - * Synchronous reply Subscriber will listen for [subject] with [loadBalanceGroup]. - * This is used only the message has to be consumed by only one instance in the cluster. - * server will now load balance messages between the members of the queue group and message handler must reply. - */ - suspend fun loadBalanceReplySubscribe( - subject: String, - loadBalanceGroup: String, - messageHandler: io.nats.client.MessageHandler - ): Dispatcher { - val natsConnection = connection().natsConnection - val dispatcher = natsConnection.createDispatcher(messageHandler) - return dispatcher.subscribe(subject, loadBalanceGroup) - } - - /** Publish the [message] to all subscribers on the [subject] */ - suspend fun publish(subject: String, message: ByteArray) { - connection().publish(subject, message) - } - - /** Subscribe the [subject] with the [messageHandler]. - * This is used only the message has to be consumed by all instances in the cluster. - */ - suspend fun subscribe( - subject: String, - messageHandler: MessageHandler - ): Subscription { - return connection().subscribe(subject, messageHandler) - } - - /** Subscribe the [subject] with the [messageHandler] and [subscriptionOptions]. - * This is used only the message has to be consumed by all instances in the cluster. - */ - suspend fun subscribe( - subject: String, - messageHandler: MessageHandler, - subscriptionOptions: SubscriptionOptions - ): Subscription { - return connection().subscribe(subject, messageHandler, subscriptionOptions) - } - - /** - * https://docs.nats.io/developing-with-nats/receiving/queues - * subscribers will listen for [subject] with [loadBalanceGroup]. - * This is used only the message has to be consumed by only one instance in the cluster. - * server will now load balance messages between the members of the queue group. - */ - suspend fun loadBalanceSubscribe( - subject: String, - loadBalanceGroup: String, - messageHandler: MessageHandler - ): Subscription { - return connection().subscribe(subject, loadBalanceGroup, messageHandler) - } - - /** - * https://docs.nats.io/developing-with-nats/receiving/queues - * subscribers will listen for [subject] with [loadBalanceGroup] and [subscriptionOptions]. - * This is used only the message has to be consumed by only one instance in the cluster. - * server will now load balance messages between the members of the queue group. - */ - suspend fun loadBalanceSubscribe( - subject: String, - loadBalanceGroup: String, - messageHandler: MessageHandler, - subscriptionOptions: SubscriptionOptions - ): Subscription { - return connection().subscribe(subject, loadBalanceGroup, messageHandler, subscriptionOptions) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TLSAuthNatsService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TLSAuthNatsService.kt index 1bde8e534..00a972eff 100644 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TLSAuthNatsService.kt +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TLSAuthNatsService.kt @@ -25,7 +25,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.splitCommaAsList import javax.net.ssl.SSLContext open class TLSAuthNatsService(private val natsConnectionProperties: TLSAuthNatsConnectionProperties) : - BlueprintNatsService { + BluePrintNatsService { lateinit var streamingConnection: StreamingConnection diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TokenAuthNatsService.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TokenAuthNatsService.kt index 9d4aacfbd..7c24b70d0 100644 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TokenAuthNatsService.kt +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/TokenAuthNatsService.kt @@ -25,7 +25,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.splitCommaAsList open class TokenAuthNatsService(private val natsConnectionProperties: TokenAuthNatsConnectionProperties) : - BlueprintNatsService { + BluePrintNatsService { private val log = logger(TokenAuthNatsService::class) diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/utils/NatsClusterUtils.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/utils/NatsClusterUtils.kt index a155a076d..a7726a14b 100644 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/utils/NatsClusterUtils.kt +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/utils/NatsClusterUtils.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.nats.utils import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils object NatsClusterUtils { @@ -32,7 +32,7 @@ object NatsClusterUtils { } fun currentApplicationSubject(subject: String): String { - return "${BlueprintConstants.APP_NAME}.$subject" + return "${BluePrintConstants.APP_NAME}.$subject" } fun currentNodeDurable(subject: String): String { @@ -40,6 +40,6 @@ object NatsClusterUtils { } fun applicationLoadBalanceGroup(): String { - return "${BlueprintConstants.APP_NAME}" + return "${BluePrintConstants.APP_NAME}" } } diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSLTest.kt index fa70f0738..a95b900fe 100644 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/NatsPropertiesDSLTest.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.nats import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate @@ -59,12 +59,12 @@ class NatsPropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_NATS}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsExtensionsTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsExtensionsTest.kt new file mode 100644 index 000000000..ec120dc18 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsExtensionsTest.kt @@ -0,0 +1,51 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats.service + +import io.mockk.every +import io.mockk.mockk +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.nats.asJsonType +import org.onap.ccsdk.cds.blueprintsprocessor.nats.strData +import org.onap.ccsdk.cds.controllerblueprints.core.asByteArray +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType +import java.nio.charset.Charset +import kotlin.test.assertEquals + +class BluePrintNatsExtensionsTest { + + @Test + fun testMessageStrConversion() { + val mockMessage = mockk() + every { mockMessage.data } returns "I am message".toByteArray(Charset.defaultCharset()) + + val messageData = mockMessage.strData() + assertEquals("I am message", messageData) + } + + @Test + fun testMessageJsonConversion() { + val json = """{"name":"value"}""" + + val mockMessage = mockk() + every { mockMessage.data } returns json.jsonAsJsonType().asByteArray() + + val messageData = mockMessage.asJsonType().asJsonString() + assertEquals(json, messageData) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyServiceTest.kt new file mode 100644 index 000000000..9a332d589 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsLibPropertyServiceTest.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats.service + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.nats.BluePrintNatsLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintNatsLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class + ] +) +@TestPropertySource( + properties = + [ + "blueprintsprocessor.nats.cds-controller.type=token-auth", + "blueprintsprocessor.nats.cds-controller.host=nats://localhost:4222", + "blueprintsprocessor.nats.cds-controller.token=tokenAuth" + ] +) +class BluePrintNatsLibPropertyServiceTest { + + @Autowired + lateinit var bluePrintNatsLibPropertyService: BluePrintNatsLibPropertyService + + @Test + fun testNatsProperties() { + assertTrue(::bluePrintNatsLibPropertyService.isInitialized) + bluePrintNatsLibPropertyService.bluePrintNatsService(NatsLibConstants.DEFULT_NATS_SELECTOR) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsServiceTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsServiceTest.kt new file mode 100644 index 000000000..721828ac9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BluePrintNatsServiceTest.kt @@ -0,0 +1,267 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.nats.service + +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import io.nats.streaming.MessageHandler +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsConnectionProperties +import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.nats.TokenAuthNatsConnectionProperties +import org.onap.ccsdk.cds.blueprintsprocessor.nats.strData +import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.SubscriptionOptionsUtils +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType +import kotlin.test.assertNotNull + +class BluePrintNatsServiceTest { + + @Test + fun testTokenAuthNatService() { + val configuration = """{ + "type" : "${NatsLibConstants.TYPE_TOKEN_AUTH}", + "host" : "nats://localhost:4222", + "token" : "tokenAuth" + } + """.trimIndent() + + val bluePrintNatsLibPropertyService = BluePrintNatsLibPropertyService(mockk()) + + val spkBluePrintNatsLibPropertyService = spyk(bluePrintNatsLibPropertyService) + every { + spkBluePrintNatsLibPropertyService + .bluePrintNatsService(any()) + } returns TokenAuthNatsService( + mockk() + ) + + val bluePrintNatsService = + spkBluePrintNatsLibPropertyService.bluePrintNatsService(configuration.jsonAsJsonType()) + assertNotNull(bluePrintNatsService, "failed to get NATS Service") + } + + @Test + fun testTLSAuthNatService() { + val configuration = """{ + "type" : "${NatsLibConstants.TYPE_TLS_AUTH}", + "host" : "nats://localhost:4222" + } + """.trimIndent() + + val bluePrintNatsLibPropertyService = BluePrintNatsLibPropertyService(mockk()) + + val spkBluePrintNatsLibPropertyService = spyk(bluePrintNatsLibPropertyService) + every { + spkBluePrintNatsLibPropertyService + .bluePrintNatsService(any()) + } returns TLSAuthNatsService( + mockk() + ) + + val bluePrintNatsService = + spkBluePrintNatsLibPropertyService.bluePrintNatsService(configuration.jsonAsJsonType()) + assertNotNull(bluePrintNatsService, "failed to get NATS Service") + } + + /** Enable to test only on local desktop. Don't enable in Build server + * Start the Server with : nats-streaming-server -cid cds-cluster --auth tokenAuth -m 8222 -V + */ + // @Test + fun localIntegrationTest() { + runBlocking { + + val connectionProperties = TokenAuthNatsConnectionProperties().apply { + host = "nats://localhost:4222,nats://localhost:4223" + clientId = "client-1" + token = "tokenAuth" + } + val natsService = TokenAuthNatsService(connectionProperties) + val streamingConnection = natsService.connection() + assertNotNull(streamingConnection, "failed to create nats connection") + + val connectionProperties2 = TokenAuthNatsConnectionProperties().apply { + host = "nats://localhost:4222,nats://localhost:4223" + clientId = "client-2" + token = "tokenAuth" + } + val tlsAuthNatsService2 = TokenAuthNatsService(connectionProperties2) + val streamingConnection2 = tlsAuthNatsService2.connection() + assertNotNull(streamingConnection2, "failed to create nats connection 2") + + testMultiPublish(natsService) + testLoadBalance(natsService) + testLimitSubscription(natsService) + testRequestReply(natsService) + testMultiRequestReply(natsService) + delay(1000) + } + } + + private fun testMultiPublish(natsService: BluePrintNatsService) { + runBlocking { + /** Multiple Publish Message Test **/ + val messageHandler1 = + MessageHandler { message -> println("Multi Publish Message Handler 1: ${message.strData()}") } + val messageHandler2 = + MessageHandler { message -> println("Multi Publish Message Handler 2: ${message.strData()}") } + + natsService.subscribe("multi-publish", messageHandler1) + natsService.subscribe("multi-publish", messageHandler2) + + repeat(5) { + natsService.publish("multi-publish", "multi publish message-$it".toByteArray()) + } + } + } + + private fun testLoadBalance(natsService: BluePrintNatsService) { + runBlocking { + /** Load balance Publish Message Test **/ + val lbMessageHandler1 = + MessageHandler { message -> println("LB Publish Message Handler 1: ${message.strData()}") } + val lbMessageHandler2 = + MessageHandler { message -> println("LB Publish Message Handler 2: ${message.strData()}") } + + val sub1 = natsService.loadBalanceSubscribe("lb-publish", "lb-group", lbMessageHandler1) + val sub2 = natsService.loadBalanceSubscribe("lb-publish", "lb-group", lbMessageHandler2) + + repeat(5) { + natsService.publish("lb-publish", "lb publish message-$it".toByteArray()) + } + sub1.unsubscribe() + sub2.unsubscribe() + } + } + + private fun testLimitSubscription(natsService: BluePrintNatsService) { + runBlocking { + /** Load balance Publish Message Test **/ + val lbMessageHandler1 = + MessageHandler { message -> + runBlocking { + println("LB Publish Message Handler 1: ${message.strData()}") + message.ack() + } + } + val lbMessageHandler2 = + MessageHandler { message -> + runBlocking { + println("LB Publish Message Handler 2: ${message.strData()}") + message.ack() + } + } + + val sub1 = natsService.loadBalanceSubscribe( + "lb-publish", "lb-group", lbMessageHandler1, + SubscriptionOptionsUtils.manualAckWithRateLimit(1) + ) + val sub2 = natsService.loadBalanceSubscribe( + "lb-publish", "lb-group", lbMessageHandler2, + SubscriptionOptionsUtils.manualAckWithRateLimit(1) + ) + + repeat(10) { + natsService.publish("lb-publish", "lb limit message-$it".toByteArray()) + } + sub1.unsubscribe() + sub2.unsubscribe() + } + } + + private fun testRequestReply(natsService: BluePrintNatsService) { + runBlocking { + val lbMessageHandler1 = io.nats.client.MessageHandler { message -> + println("LB RR Request Handler 1: ${String(message.data)} will reply to(${message.replyTo})") + message.connection.publish( + message.replyTo, + "Notification ${String(message.data)} reply from 1".toByteArray() + ) + } + + val lbMessageHandler2 = io.nats.client.MessageHandler { message -> + println("LB RR Request Handler 2: ${String(message.data)} will reply to(${message.replyTo})") + message.connection.publish( + message.replyTo, + "Notification ${String(message.data)} reply from 2".toByteArray() + ) + } + + natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler1) + natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler2) + + repeat(5) { + val message = natsService.requestAndGetOneReply( + "rr-request", + "rr message-$it".toByteArray(), + 1000 + ) + println("Received : ${message.strData()}") + } + } + } + + private fun testMultiRequestReply(natsService: BluePrintNatsService) { + runBlocking { + /** Request Reply **/ + val lbMessageHandler1 = io.nats.client.MessageHandler { message -> + println("LB RR Request Handler 1: ${String(message.data)} will reply to(${message.replyTo})") + message.connection.publish( + message.replyTo, + "Notification ${message.strData()} reply from 1".toByteArray() + ) + message.connection.publish( + message.replyTo, + "Completion ${message.strData()} reply from 1".toByteArray() + ) + } + val lbMessageHandler2 = io.nats.client.MessageHandler { message -> + println("LB RR Request Handler 2: ${message.strData()} will reply to(${message.replyTo})") + message.connection.publish( + message.replyTo, + "Notification ${message.strData()} reply from 2".toByteArray() + ) + message.connection.publish( + message.replyTo, + "Completion ${message.strData()} reply from 2".toByteArray() + ) + } + + natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler1) + natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler2) + + /** Should unsubscribe on completion message */ + val rrReplyMessageHandler = io.nats.client.MessageHandler { message -> + val messageContent = message.strData() + println("RR Reply Handler : $messageContent") + if (messageContent.startsWith("Completion")) { + message.subscription.unsubscribe() + } + } + repeat(5) { + natsService.requestAndGetMultipleReplies( + "rr-request", + "rr-reply-$it", + "rr message-$it".toByteArray(), + rrReplyMessageHandler + ) + } + } + } +} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsExtensionsTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsExtensionsTest.kt deleted file mode 100644 index 816b6c809..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsExtensionsTest.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats.service - -import io.mockk.every -import io.mockk.mockk -import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.nats.asJsonType -import org.onap.ccsdk.cds.blueprintsprocessor.nats.strData -import org.onap.ccsdk.cds.controllerblueprints.core.asByteArray -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType -import java.nio.charset.Charset -import kotlin.test.assertEquals - -class BlueprintNatsExtensionsTest { - - @Test - fun testMessageStrConversion() { - val mockMessage = mockk() - every { mockMessage.data } returns "I am message".toByteArray(Charset.defaultCharset()) - - val messageData = mockMessage.strData() - assertEquals("I am message", messageData) - } - - @Test - fun testMessageJsonConversion() { - val json = """{"name":"value"}""" - - val mockMessage = mockk() - every { mockMessage.data } returns json.jsonAsJsonType().asByteArray() - - val messageData = mockMessage.asJsonType().asJsonString() - assertEquals(json, messageData) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyServiceTest.kt deleted file mode 100644 index 5ef4a72c6..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsLibPropertyServiceTest.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats.service - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.nats.BlueprintNatsLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintNatsLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class - ] -) -@TestPropertySource( - properties = - [ - "blueprintsprocessor.nats.cds-controller.type=token-auth", - "blueprintsprocessor.nats.cds-controller.host=nats://localhost:4222", - "blueprintsprocessor.nats.cds-controller.token=tokenAuth" - ] -) -class BlueprintNatsLibPropertyServiceTest { - - @Autowired - lateinit var bluePrintNatsLibPropertyService: BlueprintNatsLibPropertyService - - @Test - fun testNatsProperties() { - assertTrue(::bluePrintNatsLibPropertyService.isInitialized) - bluePrintNatsLibPropertyService.bluePrintNatsService(NatsLibConstants.DEFULT_NATS_SELECTOR) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsServiceTest.kt b/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsServiceTest.kt deleted file mode 100644 index 8e7ee63f1..000000000 --- a/ms/blueprintsprocessor/modules/commons/nats-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/nats/service/BlueprintNatsServiceTest.kt +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.nats.service - -import io.mockk.every -import io.mockk.mockk -import io.mockk.spyk -import io.nats.streaming.MessageHandler -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsConnectionProperties -import org.onap.ccsdk.cds.blueprintsprocessor.nats.NatsLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.nats.TokenAuthNatsConnectionProperties -import org.onap.ccsdk.cds.blueprintsprocessor.nats.strData -import org.onap.ccsdk.cds.blueprintsprocessor.nats.utils.SubscriptionOptionsUtils -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType -import kotlin.test.assertNotNull - -class BlueprintNatsServiceTest { - - @Test - fun testTokenAuthNatService() { - val configuration = """{ - "type" : "${NatsLibConstants.TYPE_TOKEN_AUTH}", - "host" : "nats://localhost:4222", - "token" : "tokenAuth" - } - """.trimIndent() - - val bluePrintNatsLibPropertyService = BlueprintNatsLibPropertyService(mockk()) - - val spkBlueprintNatsLibPropertyService = spyk(bluePrintNatsLibPropertyService) - every { - spkBlueprintNatsLibPropertyService - .bluePrintNatsService(any()) - } returns TokenAuthNatsService( - mockk() - ) - - val bluePrintNatsService = - spkBlueprintNatsLibPropertyService.bluePrintNatsService(configuration.jsonAsJsonType()) - assertNotNull(bluePrintNatsService, "failed to get NATS Service") - } - - @Test - fun testTLSAuthNatService() { - val configuration = """{ - "type" : "${NatsLibConstants.TYPE_TLS_AUTH}", - "host" : "nats://localhost:4222" - } - """.trimIndent() - - val bluePrintNatsLibPropertyService = BlueprintNatsLibPropertyService(mockk()) - - val spkBlueprintNatsLibPropertyService = spyk(bluePrintNatsLibPropertyService) - every { - spkBlueprintNatsLibPropertyService - .bluePrintNatsService(any()) - } returns TLSAuthNatsService( - mockk() - ) - - val bluePrintNatsService = - spkBlueprintNatsLibPropertyService.bluePrintNatsService(configuration.jsonAsJsonType()) - assertNotNull(bluePrintNatsService, "failed to get NATS Service") - } - - /** Enable to test only on local desktop. Don't enable in Build server - * Start the Server with : nats-streaming-server -cid cds-cluster --auth tokenAuth -m 8222 -V - */ - // @Test - fun localIntegrationTest() { - runBlocking { - - val connectionProperties = TokenAuthNatsConnectionProperties().apply { - host = "nats://localhost:4222,nats://localhost:4223" - clientId = "client-1" - token = "tokenAuth" - } - val natsService = TokenAuthNatsService(connectionProperties) - val streamingConnection = natsService.connection() - assertNotNull(streamingConnection, "failed to create nats connection") - - val connectionProperties2 = TokenAuthNatsConnectionProperties().apply { - host = "nats://localhost:4222,nats://localhost:4223" - clientId = "client-2" - token = "tokenAuth" - } - val tlsAuthNatsService2 = TokenAuthNatsService(connectionProperties2) - val streamingConnection2 = tlsAuthNatsService2.connection() - assertNotNull(streamingConnection2, "failed to create nats connection 2") - - testMultiPublish(natsService) - testLoadBalance(natsService) - testLimitSubscription(natsService) - testRequestReply(natsService) - testMultiRequestReply(natsService) - delay(1000) - } - } - - private fun testMultiPublish(natsService: BlueprintNatsService) { - runBlocking { - /** Multiple Publish Message Test **/ - val messageHandler1 = - MessageHandler { message -> println("Multi Publish Message Handler 1: ${message.strData()}") } - val messageHandler2 = - MessageHandler { message -> println("Multi Publish Message Handler 2: ${message.strData()}") } - - natsService.subscribe("multi-publish", messageHandler1) - natsService.subscribe("multi-publish", messageHandler2) - - repeat(5) { - natsService.publish("multi-publish", "multi publish message-$it".toByteArray()) - } - } - } - - private fun testLoadBalance(natsService: BlueprintNatsService) { - runBlocking { - /** Load balance Publish Message Test **/ - val lbMessageHandler1 = - MessageHandler { message -> println("LB Publish Message Handler 1: ${message.strData()}") } - val lbMessageHandler2 = - MessageHandler { message -> println("LB Publish Message Handler 2: ${message.strData()}") } - - val sub1 = natsService.loadBalanceSubscribe("lb-publish", "lb-group", lbMessageHandler1) - val sub2 = natsService.loadBalanceSubscribe("lb-publish", "lb-group", lbMessageHandler2) - - repeat(5) { - natsService.publish("lb-publish", "lb publish message-$it".toByteArray()) - } - sub1.unsubscribe() - sub2.unsubscribe() - } - } - - private fun testLimitSubscription(natsService: BlueprintNatsService) { - runBlocking { - /** Load balance Publish Message Test **/ - val lbMessageHandler1 = - MessageHandler { message -> - runBlocking { - println("LB Publish Message Handler 1: ${message.strData()}") - message.ack() - } - } - val lbMessageHandler2 = - MessageHandler { message -> - runBlocking { - println("LB Publish Message Handler 2: ${message.strData()}") - message.ack() - } - } - - val sub1 = natsService.loadBalanceSubscribe( - "lb-publish", "lb-group", lbMessageHandler1, - SubscriptionOptionsUtils.manualAckWithRateLimit(1) - ) - val sub2 = natsService.loadBalanceSubscribe( - "lb-publish", "lb-group", lbMessageHandler2, - SubscriptionOptionsUtils.manualAckWithRateLimit(1) - ) - - repeat(10) { - natsService.publish("lb-publish", "lb limit message-$it".toByteArray()) - } - sub1.unsubscribe() - sub2.unsubscribe() - } - } - - private fun testRequestReply(natsService: BlueprintNatsService) { - runBlocking { - val lbMessageHandler1 = io.nats.client.MessageHandler { message -> - println("LB RR Request Handler 1: ${String(message.data)} will reply to(${message.replyTo})") - message.connection.publish( - message.replyTo, - "Notification ${String(message.data)} reply from 1".toByteArray() - ) - } - - val lbMessageHandler2 = io.nats.client.MessageHandler { message -> - println("LB RR Request Handler 2: ${String(message.data)} will reply to(${message.replyTo})") - message.connection.publish( - message.replyTo, - "Notification ${String(message.data)} reply from 2".toByteArray() - ) - } - - natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler1) - natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler2) - - repeat(5) { - val message = natsService.requestAndGetOneReply( - "rr-request", - "rr message-$it".toByteArray(), - 1000 - ) - println("Received : ${message.strData()}") - } - } - } - - private fun testMultiRequestReply(natsService: BlueprintNatsService) { - runBlocking { - /** Request Reply **/ - val lbMessageHandler1 = io.nats.client.MessageHandler { message -> - println("LB RR Request Handler 1: ${String(message.data)} will reply to(${message.replyTo})") - message.connection.publish( - message.replyTo, - "Notification ${message.strData()} reply from 1".toByteArray() - ) - message.connection.publish( - message.replyTo, - "Completion ${message.strData()} reply from 1".toByteArray() - ) - } - val lbMessageHandler2 = io.nats.client.MessageHandler { message -> - println("LB RR Request Handler 2: ${message.strData()} will reply to(${message.replyTo})") - message.connection.publish( - message.replyTo, - "Notification ${message.strData()} reply from 2".toByteArray() - ) - message.connection.publish( - message.replyTo, - "Completion ${message.strData()} reply from 2".toByteArray() - ) - } - - natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler1) - natsService.loadBalanceReplySubscribe("rr-request", "rr-group", lbMessageHandler2) - - /** Should unsubscribe on completion message */ - val rrReplyMessageHandler = io.nats.client.MessageHandler { message -> - val messageContent = message.strData() - println("RR Reply Handler : $messageContent") - if (messageContent.startsWith("Completion")) { - message.subscription.unsubscribe() - } - } - repeat(5) { - natsService.requestAndGetMultipleReplies( - "rr-request", - "rr-reply-$it", - "rr message-$it".toByteArray(), - rrReplyMessageHandler - ) - } - } - } -} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt new file mode 100644 index 000000000..2a4d05dcb --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt @@ -0,0 +1,88 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.context.properties.bind.Bindable +import org.springframework.boot.context.properties.bind.Binder +import org.springframework.context.ApplicationContext +import org.springframework.context.ApplicationContextAware +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.core.env.Environment +import org.springframework.stereotype.Service + +@Configuration +open class BluePrintCoreConfiguration(private val bluePrintPropertiesService: BluePrintPropertiesService) { + + companion object { + + const val PREFIX_BLUEPRINT_PROCESSOR = "blueprintsprocessor" + } + + @Bean + open fun bluePrintLoadConfiguration(): BluePrintLoadConfiguration { + return bluePrintPropertiesService + .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BluePrintLoadConfiguration::class.java) + } +} + +@Configuration +open class BluePrintPropertyConfiguration { + + @Autowired + lateinit var environment: Environment + + @Bean + open fun bluePrintPropertyBinder(): Binder { + return Binder.get(environment) + } +} + +@Service +open class BluePrintPropertiesService(private var bluePrintPropertyConfig: BluePrintPropertyConfiguration) { + + private val log = logger(BluePrintPropertiesService::class) + + fun propertyBeanType(prefix: String, type: Class): T { + return try { + bluePrintPropertyConfig.bluePrintPropertyBinder().bind(prefix, Bindable.of(type)).get() + } catch (e: NoSuchElementException) { + val errMsg = "Error: missing property \"$prefix\"... Check the application.properties file." + log.error(errMsg) + throw BluePrintProcessorException(e, errMsg) + } + } +} + +@Configuration +// Add Conditional property , If we try to manage on Application level +open class BlueprintDependencyConfiguration : ApplicationContextAware { + + private val log = LoggerFactory.getLogger(BlueprintDependencyConfiguration::class.java)!! + + override fun setApplicationContext(applicationContext: ApplicationContext) { + BluePrintDependencyService.inject(applicationContext) + log.info("Dependency Management module created...") + } +} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintCoreConfiguration.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintCoreConfiguration.kt deleted file mode 100644 index 782a7b033..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintCoreConfiguration.kt +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.core - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.context.properties.bind.Bindable -import org.springframework.boot.context.properties.bind.Binder -import org.springframework.context.ApplicationContext -import org.springframework.context.ApplicationContextAware -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.core.env.Environment -import org.springframework.stereotype.Service - -@Configuration -open class BlueprintCoreConfiguration(private val bluePrintPropertiesService: BlueprintPropertiesService) { - - companion object { - - const val PREFIX_BLUEPRINT_PROCESSOR = "blueprintsprocessor" - } - - @Bean - open fun bluePrintLoadConfiguration(): BlueprintLoadConfiguration { - return bluePrintPropertiesService - .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BlueprintLoadConfiguration::class.java) - } -} - -@Configuration -open class BlueprintPropertyConfiguration { - - @Autowired - lateinit var environment: Environment - - @Bean - open fun bluePrintPropertyBinder(): Binder { - return Binder.get(environment) - } -} - -@Service -open class BlueprintPropertiesService(private var bluePrintPropertyConfig: BlueprintPropertyConfiguration) { - - private val log = logger(BlueprintPropertiesService::class) - - fun propertyBeanType(prefix: String, type: Class): T { - return try { - bluePrintPropertyConfig.bluePrintPropertyBinder().bind(prefix, Bindable.of(type)).get() - } catch (e: NoSuchElementException) { - val errMsg = "Error: missing property \"$prefix\"... Check the application.properties file." - log.error(errMsg) - throw BlueprintProcessorException(e, errMsg) - } - } -} - -@Configuration -// Add Conditional property , If we try to manage on Application level -open class BlueprintDependencyConfiguration : ApplicationContextAware { - - private val log = LoggerFactory.getLogger(BlueprintDependencyConfiguration::class.java)!! - - override fun setApplicationContext(applicationContext: ApplicationContext) { - BlueprintDependencyService.inject(applicationContext) - log.info("Dependency Management module created...") - } -} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt index 924aed898..61997061b 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import io.swagger.annotations.ApiModelProperty import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import java.util.Date import java.util.UUID @@ -154,7 +154,7 @@ open class Status { var errorMessage: String? = null @get:ApiModelProperty(required = true, value = "Message providing request status") - var message: String = BlueprintConstants.STATUS_SUCCESS + var message: String = BluePrintConstants.STATUS_SUCCESS } open class StepData { diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensions.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensions.kt new file mode 100644 index 000000000..edb5bbfe6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensions.kt @@ -0,0 +1,75 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.cluster + +import com.hazelcast.cluster.Member +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.newSingleThreadContext +import kotlinx.coroutines.withContext +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterMember +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService + +/** + * Exposed Dependency Service by this Hazelcast Lib Module + */ +fun BluePrintDependencyService.clusterService(): BluePrintClusterService = + instance(HazelcastClusterService::class) + +/** Optional Cluster Service, returns only if Cluster is enabled */ +fun BluePrintDependencyService.optionalClusterService(): BluePrintClusterService? { + return if (BluePrintConstants.CLUSTER_ENABLED) { + BluePrintDependencyService.clusterService() + } else null +} + +/** Extension to convert Hazelcast Member to Blueprints Cluster Member */ +fun Member.toClusterMember(): ClusterMember { + val memberName: String = this.getAttribute(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID) ?: this.uuid.toString() + return ClusterMember( + id = this.uuid.toString(), + name = memberName, + memberAddress = this.address.toString() + ) +} + +/** + * This function will try to acquire the lock and then execute the provided block. + * If the lock cannot be acquired within timeout, a BluePrintException will be thrown. + * + * Since a lock can only be unlocked by the the thread which acquired the lock, + * this function will confine coroutines within the block to a dedicated thread. + */ +suspend fun ClusterLock.executeWithLock(acquireLockTimeout: Long, block: suspend () -> R): R { + val lock = this + return newSingleThreadContext(lock.name()).use { + withContext(GlobalScope.coroutineContext[MDCContext]?.plus(it) ?: it) { + if (lock.tryLock(acquireLockTimeout)) { + try { + block() + } finally { + lock.unLock() + } + } else + throw BluePrintException("Failed to acquire lock within timeout") + } + } +} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensions.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensions.kt deleted file mode 100644 index f0504555f..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensions.kt +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.core.cluster - -import com.hazelcast.cluster.Member -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.newSingleThreadContext -import kotlinx.coroutines.withContext -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterMember -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService - -/** - * Exposed Dependency Service by this Hazelcast Lib Module - */ -fun BlueprintDependencyService.clusterService(): BlueprintClusterService = - instance(HazelcastClusterService::class) - -/** Optional Cluster Service, returns only if Cluster is enabled */ -fun BlueprintDependencyService.optionalClusterService(): BlueprintClusterService? { - return if (BlueprintConstants.CLUSTER_ENABLED) { - BlueprintDependencyService.clusterService() - } else null -} - -/** Extension to convert Hazelcast Member to Blueprints Cluster Member */ -fun Member.toClusterMember(): ClusterMember { - val memberName: String = this.getAttribute(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID) ?: this.uuid.toString() - return ClusterMember( - id = this.uuid.toString(), - name = memberName, - memberAddress = this.address.toString() - ) -} - -/** - * This function will try to acquire the lock and then execute the provided block. - * If the lock cannot be acquired within timeout, a BlueprintException will be thrown. - * - * Since a lock can only be unlocked by the the thread which acquired the lock, - * this function will confine coroutines within the block to a dedicated thread. - */ -suspend fun ClusterLock.executeWithLock(acquireLockTimeout: Long, block: suspend () -> R): R { - val lock = this - return newSingleThreadContext(lock.name()).use { - withContext(GlobalScope.coroutineContext[MDCContext]?.plus(it) ?: it) { - if (lock.tryLock(acquireLockTimeout)) { - try { - block() - } finally { - lock.unLock() - } - } else - throw BlueprintException("Failed to acquire lock within timeout") - } - } -} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterService.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterService.kt index 613fc4a58..fb9056776 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterService.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterService.kt @@ -33,15 +33,15 @@ import com.hazelcast.scheduledexecutor.IScheduledExecutorService import com.hazelcast.topic.Message import com.hazelcast.topic.MessageListener import kotlinx.coroutines.delay -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessage -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterMessage +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessageListener import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterInfo import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterJoinedEvent import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterMember -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.utils.ClusterUtils @@ -53,7 +53,7 @@ import java.util.UUID import java.util.concurrent.TimeUnit @Service -open class HazelcastClusterService(private val applicationEventPublisher: ApplicationEventPublisher) : BlueprintClusterService { +open class HazelcastClusterService(private val applicationEventPublisher: ApplicationEventPublisher) : BluePrintClusterService { private val log = logger(HazelcastClusterService::class) lateinit var hazelcast: HazelcastInstance @@ -78,12 +78,12 @@ open class HazelcastClusterService(private val applicationEventPublisher: Applic } is ClusterInfo -> { - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_ID, configuration.id) - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID, configuration.nodeId) + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_ID, configuration.id) + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID, configuration.nodeId) val memberAttributeConfig = MemberAttributeConfig() memberAttributeConfig.setAttribute( - BlueprintConstants.PROPERTY_CLUSTER_NODE_ID, + BluePrintConstants.PROPERTY_CLUSTER_NODE_ID, configuration.nodeId ) @@ -122,7 +122,7 @@ open class HazelcastClusterService(private val applicationEventPublisher: Applic } } else -> { - throw BlueprintProcessorException("couldn't understand the cluster configuration") + throw BluePrintProcessorException("couldn't understand the cluster configuration") } } @@ -179,7 +179,7 @@ open class HazelcastClusterService(private val applicationEventPublisher: Applic return ClusterLockImpl(hazelcast, name) } - /** Return interface may change and it will be included in BlueprintClusterService */ + /** Return interface may change and it will be included in BluePrintClusterService */ @UseExperimental suspend fun clusterScheduler(name: String): IScheduledExecutorService { check(::hazelcast.isInitialized) { "failed to start and join cluster" } @@ -225,7 +225,7 @@ open class HazelcastClusterService(private val applicationEventPublisher: Applic check(::hazelcast.isInitialized) { "failed to start and join cluster" } val applicationMembers: MutableMap = hashMapOf() hazelcast.cluster.members.map { member -> - val memberName: String = member.getAttribute(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID) + val memberName: String = member.getAttribute(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID) if (memberName.startsWith(appName, true)) { applicationMembers[memberName] = member } @@ -300,7 +300,7 @@ open class ClusterLockImpl(private val hazelcast: HazelcastInstance, private val class HazelcastMessageListenerAdapter(val listener: BlueprintClusterMessageListener) : MessageListener { override fun onMessage(message: Message?) = message?.let { - BlueprintClusterMessage( + BluePrintClusterMessage( BlueprintClusterTopic.valueOf(it.source as String), it.messageObject, it.publishTime, diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt index 46ab25e23..2f925dc5b 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.core.factory -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware @@ -29,16 +29,16 @@ import org.springframework.context.ApplicationContextAware */ interface ComponentNode { - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun validate(context: MutableMap, componentContext: MutableMap) - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun process(context: MutableMap, componentContext: MutableMap) - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun errorHandle(context: MutableMap, componentContext: MutableMap) - @Throws(BlueprintProcessorException::class) + @Throws(BluePrintProcessorException::class) fun reTrigger(context: MutableMap, componentContext: MutableMap) } diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/listeners/BlueprintCompilerCacheMessageListener.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/listeners/BlueprintCompilerCacheMessageListener.kt index 64b4f0ac5..3833379c9 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/listeners/BlueprintCompilerCacheMessageListener.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/listeners/BlueprintCompilerCacheMessageListener.kt @@ -17,19 +17,19 @@ package org.onap.ccsdk.cds.blueprintsprocessor.core.listeners import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.BlueprintClusterTopic -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessage -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterMessage +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessageListener import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterJoinedEvent import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintCompileCache +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.event.EventListener import org.springframework.stereotype.Component @Component @ConditionalOnProperty("CLUSTER_ENABLED", havingValue = "true") -open class BlueprintCompilerCacheMessageListener(private val clusterService: BlueprintClusterService) : BlueprintClusterMessageListener { +open class BlueprintCompilerCacheMessageListener(private val clusterService: BluePrintClusterService) : BlueprintClusterMessageListener { private val log = logger(BlueprintCompilerCacheMessageListener::class) @EventListener(ClusterJoinedEvent::class) @@ -38,10 +38,10 @@ open class BlueprintCompilerCacheMessageListener(private val clusterService: Blu clusterService.addBlueprintClusterMessageListener(BlueprintClusterTopic.BLUEPRINT_CLEAN_COMPILER_CACHE, this) } - override fun onMessage(message: BlueprintClusterMessage?) { + override fun onMessage(message: BluePrintClusterMessage?) { message?.let { log.info("Received ClusterMessage - Cleaning compile cache for blueprint (${it.payload})") - BlueprintCompileCache.cleanClassLoader(it.payload) + BluePrintCompileCache.cleanClassLoader(it.payload) } } } diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BluePrintClusterService.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BluePrintClusterService.kt new file mode 100644 index 000000000..f7ba6f25f --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BluePrintClusterService.kt @@ -0,0 +1,106 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.service + +import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.BlueprintClusterTopic +import org.springframework.context.ApplicationEvent +import java.time.Duration +import java.util.Properties +import java.util.UUID + +interface BluePrintClusterService { + + /** Start the cluster with [clusterInfo], By default clustering service is disabled. + * Application module has to start cluster */ + suspend fun startCluster(configuration: T) + + fun clusterJoined(): Boolean + + fun isClient(): Boolean + + fun isLiteMember(): Boolean + + /** Returns [partitionGroup] master member */ + suspend fun masterMember(partitionGroup: String): ClusterMember + + /** Returns all the data cluster members */ + suspend fun allMembers(): Set + + /** + * Returns application cluster members for [appName] joined as server or lite member, + * Node joined as client won't be visible. Here the assumption is node-id is combination of + * application id and replica number, for an example Application cds-cluster then the node ids will be + * cds-cluster-1, cds-cluster-2, cds-cluster-3 + */ + suspend fun applicationMembers(appName: String): Set + + /** Create and get or get the distributed data map store with [name] */ + suspend fun clusterMapStore(name: String): MutableMap + + /** Create and get the distributed lock with [name] */ + suspend fun clusterLock(name: String): ClusterLock + + /** Shut down the cluster with [duration] */ + suspend fun shutDown(duration: Duration) + + /** Send [message] to the listener(s) of a [topic] */ + suspend fun sendMessage(topic: BlueprintClusterTopic, message: T) + + /** Register a [listener] to a [topic] and returns his UUID */ + fun addBlueprintClusterMessageListener(topic: BlueprintClusterTopic, listener: BlueprintClusterMessageListener): UUID + + /** Unregister a listener from a [topic] using his [uuid] and returns true if it succeeded */ + fun removeBlueprintClusterMessageListener(topic: BlueprintClusterTopic, uuid: UUID): Boolean +} + +data class ClusterInfo( + val id: String, + val nodeId: String, + var joinAsClient: Boolean = false, + var properties: Properties?, + var configFile: String +) + +data class ClusterMember( + val id: String, + val name: String, + val memberAddress: String?, + val state: String? = null +) + +interface ClusterLock { + + fun name(): String + suspend fun lock() + suspend fun fenceLock(): String + suspend fun tryLock(timeout: Long): Boolean + suspend fun tryFenceLock(timeout: Long): String + suspend fun unLock() + fun isLocked(): Boolean + fun isLockedByCurrentThread(): Boolean + fun close() +} + +class BluePrintClusterMessage(val topic: BlueprintClusterTopic, val payload: E, publishTime: Long, clusterMember: ClusterMember) + +interface BlueprintClusterMessageListener { + fun onMessage(message: BluePrintClusterMessage?) +} + +class ClusterJoinedEvent(source: Any) : ApplicationEvent(source) + +const val CDS_LOCK_GROUP = "cds-lock" diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BlueprintClusterService.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BlueprintClusterService.kt deleted file mode 100644 index 900ae927b..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/service/BlueprintClusterService.kt +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.core.service - -import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.BlueprintClusterTopic -import org.springframework.context.ApplicationEvent -import java.time.Duration -import java.util.Properties -import java.util.UUID - -interface BlueprintClusterService { - - /** Start the cluster with [clusterInfo], By default clustering service is disabled. - * Application module has to start cluster */ - suspend fun startCluster(configuration: T) - - fun clusterJoined(): Boolean - - fun isClient(): Boolean - - fun isLiteMember(): Boolean - - /** Returns [partitionGroup] master member */ - suspend fun masterMember(partitionGroup: String): ClusterMember - - /** Returns all the data cluster members */ - suspend fun allMembers(): Set - - /** - * Returns application cluster members for [appName] joined as server or lite member, - * Node joined as client won't be visible. Here the assumption is node-id is combination of - * application id and replica number, for an example Application cds-cluster then the node ids will be - * cds-cluster-1, cds-cluster-2, cds-cluster-3 - */ - suspend fun applicationMembers(appName: String): Set - - /** Create and get or get the distributed data map store with [name] */ - suspend fun clusterMapStore(name: String): MutableMap - - /** Create and get the distributed lock with [name] */ - suspend fun clusterLock(name: String): ClusterLock - - /** Shut down the cluster with [duration] */ - suspend fun shutDown(duration: Duration) - - /** Send [message] to the listener(s) of a [topic] */ - suspend fun sendMessage(topic: BlueprintClusterTopic, message: T) - - /** Register a [listener] to a [topic] and returns his UUID */ - fun addBlueprintClusterMessageListener(topic: BlueprintClusterTopic, listener: BlueprintClusterMessageListener): UUID - - /** Unregister a listener from a [topic] using his [uuid] and returns true if it succeeded */ - fun removeBlueprintClusterMessageListener(topic: BlueprintClusterTopic, uuid: UUID): Boolean -} - -data class ClusterInfo( - val id: String, - val nodeId: String, - var joinAsClient: Boolean = false, - var properties: Properties?, - var configFile: String -) - -data class ClusterMember( - val id: String, - val name: String, - val memberAddress: String?, - val state: String? = null -) - -interface ClusterLock { - - fun name(): String - suspend fun lock() - suspend fun fenceLock(): String - suspend fun tryLock(timeout: Long): Boolean - suspend fun tryFenceLock(timeout: Long): String - suspend fun unLock() - fun isLocked(): Boolean - fun isLockedByCurrentThread(): Boolean - fun close() -} - -class BlueprintClusterMessage(val topic: BlueprintClusterTopic, val payload: E, publishTime: Long, clusterMember: ClusterMember) - -interface BlueprintClusterMessageListener { - fun onMessage(message: BlueprintClusterMessage?) -} - -class ClusterJoinedEvent(source: Any) : ApplicationEvent(source) - -const val CDS_LOCK_GROUP = "cds-lock" diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt index 4ac59802b..72e5654d4 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt @@ -17,11 +17,11 @@ package org.onap.ccsdk.cds.blueprintsprocessor.core.utils import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils object PayloadUtils { @@ -38,11 +38,11 @@ object PayloadUtils { fun getResponseDataFromPayload(workflowName: String, responsePayload: JsonNode): JsonNode { return responsePayload.get("$workflowName-response").returnNullIfMissing() - ?: throw BlueprintProcessorException("failed to get property($workflowName-response)") + ?: throw BluePrintProcessorException("failed to get property($workflowName-response)") } fun prepareInputsFromWorkflowPayload( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode, workflowName: String ) { @@ -51,7 +51,7 @@ object PayloadUtils { } fun prepareDynamicInputsFromWorkflowPayload( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode, workflowName: String ) { @@ -61,12 +61,12 @@ object PayloadUtils { } fun prepareDynamicInputsFromComponentPayload( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode ) { payload.fields().forEach { property -> - val path = StringBuilder(BlueprintConstants.PATH_INPUTS) - .append(BlueprintConstants.PATH_DIVIDER).append(property.key).toString() + val path = StringBuilder(BluePrintConstants.PATH_INPUTS) + .append(BluePrintConstants.PATH_DIVIDER).append(property.key).toString() bluePrintRuntimeService.put(path, property.value) } } diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt new file mode 100644 index 000000000..c27285020 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt @@ -0,0 +1,20 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core + +// TODO +open class BluePrintPropertiesTest diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintPropertiesTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintPropertiesTest.kt deleted file mode 100644 index fa2e4d41a..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BlueprintPropertiesTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.core - -// TODO -open class BlueprintPropertiesTest diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensionsTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensionsTest.kt new file mode 100644 index 000000000..95394e7a9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BluePrintClusterExtensionsTest.kt @@ -0,0 +1,74 @@ +/* + * Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.cluster + +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.runBlocking +import org.junit.Before +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import kotlin.test.assertEquals + +class BluePrintClusterExtensionsTest { + + private lateinit var clusterLockMock: ClusterLock + + @Before + fun setup() { + clusterLockMock = mockk() + every { clusterLockMock.name() } returns "mock-lock" + } + + @Test + fun `executeWithLock - should call unlock and return block result`() { + runBlocking { + every { runBlocking { clusterLockMock.tryLock(more(0L)) } } returns true + every { runBlocking { clusterLockMock.unLock() } } returns Unit + + val result = clusterLockMock.executeWithLock(1_000) { "result" } + + verify { runBlocking { clusterLockMock.unLock() } } + assertEquals("result", result) + } + } + + @Test + fun `executeWithLock - should call unlock even when block throws exception`() { + runBlocking { + every { runBlocking { clusterLockMock.tryLock(more(0L)) } } returns true + every { runBlocking { clusterLockMock.unLock() } } returns Unit + + try { + clusterLockMock.executeWithLock(1_000) { throw RuntimeException("It crashed") } + } catch (e: Exception) { + } + + verify { runBlocking { clusterLockMock.unLock() } } + } + } + + @Test(expected = BluePrintException::class) + fun `executeWithLock - should throw exception when lock was not acquired within timeout`() { + runBlocking { + every { runBlocking { clusterLockMock.tryLock(eq(0L)) } } returns false + clusterLockMock.executeWithLock(0) { "Will not run" } + } + } +} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensionsTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensionsTest.kt deleted file mode 100644 index ead24b58d..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/BlueprintClusterExtensionsTest.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright © 2019 Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.core.cluster - -import io.mockk.every -import io.mockk.mockk -import io.mockk.verify -import kotlinx.coroutines.runBlocking -import org.junit.Before -import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import kotlin.test.assertEquals - -class BlueprintClusterExtensionsTest { - - private lateinit var clusterLockMock: ClusterLock - - @Before - fun setup() { - clusterLockMock = mockk() - every { clusterLockMock.name() } returns "mock-lock" - } - - @Test - fun `executeWithLock - should call unlock and return block result`() { - runBlocking { - every { runBlocking { clusterLockMock.tryLock(more(0L)) } } returns true - every { runBlocking { clusterLockMock.unLock() } } returns Unit - - val result = clusterLockMock.executeWithLock(1_000) { "result" } - - verify { runBlocking { clusterLockMock.unLock() } } - assertEquals("result", result) - } - } - - @Test - fun `executeWithLock - should call unlock even when block throws exception`() { - runBlocking { - every { runBlocking { clusterLockMock.tryLock(more(0L)) } } returns true - every { runBlocking { clusterLockMock.unLock() } } returns Unit - - try { - clusterLockMock.executeWithLock(1_000) { throw RuntimeException("It crashed") } - } catch (e: Exception) { - } - - verify { runBlocking { clusterLockMock.unLock() } } - } - } - - @Test(expected = BlueprintException::class) - fun `executeWithLock - should throw exception when lock was not acquired within timeout`() { - runBlocking { - every { runBlocking { clusterLockMock.tryLock(eq(0L)) } } returns false - clusterLockMock.executeWithLock(0) { "Will not run" } - } - } -} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterServiceTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterServiceTest.kt index 91ad657a2..ded017940 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/cluster/HazelcastClusterServiceTest.kt @@ -33,11 +33,11 @@ import kotlinx.coroutines.withContext import org.junit.After import org.junit.Before import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessage -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterMessage +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterMessageListener import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterInfo -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile @@ -61,8 +61,8 @@ class HazelcastClusterServiceTest { @Test fun testClientFileSystemYamlConfig() { - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_ID, "test-cluster") - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID, "node-1234") + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_ID, "test-cluster") + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID, "node-1234") System.setProperty( "hazelcast.client.config", normalizedFile("./src/test/resources/hazelcast/hazelcast-client.yaml").absolutePath @@ -75,8 +75,8 @@ class HazelcastClusterServiceTest { @Test fun testServerFileSystemYamlConfig() { - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_ID, "test-cluster") - System.setProperty(BlueprintConstants.PROPERTY_CLUSTER_NODE_ID, "node-1234") + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_ID, "test-cluster") + System.setProperty(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID, "node-1234") val configFile = normalizedFile("./src/test/resources/hazelcast/hazelcast.yaml") val config = FileSystemYamlConfig(configFile) assertNotNull(config) @@ -105,7 +105,7 @@ class HazelcastClusterServiceTest { } } - private suspend fun testMessageReceived(bluePrintClusterServices: List) { + private suspend fun testMessageReceived(bluePrintClusterServices: List) { val sender = bluePrintClusterServices[0] as HazelcastClusterService val receiver = bluePrintClusterServices[1] as HazelcastClusterService val messageSent = "hello world" @@ -113,7 +113,7 @@ class HazelcastClusterServiceTest { val uuid = receiver.addBlueprintClusterMessageListener( BlueprintClusterTopic.BLUEPRINT_CLEAN_COMPILER_CACHE, object : BlueprintClusterMessageListener { - override fun onMessage(message: BlueprintClusterMessage?) { + override fun onMessage(message: BluePrintClusterMessage?) { log.info("Message received - ${message?.payload}") isMessageReceived = messageSent == message?.payload } @@ -132,7 +132,7 @@ class HazelcastClusterServiceTest { private suspend fun createCluster( ids: List, joinAsClient: Boolean? = false - ): List { + ): List { return withContext(Dispatchers.Default) { val deferred = ids.map { id -> @@ -164,7 +164,7 @@ class HazelcastClusterServiceTest { } } - private suspend fun testDistributedStore(bluePrintClusterServices: List) { + private suspend fun testDistributedStore(bluePrintClusterServices: List) { /** Test Distributed store creation */ repeat(2) { storeId -> val store = bluePrintClusterServices[0].clusterMapStore( @@ -187,7 +187,7 @@ class HazelcastClusterServiceTest { } } - private suspend fun testDistributedLock(bluePrintClusterServices: List) { + private suspend fun testDistributedLock(bluePrintClusterServices: List) { val lockName = "sample-lock" withContext(Dispatchers.IO) { val deferred = async { @@ -218,7 +218,7 @@ class HazelcastClusterServiceTest { } private suspend fun executeLock( - bluePrintClusterService: BlueprintClusterService, + bluePrintClusterService: BluePrintClusterService, lockId: String, lockName: String ) { @@ -237,7 +237,7 @@ class HazelcastClusterServiceTest { distributedLock.close() } - private suspend fun executeScheduler(bluePrintClusterService: BlueprintClusterService) { + private suspend fun executeScheduler(bluePrintClusterService: BluePrintClusterService) { log.info("initialising ...") val hazelcastClusterService = bluePrintClusterService as HazelcastClusterService @@ -251,7 +251,7 @@ class HazelcastClusterServiceTest { // scheduler.scheduleOnAllMembersAtFixedRate(SampleSchedulerTask(), 0, 5, TimeUnit.SECONDS) } - private suspend fun printReachableMembers(bluePrintClusterServices: List) { + private suspend fun printReachableMembers(bluePrintClusterServices: List) { bluePrintClusterServices.forEach { bluePrintClusterService -> val hazelcastClusterService = bluePrintClusterService as HazelcastClusterService val hazelcast = hazelcastClusterService.hazelcast diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt new file mode 100644 index 000000000..e8bdbf9ef --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt @@ -0,0 +1,137 @@ +package org.onap.ccsdk.cds.blueprintsprocessor.core.utils + +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag +import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp +import org.springframework.test.context.junit4.SpringRunner +import java.text.SimpleDateFormat + +@RunWith(SpringRunner::class) +class BluePrintMappingsTest { + + val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val dateString = "2019-01-16T18:25:43.511Z" + val dateForTest = formatter.parse(dateString) + + val flag = Flag.newBuilder().setIsForce(false).setTtl(1).build() + + fun createFlag(): Flags { + val flag = Flags() + flag.isForce = false + flag.ttl = 1 + return flag + } + + @Test + fun flagToJavaTest() { + val flag2 = flag.toJava() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + @Test + fun flagToProtoTest() { + val flag = createFlag() + val flag2 = flag.toProto() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + fun createStatus(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status { + val status = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status() + status.code = 400 + status.errorMessage = "Concurrent modification exception" + status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name + status.message = "Error uploading data" + status.timestamp = dateForTest + return status + } + + @Test + fun statusToProtoTest() { + val status = createStatus() + val status2 = status.toProto() + + Assert.assertEquals(status.code, status2.code) + Assert.assertEquals(status.errorMessage, status2.errorMessage) + Assert.assertEquals(status.eventType, status2.eventType.name) + Assert.assertEquals(status.message, status2.message) + Assert.assertEquals(status.timestamp.toString(), status2.timestamp) + } + + @Test + fun commonHeaderToJavaTest() { + val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build() + + val commonHeader = + CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString) + .setFlag(flag).build() + val commonHeader2 = commonHeader.toJava() + + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp, formatter.format(commonHeader2.timestamp)) + } + + fun createCommonHeader(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader { + val commonHeader = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader() + commonHeader.flags = createFlag() + commonHeader.originatorId = "1234" + commonHeader.requestId = "2345" + commonHeader.subRequestId = "0123" + commonHeader.timestamp = dateForTest + return commonHeader + } + + @Test + fun commonHeaderToProtoTest() { + val commonHeader = createCommonHeader() + val commonHeader2 = commonHeader.toProto() + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp.currentTimestamp(), commonHeader2.timestamp) + } + + @Test + fun actionIdentifierToJavaTest() { + val actionIdentifiers = + ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0") + .setMode("Execution").build() + val actionIdentifiers2 = actionIdentifiers.toJava() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } + + fun createActionIdentifier(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers { + val ac = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers() + ac.mode = "mode" + ac.blueprintVersion = "version" + ac.blueprintName = "name" + ac.actionName = "action" + return ac + } + + @Test + fun actionIdentifierToProtoTest() { + val actionIdentifiers = createActionIdentifier() + val actionIdentifiers2 = actionIdentifiers.toProto() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BlueprintMappingsTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BlueprintMappingsTest.kt deleted file mode 100644 index 1549c9cdf..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BlueprintMappingsTest.kt +++ /dev/null @@ -1,137 +0,0 @@ -package org.onap.ccsdk.cds.blueprintsprocessor.core.utils - -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag -import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp -import org.springframework.test.context.junit4.SpringRunner -import java.text.SimpleDateFormat - -@RunWith(SpringRunner::class) -class BlueprintMappingsTest { - - val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - val dateString = "2019-01-16T18:25:43.511Z" - val dateForTest = formatter.parse(dateString) - - val flag = Flag.newBuilder().setIsForce(false).setTtl(1).build() - - fun createFlag(): Flags { - val flag = Flags() - flag.isForce = false - flag.ttl = 1 - return flag - } - - @Test - fun flagToJavaTest() { - val flag2 = flag.toJava() - - Assert.assertEquals(flag.isForce, flag2.isForce) - Assert.assertEquals(flag.ttl, flag2.ttl) - } - - @Test - fun flagToProtoTest() { - val flag = createFlag() - val flag2 = flag.toProto() - - Assert.assertEquals(flag.isForce, flag2.isForce) - Assert.assertEquals(flag.ttl, flag2.ttl) - } - - fun createStatus(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status { - val status = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status() - status.code = 400 - status.errorMessage = "Concurrent modification exception" - status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name - status.message = "Error uploading data" - status.timestamp = dateForTest - return status - } - - @Test - fun statusToProtoTest() { - val status = createStatus() - val status2 = status.toProto() - - Assert.assertEquals(status.code, status2.code) - Assert.assertEquals(status.errorMessage, status2.errorMessage) - Assert.assertEquals(status.eventType, status2.eventType.name) - Assert.assertEquals(status.message, status2.message) - Assert.assertEquals(status.timestamp.toString(), status2.timestamp) - } - - @Test - fun commonHeaderToJavaTest() { - val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build() - - val commonHeader = - CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString) - .setFlag(flag).build() - val commonHeader2 = commonHeader.toJava() - - Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) - Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) - Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) - Assert.assertEquals(commonHeader.timestamp, formatter.format(commonHeader2.timestamp)) - } - - fun createCommonHeader(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader { - val commonHeader = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader() - commonHeader.flags = createFlag() - commonHeader.originatorId = "1234" - commonHeader.requestId = "2345" - commonHeader.subRequestId = "0123" - commonHeader.timestamp = dateForTest - return commonHeader - } - - @Test - fun commonHeaderToProtoTest() { - val commonHeader = createCommonHeader() - val commonHeader2 = commonHeader.toProto() - Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) - Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) - Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) - Assert.assertEquals(commonHeader.timestamp.currentTimestamp(), commonHeader2.timestamp) - } - - @Test - fun actionIdentifierToJavaTest() { - val actionIdentifiers = - ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0") - .setMode("Execution").build() - val actionIdentifiers2 = actionIdentifiers.toJava() - - Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) - Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) - Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) - Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) - } - - fun createActionIdentifier(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers { - val ac = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers() - ac.mode = "mode" - ac.blueprintVersion = "version" - ac.blueprintName = "name" - ac.actionName = "action" - return ac - } - - @Test - fun actionIdentifierToProtoTest() { - val actionIdentifiers = createActionIdentifier() - val actionIdentifiers2 = actionIdentifiers.toProto() - - Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) - Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) - Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) - Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt new file mode 100644 index 000000000..6e9e4b554 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt @@ -0,0 +1,61 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2019 Huawei. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintRestLibConfiguration + +/** + * Exposed Dependency Service by this Rest Lib Module + */ +fun BluePrintDependencyService.restLibPropertyService(): BluePrintRestLibPropertyService = + instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) + +fun BluePrintDependencyService.restClientService(selector: String): BlueprintWebClientService { + return restLibPropertyService().blueprintWebClientService(selector) +} + +fun BluePrintDependencyService.restClientService(jsonNode: JsonNode): BlueprintWebClientService { + return restLibPropertyService().blueprintWebClientService(jsonNode) +} + +class RestLibConstants { + companion object { + + const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service" + const val PROPERTY_REST_CLIENT_PREFIX = "blueprintsprocessor.restclient." + const val PROPERTY_TYPE = "type" + const val TYPE_TOKEN_AUTH = "token-auth" + const val TYPE_BASIC_AUTH = "basic-auth" + const val TYPE_SSL_BASIC_AUTH = "ssl-basic-auth" + const val TYPE_SSL_TOKEN_AUTH = "ssl-token-auth" + const val TYPE_SSL_NO_AUTH = "ssl-no-auth" + const val TYPE_POLICY_MANAGER = "policy-manager" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt new file mode 100644 index 000000000..a227cf24e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt @@ -0,0 +1,66 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Huawei. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest + +open class RestClientProperties { + + lateinit var type: String + lateinit var url: String + var additionalHeaders: Map? = null +} + +open class SSLRestClientProperties : RestClientProperties() { + + lateinit var keyStoreInstance: String // JKS, PKCS12 + lateinit var sslTrust: String + lateinit var sslTrustPassword: String + var sslTrustIgnoreHostname: Boolean = false + var sslKey: String? = null + var sslKeyPassword: String? = null +} + +// FIXME("Define basic auth userName and password properties") +open class SSLBasicAuthRestClientProperties : SSLRestClientProperties() { + + var basicAuth: BasicAuthRestClientProperties? = null +} + +// FIXME("Define token properties") +open class SSLTokenAuthRestClientProperties : SSLRestClientProperties() { + + var tokenAuth: TokenAuthRestClientProperties? = null +} + +open class BasicAuthRestClientProperties : RestClientProperties() { + + lateinit var password: String + lateinit var username: String +} + +open class TokenAuthRestClientProperties : RestClientProperties() { + + var token: String? = null +} + +open class PolicyManagerRestClientProperties : RestClientProperties() { + + lateinit var env: String + lateinit var clientAuth: String + lateinit var authorisation: String +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibConfiguration.kt deleted file mode 100644 index 701fd172f..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibConfiguration.kt +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2019 Huawei. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.rest - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintRestLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BlueprintRestLibConfiguration - -/** - * Exposed Dependency Service by this Rest Lib Module - */ -fun BlueprintDependencyService.restLibPropertyService(): BlueprintRestLibPropertyService = - instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) - -fun BlueprintDependencyService.restClientService(selector: String): BlueprintWebClientService { - return restLibPropertyService().blueprintWebClientService(selector) -} - -fun BlueprintDependencyService.restClientService(jsonNode: JsonNode): BlueprintWebClientService { - return restLibPropertyService().blueprintWebClientService(jsonNode) -} - -class RestLibConstants { - companion object { - - const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service" - const val PROPERTY_REST_CLIENT_PREFIX = "blueprintsprocessor.restclient." - const val PROPERTY_TYPE = "type" - const val TYPE_TOKEN_AUTH = "token-auth" - const val TYPE_BASIC_AUTH = "basic-auth" - const val TYPE_SSL_BASIC_AUTH = "ssl-basic-auth" - const val TYPE_SSL_TOKEN_AUTH = "ssl-token-auth" - const val TYPE_SSL_NO_AUTH = "ssl-no-auth" - const val TYPE_POLICY_MANAGER = "policy-manager" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibData.kt deleted file mode 100644 index a227cf24e..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BlueprintRestLibData.kt +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Huawei. - * Modifications Copyright © 2019 Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.rest - -open class RestClientProperties { - - lateinit var type: String - lateinit var url: String - var additionalHeaders: Map? = null -} - -open class SSLRestClientProperties : RestClientProperties() { - - lateinit var keyStoreInstance: String // JKS, PKCS12 - lateinit var sslTrust: String - lateinit var sslTrustPassword: String - var sslTrustIgnoreHostname: Boolean = false - var sslKey: String? = null - var sslKeyPassword: String? = null -} - -// FIXME("Define basic auth userName and password properties") -open class SSLBasicAuthRestClientProperties : SSLRestClientProperties() { - - var basicAuth: BasicAuthRestClientProperties? = null -} - -// FIXME("Define token properties") -open class SSLTokenAuthRestClientProperties : SSLRestClientProperties() { - - var tokenAuth: TokenAuthRestClientProperties? = null -} - -open class BasicAuthRestClientProperties : RestClientProperties() { - - lateinit var password: String - lateinit var username: String -} - -open class TokenAuthRestClientProperties : RestClientProperties() { - - var token: String? = null -} - -open class PolicyManagerRestClientProperties : RestClientProperties() { - - lateinit var env: String - lateinit var clientAuth: String - lateinit var authorisation: String -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt index 45b9e3827..ca1046dde 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -30,25 +30,25 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Type DSL for Rest */ fun ServiceTemplateBuilder.relationshipTypeConnectsToRestClient() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToRestClient() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToRestClient() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToRestClient(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToRestClient(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through" ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -66,35 +66,35 @@ fun TopologyTemplateBuilder.relationshipTemplateRestClient( open class RestClientRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT, description ) { fun basicAuth(block: BasicAuthRestClientPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.basicAuthRestClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.basicAuthRestClientProperties(block)) } fun tokenAuth(block: TokenAuthRestClientPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.tokenAuthRestClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.tokenAuthRestClientProperties(block)) } fun sslAuth(block: SslAuthRestClientPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.sslRestClientProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.sslRestClientProperties(block)) } } -fun BlueprintTypes.basicAuthRestClientProperties(block: BasicAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.basicAuthRestClientProperties(block: BasicAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = BasicAuthRestClientPropertiesAssignmentBuilder().apply(block).build() assignments[RestClientProperties::type.name] = RestLibConstants.TYPE_BASIC_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.tokenAuthRestClientProperties(block: TokenAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.tokenAuthRestClientProperties(block: TokenAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = TokenAuthRestClientPropertiesAssignmentBuilder().apply(block).build() assignments[RestClientProperties::type.name] = RestLibConstants.TYPE_TOKEN_AUTH.asJsonPrimitive() return assignments.asJsonType() } -fun BlueprintTypes.sslRestClientProperties(block: SslAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.sslRestClientProperties(block: SslAuthRestClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { val assignments = SslAuthRestClientPropertiesAssignmentBuilder().apply(block).build() assignments[RestClientProperties::type.name] = RestLibConstants.TYPE_SSL_NO_AUTH.asJsonPrimitive() return assignments.asJsonType() diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt new file mode 100644 index 000000000..a2c68ec68 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt @@ -0,0 +1,222 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2019 Huawei. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.PolicyManagerRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) +open class BluePrintRestLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) { + + private var preInterceptor: PreInterceptor? = null + private var postInterceptor: PostInterceptor? = null + + fun setInterceptors(preInterceptor: PreInterceptor?, postInterceptor: PostInterceptor?) { + this.preInterceptor = preInterceptor + this.postInterceptor = postInterceptor + } + + fun clearInterceptors() { + this.preInterceptor = null + this.postInterceptor = null + } + + open fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService { + val service = preInterceptor?.getInstance(jsonNode) + ?: blueprintWebClientService(restClientProperties(jsonNode)) + return postInterceptor?.getInstance(jsonNode, service) ?: service + } + + open fun blueprintWebClientService(selector: String): BlueprintWebClientService { + val service = preInterceptor?.getInstance(selector) ?: run { + val prefix = "blueprintsprocessor.restclient.$selector" + val restClientProperties = restClientProperties(prefix) + blueprintWebClientService(restClientProperties) + } + return postInterceptor?.getInstance(selector, service) ?: service + } + + fun restClientProperties(prefix: String): RestClientProperties { + val type = bluePrintPropertiesService.propertyBeanType( + "$prefix.type", String::class.java + ) + return when (type) { + RestLibConstants.TYPE_BASIC_AUTH -> { + basicAuthRestClientProperties(prefix) + } + RestLibConstants.TYPE_TOKEN_AUTH -> { + tokenRestClientProperties(prefix) + } + RestLibConstants.TYPE_SSL_BASIC_AUTH -> { + sslBasicAuthRestClientProperties(prefix) + } + RestLibConstants.TYPE_SSL_TOKEN_AUTH -> { + sslTokenAuthRestClientProperties(prefix) + } + RestLibConstants.TYPE_SSL_NO_AUTH -> { + sslNoAuthRestClientProperties(prefix) + } + + RestLibConstants.TYPE_POLICY_MANAGER -> { + policyManagerRestClientProperties(prefix) + } + else -> { + throw BluePrintProcessorException( + "Rest adaptor($type) is" + + " not supported" + ) + } + } + } + + fun restClientProperties(jsonNode: JsonNode): RestClientProperties { + + val type = jsonNode.get("type").textValue() + return when (type) { + RestLibConstants.TYPE_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, TokenAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, BasicAuthRestClientProperties::class.java)!! + } + + RestLibConstants.TYPE_POLICY_MANAGER -> { + JacksonUtils.readValue(jsonNode, PolicyManagerRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_SSL_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, SSLBasicAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_SSL_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, SSLTokenAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_SSL_NO_AUTH -> { + JacksonUtils.readValue(jsonNode, SSLRestClientProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException( + "Rest adaptor($type) is not supported" + ) + } + } + } + + private fun blueprintWebClientService(restClientProperties: RestClientProperties): + BlueprintWebClientService { + + when (restClientProperties) { + is SSLRestClientProperties -> { + return SSLRestClientService(restClientProperties) + } + is TokenAuthRestClientProperties -> { + return TokenAuthRestClientService(restClientProperties) + } + is BasicAuthRestClientProperties -> { + return BasicAuthRestClientService(restClientProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get rest service for type:${restClientProperties.type} uri: ${restClientProperties.url}") + } + } + } + + private fun tokenRestClientProperties(prefix: String): + TokenAuthRestClientProperties { + return bluePrintPropertiesService.propertyBeanType( + prefix, TokenAuthRestClientProperties::class.java + ) + } + + private fun basicAuthRestClientProperties(prefix: String): + BasicAuthRestClientProperties { + return bluePrintPropertiesService.propertyBeanType( + prefix, BasicAuthRestClientProperties::class.java + ) + } + + private fun sslBasicAuthRestClientProperties(prefix: String): + SSLRestClientProperties { + + val sslProps: SSLBasicAuthRestClientProperties = + bluePrintPropertiesService.propertyBeanType( + prefix, SSLBasicAuthRestClientProperties::class.java + ) + val basicProps: BasicAuthRestClientProperties = + bluePrintPropertiesService.propertyBeanType( + prefix, BasicAuthRestClientProperties::class.java + ) + sslProps.basicAuth = basicProps + return sslProps + } + + private fun sslTokenAuthRestClientProperties(prefix: String): + SSLRestClientProperties { + + val sslProps: SSLTokenAuthRestClientProperties = + bluePrintPropertiesService.propertyBeanType( + prefix, + SSLTokenAuthRestClientProperties::class.java + ) + val basicProps: TokenAuthRestClientProperties = + bluePrintPropertiesService.propertyBeanType( + prefix, + TokenAuthRestClientProperties::class.java + ) + sslProps.tokenAuth = basicProps + return sslProps + } + + private fun sslNoAuthRestClientProperties(prefix: String): + SSLRestClientProperties { + return bluePrintPropertiesService.propertyBeanType( + prefix, SSLRestClientProperties::class.java + ) + } + + private fun policyManagerRestClientProperties(prefix: String): + PolicyManagerRestClientProperties { + return bluePrintPropertiesService.propertyBeanType( + prefix, PolicyManagerRestClientProperties::class.java + ) + } + + interface PreInterceptor { + + fun getInstance(jsonNode: JsonNode): BlueprintWebClientService? + + fun getInstance(selector: String): BlueprintWebClientService? + } + + interface PostInterceptor { + + fun getInstance(jsonNode: JsonNode, service: BlueprintWebClientService): BlueprintWebClientService + + fun getInstance(selector: String, service: BlueprintWebClientService): BlueprintWebClientService + } +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyService.kt deleted file mode 100644 index d28bd77db..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyService.kt +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, Bell Canada - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2019 Huawei. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.rest.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.PolicyManagerRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) -open class BlueprintRestLibPropertyService(private var bluePrintPropertiesService: BlueprintPropertiesService) { - - private var preInterceptor: PreInterceptor? = null - private var postInterceptor: PostInterceptor? = null - - fun setInterceptors(preInterceptor: PreInterceptor?, postInterceptor: PostInterceptor?) { - this.preInterceptor = preInterceptor - this.postInterceptor = postInterceptor - } - - fun clearInterceptors() { - this.preInterceptor = null - this.postInterceptor = null - } - - open fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService { - val service = preInterceptor?.getInstance(jsonNode) - ?: blueprintWebClientService(restClientProperties(jsonNode)) - return postInterceptor?.getInstance(jsonNode, service) ?: service - } - - open fun blueprintWebClientService(selector: String): BlueprintWebClientService { - val service = preInterceptor?.getInstance(selector) ?: run { - val prefix = "blueprintsprocessor.restclient.$selector" - val restClientProperties = restClientProperties(prefix) - blueprintWebClientService(restClientProperties) - } - return postInterceptor?.getInstance(selector, service) ?: service - } - - fun restClientProperties(prefix: String): RestClientProperties { - val type = bluePrintPropertiesService.propertyBeanType( - "$prefix.type", String::class.java - ) - return when (type) { - RestLibConstants.TYPE_BASIC_AUTH -> { - basicAuthRestClientProperties(prefix) - } - RestLibConstants.TYPE_TOKEN_AUTH -> { - tokenRestClientProperties(prefix) - } - RestLibConstants.TYPE_SSL_BASIC_AUTH -> { - sslBasicAuthRestClientProperties(prefix) - } - RestLibConstants.TYPE_SSL_TOKEN_AUTH -> { - sslTokenAuthRestClientProperties(prefix) - } - RestLibConstants.TYPE_SSL_NO_AUTH -> { - sslNoAuthRestClientProperties(prefix) - } - - RestLibConstants.TYPE_POLICY_MANAGER -> { - policyManagerRestClientProperties(prefix) - } - else -> { - throw BlueprintProcessorException( - "Rest adaptor($type) is" + - " not supported" - ) - } - } - } - - fun restClientProperties(jsonNode: JsonNode): RestClientProperties { - - val type = jsonNode.get("type").textValue() - return when (type) { - RestLibConstants.TYPE_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, TokenAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, BasicAuthRestClientProperties::class.java)!! - } - - RestLibConstants.TYPE_POLICY_MANAGER -> { - JacksonUtils.readValue(jsonNode, PolicyManagerRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_SSL_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, SSLBasicAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_SSL_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, SSLTokenAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_SSL_NO_AUTH -> { - JacksonUtils.readValue(jsonNode, SSLRestClientProperties::class.java)!! - } - else -> { - throw BlueprintProcessorException( - "Rest adaptor($type) is not supported" - ) - } - } - } - - private fun blueprintWebClientService(restClientProperties: RestClientProperties): - BlueprintWebClientService { - - when (restClientProperties) { - is SSLRestClientProperties -> { - return SSLRestClientService(restClientProperties) - } - is TokenAuthRestClientProperties -> { - return TokenAuthRestClientService(restClientProperties) - } - is BasicAuthRestClientProperties -> { - return BasicAuthRestClientService(restClientProperties) - } - else -> { - throw BlueprintProcessorException("couldn't get rest service for type:${restClientProperties.type} uri: ${restClientProperties.url}") - } - } - } - - private fun tokenRestClientProperties(prefix: String): - TokenAuthRestClientProperties { - return bluePrintPropertiesService.propertyBeanType( - prefix, TokenAuthRestClientProperties::class.java - ) - } - - private fun basicAuthRestClientProperties(prefix: String): - BasicAuthRestClientProperties { - return bluePrintPropertiesService.propertyBeanType( - prefix, BasicAuthRestClientProperties::class.java - ) - } - - private fun sslBasicAuthRestClientProperties(prefix: String): - SSLRestClientProperties { - - val sslProps: SSLBasicAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, SSLBasicAuthRestClientProperties::class.java - ) - val basicProps: BasicAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, BasicAuthRestClientProperties::class.java - ) - sslProps.basicAuth = basicProps - return sslProps - } - - private fun sslTokenAuthRestClientProperties(prefix: String): - SSLRestClientProperties { - - val sslProps: SSLTokenAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, - SSLTokenAuthRestClientProperties::class.java - ) - val basicProps: TokenAuthRestClientProperties = - bluePrintPropertiesService.propertyBeanType( - prefix, - TokenAuthRestClientProperties::class.java - ) - sslProps.tokenAuth = basicProps - return sslProps - } - - private fun sslNoAuthRestClientProperties(prefix: String): - SSLRestClientProperties { - return bluePrintPropertiesService.propertyBeanType( - prefix, SSLRestClientProperties::class.java - ) - } - - private fun policyManagerRestClientProperties(prefix: String): - PolicyManagerRestClientProperties { - return bluePrintPropertiesService.propertyBeanType( - prefix, PolicyManagerRestClientProperties::class.java - ) - } - - interface PreInterceptor { - - fun getInstance(jsonNode: JsonNode): BlueprintWebClientService? - - fun getInstance(selector: String): BlueprintWebClientService? - } - - interface PostInterceptor { - - fun getInstance(jsonNode: JsonNode, service: BlueprintWebClientService): BlueprintWebClientService - - fun getInstance(selector: String, service: BlueprintWebClientService): BlueprintWebClientService - } -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt index 43dbcbeb2..945d29850 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt @@ -36,9 +36,9 @@ import org.apache.http.message.BasicHeader import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants import org.onap.ccsdk.cds.blueprintsprocessor.rest.utils.WebClientUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintRetryException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintIOUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintRetryException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintIOUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod @@ -59,7 +59,7 @@ interface BlueprintWebClientService { .build() } - /** High performance non blocking Retry function, If execution block [block] throws BlueprintRetryException + /** High performance non blocking Retry function, If execution block [block] throws BluePrintRetryException * exception then this will perform wait and retrigger accoring to times [times] with delay [delay] */ suspend fun retry( @@ -69,11 +69,11 @@ interface BlueprintWebClientService { block: suspend (Int) -> T ): T { val exceptionBlock = { e: Exception -> - if (e !is BlueprintRetryException) { + if (e !is BluePrintRetryException) { throw e } } - return BlueprintIOUtils.retry(times, initialDelay, delay, block, exceptionBlock) + return BluePrintIOUtils.retry(times, initialDelay, delay, block, exceptionBlock) } fun exchangeResource(methodType: String, path: String, request: String): WebClientResponse { @@ -98,7 +98,7 @@ interface BlueprintWebClientService { HttpMethod.POST -> post(path, request, convertedHeaders, String::class.java) HttpMethod.PUT -> put(path, request, convertedHeaders, String::class.java) HttpMethod.PATCH -> patch(path, request, convertedHeaders, String::class.java) - else -> throw BlueprintProcessorException( + else -> throw BluePrintProcessorException( "Unsupported methodType($methodType) attempted on path($path)" ) } @@ -270,7 +270,7 @@ interface BlueprintWebClientService { HttpMethod.DELETE -> deleteNB(path, convertedHeaders, responseType) HttpMethod.PUT -> putNB(path, request, convertedHeaders, responseType) HttpMethod.PATCH -> patchNB(path, request, convertedHeaders, responseType) - else -> throw BlueprintProcessorException("Unsupported methodType($methodType)") + else -> throw BluePrintProcessorException("Unsupported methodType($methodType)") } } @@ -323,7 +323,7 @@ interface BlueprintWebClientService { " User-supplied \"additionalHeaders\" cannot contain AUTHORIZATION header with" + " auth-type \"${RestLibConstants.TYPE_BASIC_AUTH}\"" WebClientUtils.log.error(errMsg) - throw BlueprintProcessorException(errMsg) + throw BluePrintProcessorException(errMsg) } else { customHeaders.putAll(it) } diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt index 8c7ba6573..611c0855d 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt @@ -29,12 +29,12 @@ import kotlinx.coroutines.reactor.ReactorContext import kotlinx.coroutines.reactor.asCoroutineContext import kotlinx.coroutines.withContext import org.apache.http.message.BasicHeader -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_INVOCATION_ID -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_ORIGINATOR_ID -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_PARTNER_NAME -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_REQUEST_ID -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.ONAP_SUBREQUEST_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_INVOCATION_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_ORIGINATOR_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_PARTNER_NAME +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_REQUEST_ID +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_SUBREQUEST_ID import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext import org.onap.ccsdk.cds.controllerblueprints.core.defaultToEmpty import org.onap.ccsdk.cds.controllerblueprints.core.defaultToUUID @@ -65,7 +65,7 @@ class RestLoggerService { fun httpInvoking(headers: Array) { headers.plusElement(BasicHeader(ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID())) headers.plusElement(BasicHeader(ONAP_INVOCATION_ID, UUID.randomUUID().toString())) - headers.plusElement(BasicHeader(ONAP_PARTNER_NAME, BlueprintConstants.APP_NAME)) + headers.plusElement(BasicHeader(ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME)) } } @@ -98,7 +98,7 @@ class RestLoggerService { resHeaders[ONAP_SUBREQUEST_ID] = MDC.get("SubRequestID") resHeaders[ONAP_ORIGINATOR_ID] = MDC.get("OriginatorID") resHeaders[ONAP_INVOCATION_ID] = MDC.get("InvocationID") - resHeaders[ONAP_PARTNER_NAME] = BlueprintConstants.APP_NAME + resHeaders[ONAP_PARTNER_NAME] = BluePrintConstants.APP_NAME } catch (e: Exception) { log.warn("couldn't set response headers", e) } finally { diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt new file mode 100644 index 000000000..62fca20f7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt @@ -0,0 +1,532 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * Modifications Copyright © 2019 Huawei. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BluePrintRestLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintRestLibConfiguration::class, BluePrintPropertyConfiguration::class, + BluePrintPropertiesService::class + ] +) +@TestPropertySource( + properties = + [ + "blueprintsprocessor.restclient.sample.type=basic-auth", + "blueprintsprocessor.restclient.sample.url=http://localhost:8080", + "blueprintsprocessor.restclient.sample.userId=sampleuser", + "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth", + "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443", + "blueprintsprocessor.restclient.sslbasic.username=admin", + "blueprintsprocessor.restclient.sslbasic.password=cds", + "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth", + "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443", + "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908", + "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssl.type=ssl-no-auth", + "blueprintsprocessor.restclient.ssl.url=https://localhost:8443", + "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12", + "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit", + "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12", + "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit" + ] +) +class BluePrintRestLibPropertyServiceTest { + + @Autowired + lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService + + @Test + fun testRestClientProperties() { + val properties = bluePrintRestLibPropertyService.restClientProperties( + "blueprintsprocessor.restclient.sample" + ) + assertNotNull(properties, "failed to create property bean") + assertNotNull( + properties.url, + "failed to get url property in" + + " property bean" + ) + } + + @Test + fun testSSLBasicProperties() { + val properties = bluePrintRestLibPropertyService.restClientProperties( + "blueprintsprocessor.restclient.sslbasic" + ) + assertNotNull(properties, "failed to create property bean") + val p: SSLBasicAuthRestClientProperties = + properties as SSLBasicAuthRestClientProperties + + assertEquals(p.basicAuth!!.username, "admin") + assertEquals(p.basicAuth!!.password, "cds") + assertEquals(p.sslTrust, "src/test/resources/keystore.p12") + assertEquals(p.sslTrustPassword, "changeit") + assertEquals(p.keyStoreInstance, "PKCS12") + } + + @Test + fun testSSLTokenProperties() { + val properties = bluePrintRestLibPropertyService.restClientProperties( + "blueprintsprocessor.restclient.ssltoken" + ) + assertNotNull(properties, "failed to create property bean") + + val p: SSLTokenAuthRestClientProperties = + properties as SSLTokenAuthRestClientProperties + + assertEquals(p.tokenAuth!!.token!!, "72178473kjshdkjgvbsdkjv903274908") + assertEquals(p.sslTrust, "src/test/resources/keystore.p12") + assertEquals(p.sslTrustPassword, "changeit") + assertEquals(p.keyStoreInstance, "PKCS12") + } + + @Test + fun testSSLNoAuthProperties() { + val properties = bluePrintRestLibPropertyService.restClientProperties( + "blueprintsprocessor.restclient.ssl" + ) + assertNotNull(properties, "failed to create property bean") + + val p: SSLRestClientProperties = + properties as SSLRestClientProperties + + assertEquals(p.sslTrust, "src/test/resources/keystore.p12") + assertEquals(p.sslTrustPassword, "changeit") + assertEquals(p.keyStoreInstance, "PKCS12") + assertEquals(p.sslKey, "src/test/resources/keystore.p12") + assertEquals(p.sslKeyPassword, "changeit") + } + + @Test + fun testSSLBasicPropertiesAsJson() { + val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField()) + val properties = bluePrintRestLibPropertyService.restClientProperties( + actualObj + ) + assertNotNull(properties, "failed to create property bean") + val p: SSLBasicAuthRestClientProperties = properties as SSLBasicAuthRestClientProperties + + assertEquals("admin", p.basicAuth!!.username) + assertEquals("cds", p.basicAuth!!.password) + assertEquals("src/test/resources/keystore.p12", p.sslTrust) + assertEquals("changeit", p.sslTrustPassword) + assertEquals("PKCS12", p.keyStoreInstance) + assertEquals("ssl-basic-auth", p.type) + assertEquals("https://localhost:8443", p.url) + } + + @Test + fun testSSLTokenPropertiesAsJson() { + val actualObj: JsonNode = defaultMapper.readTree(sslTokenAuthEndpointWithHeadersField()) + val properties = + bluePrintRestLibPropertyService.restClientProperties(actualObj) + assertNotNull(properties, "failed to create property bean") + + val p: SSLTokenAuthRestClientProperties = properties as SSLTokenAuthRestClientProperties + + assertEquals("72178473kjshdkjgvbsdkjv903274908", p.tokenAuth!!.token!!) + assertEquals("src/test/resources/keystore.p12", p.sslTrust) + assertEquals("changeit", p.sslTrustPassword) + assertEquals("PKCS12", p.keyStoreInstance) + assertEquals("ssl-token-auth", p.type) + assertEquals("https://localhost:8443", p.url) + } + + @Test + fun testSSLNoAuthPropertiesAsJson() { + val actualObj: JsonNode = defaultMapper.readTree(sslNoAuthEndpointWithHeadersField()) + val properties = bluePrintRestLibPropertyService.restClientProperties( + actualObj + ) + assertNotNull(properties, "failed to create property bean") + + val p: SSLRestClientProperties = + properties as SSLRestClientProperties + + assertEquals("src/test/resources/keystore.p12", p.sslTrust) + assertEquals("changeit", p.sslTrustPassword) + assertEquals("PKCS12", p.keyStoreInstance) + assertEquals("src/test/resources/keystore.p12", p.sslKey) + assertEquals("changeit", p.sslKeyPassword) + assertEquals("ssl-no-auth", p.type) + assertEquals("https://localhost:8443", p.url) + } + + @Test + fun testBlueprintWebClientService() { + val blueprintWebClientService = bluePrintRestLibPropertyService + .blueprintWebClientService("sample") + assertNotNull( + blueprintWebClientService, + "failed to create blueprintWebClientService" + ) + } + + @Test + fun testBlueprintWebClientServiceWithJsonNode() { + val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField()) + val blueprintWebClientService = bluePrintRestLibPropertyService + .blueprintWebClientService(actualObj) + assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService") + } + + // pass the result of $typeEndpointWithHeadersField() output with and without headers to compare. + private fun validateHeadersDidNotChangeWithEmptyAdditionalHeaders(noHeaders: String, withHeaders: String) { + val parsedObj: JsonNode = defaultMapper.readTree(noHeaders) + val bpWebClientService = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) + val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) + + val parsedObjWithHeaders: JsonNode = defaultMapper.readTree(withHeaders) + val bpWebClientServiceWithHeaders = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObjWithHeaders) + val extractedHeadersWithAdditionalHeaders = bpWebClientServiceWithHeaders.convertToBasicHeaders(mapOf()) + // Array> -> Map + val headersMap = extractedHeaders.map { it.name to it.value }.toMap() + val additionalHeadersMap = extractedHeadersWithAdditionalHeaders.map { it.name to it.value }.toMap() + assertEquals(headersMap, additionalHeadersMap) + } + + @Test + fun `BasicAuth WebClientService with empty additionalHeaders does not modify headers`() { + val endPointJson = basicAuthEndpointWithHeadersField() + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(emptyAdditionalHeaders) + validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) + } + + private fun acceptsOneAdditionalHeadersTest(endPointWithHeadersJson: String) { + val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) + val bpWebClientService = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) + val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) + assertEquals(1, extractedHeaders.filter { it.name == "key1" }.count()) + } + + @Test + fun `BasicAuth WebClientService accepts one additionalHeaders`() { + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(oneAdditionalParameter) + acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) + } + + private fun acceptsMultipleAdditionalHeaders(endPointWithHeadersJson: String) { + val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) + val bpWebClientService = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) + val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) + assertEquals(1, extractedHeaders.filter { it.name == "key1" }.count()) + assertEquals(1, extractedHeaders.filter { it.name == "key2" }.count()) + assertEquals(1, extractedHeaders.filter { it.name == "key3" }.count()) + } + + @Test + fun `BasicAuth WebClientService accepts multiple additionalHeaders`() { + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(threeAdditionalHeaders) + acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) + } + + private fun additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson: String) { + val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) + val bpWebClientService = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) + val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) + assertEquals( + MediaType.APPLICATION_XML.toString(), + extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!! + ) + } + + @Test + fun `BasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { + // default content type is application/json + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) + additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) + } + + // called from within "assertFailsWith(exceptionClass = BluePrintProcessorException::class) {" + private fun attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson: String) { + val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) + val bpWebClientService = + bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) + bpWebClientService.convertToBasicHeaders(mapOf()) + } + + @Test + fun `BasicAuth WebClientService throws BluePrintProcessorException if additionalHeaders contain Authorization`() { + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuth) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + // spec says headers are case insensitive... + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + } + + @Test + fun `TokenAuth WebClientService with empty additionalHeaders does not modify headers`() { + val endPointJson = sslTokenAuthEndpointWithHeadersField() + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(emptyAdditionalHeaders) + validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) + } + + @Test + fun `TokenAuth WebClientService accepts one additionalHeaders`() { + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(oneAdditionalParameter) + acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) + } + + @Test + fun `TokenAuth WebClientService accepts multiple additionalHeaders`() { + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(threeAdditionalHeaders) + acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) + } + + @Test + fun `TokenAuth WebClientService additionalHeaders can overwrite default Content-Type`() { + // default content type is application/json + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(contentTypeAdditionalHeader) + additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) + } + + @Test + fun `TokenAuth WebClientService throws BluePrintProcessorException if additionalHeaders contain Authorization`() { + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuth) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + // spec says headers are case insensitive... + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + } + + // TESTS FOR SSL BASIC AUTH headers + @Test + fun `SSLBasicAuth WebClientService with empty additionalHeaders does not modify headers`() { + val endPointJson = sslBasicAuthEndpointWithHeadersField() + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(emptyAdditionalHeaders) + validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) + } + + @Test + fun `SSLBasicAuth WebClientService accepts one additionalHeaders`() { + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(oneAdditionalParameter) + acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) + } + + @Test + fun `SSLBasicAuth WebClientService accepts multiple additionalHeaders`() { + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(threeAdditionalHeaders) + acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) + } + + @Test + fun `SSLBasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { + // default content type is application/json + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) + additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) + } + + @Test + fun `SSLBasicAuth WebClientService throws BluePrintProcessorException if additionalHeaders contain Authorization`() { + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuth) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + // spec says headers are case insensitive... + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + } + + // SSL-NO-AUTH headers tests + @Test + fun `SSLNoAuth WebClientService with empty additionalHeaders does not modify headers`() { + val endPointJson = sslNoAuthEndpointWithHeadersField() + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(emptyAdditionalHeaders) + validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) + } + + @Test + fun `SSLNoAuth WebClientService accepts one additionalHeaders`() { + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(oneAdditionalParameter) + acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) + } + + @Test + fun `SSLNoAuth WebClientService accepts multiple additionalHeaders`() { + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(threeAdditionalHeaders) + acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) + } + + @Test + fun `SSLNoAuth WebClientService additionalHeaders can overwrite default Content-Type`() { + // default content type is application/json + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(contentTypeAdditionalHeader) + additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) + } + + @Test + fun `SSLNoAuth WebClientService throws BluePrintProcessorException if additionalHeaders contain Authorization`() { + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuth) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + // spec says headers are case insensitive... + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) + attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) + } + } + + companion object BluePrintRestLibPropertyServiceTest { + + val defaultMapper = ObjectMapper() + val expectedTokenAuthDefaultHeaders = mapOf( + "Content-Type" to "application/json", + "Accept" to "application/json", + "Authorization" to "72178473kjshdkjgvbsdkjv903274908" + ) + + val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField( + """, + "additionalHeaders" : { + "authorization": "Basic aGF2ZTphbmljZWRheQo=" + } + """.trimIndent() + ) + + private fun sslTokenAuthEndpointWithHeadersField(headers: String = ""): String = + """{ + "type" : "ssl-token-auth", + "url" : "https://localhost:8443", + "keyStoreInstance" : "PKCS12", + "sslTrust" : "src/test/resources/keystore.p12", + "sslTrustPassword" : "changeit", + "tokenAuth" : { + "token" : "72178473kjshdkjgvbsdkjv903274908" + }$headers + } + """.trimIndent() + + private fun sslBasicAuthEndpointWithHeadersField(headers: String = ""): String = + """{ + "type" : "ssl-basic-auth", + "url" : "https://localhost:8443", + "keyStoreInstance" : "PKCS12", + "sslTrust" : "src/test/resources/keystore.p12", + "sslTrustPassword" : "changeit", + "basicAuth" : { + "username" : "admin", + "password" : "cds" + }$headers + } + """.trimIndent() + + private fun sslNoAuthEndpointWithHeadersField(headers: String = ""): String = """{ + "type" : "ssl-no-auth", + "url" : "https://localhost:8443", + "keyStoreInstance" : "PKCS12", + "sslTrust" : "src/test/resources/keystore.p12", + "sslTrustPassword" : "changeit", + "sslKey" : "src/test/resources/keystore.p12", + "sslKeyPassword" : "changeit"$headers + } + """.trimIndent() + + // Don't forget to supply "," as the first char to make valid JSON + private fun basicAuthEndpointWithHeadersField(headers: String = ""): String = + """{ + "type": "basic-auth", + "url": "http://127.0.0.1:8000", + "username": "user", + "password": "pass"$headers + } + """.trimIndent() + + private val emptyAdditionalHeaders = """, + "additionalHeaders" : { + } + """.trimIndent() + + private val oneAdditionalParameter = """, + "additionalHeaders" : { + "key1": "value1" + } + """.trimIndent() + + private val threeAdditionalHeaders = """, + "additionalHeaders" : { + "key1": "value1", + "key2": "value2", + "key3": "value3" + } + """.trimIndent() + + private val contentTypeAdditionalHeader = """, + "additionalHeaders" : { + "${HttpHeaders.CONTENT_TYPE}": "${MediaType.APPLICATION_XML}" + } + """.trimIndent() + + private val additionalHeadersWithAuth = """, + "additionalHeaders" : { + "Authorization": "Basic aGF2ZTphbmljZWRheQo=" + } + """.trimIndent() + + private val additionalHeadersWithAuthLowercased = """, + "additionalHeaders" : { + "authorization": "Basic aGF2ZTphbmljZWRheQo=" + } + """.trimIndent() + } +} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyServiceTest.kt deleted file mode 100644 index 117fbbd25..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintRestLibPropertyServiceTest.kt +++ /dev/null @@ -1,532 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * Modifications Copyright © 2019 Huawei. - * Modifications Copyright © 2019 Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.rest.service - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BlueprintRestLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintRestLibConfiguration::class, BlueprintPropertyConfiguration::class, - BlueprintPropertiesService::class - ] -) -@TestPropertySource( - properties = - [ - "blueprintsprocessor.restclient.sample.type=basic-auth", - "blueprintsprocessor.restclient.sample.url=http://localhost:8080", - "blueprintsprocessor.restclient.sample.userId=sampleuser", - "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth", - "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443", - "blueprintsprocessor.restclient.sslbasic.username=admin", - "blueprintsprocessor.restclient.sslbasic.password=cds", - "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth", - "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443", - "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908", - "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssl.type=ssl-no-auth", - "blueprintsprocessor.restclient.ssl.url=https://localhost:8443", - "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12", - "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit", - "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12", - "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit" - ] -) -class BlueprintRestLibPropertyServiceTest { - - @Autowired - lateinit var bluePrintRestLibPropertyService: BlueprintRestLibPropertyService - - @Test - fun testRestClientProperties() { - val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.sample" - ) - assertNotNull(properties, "failed to create property bean") - assertNotNull( - properties.url, - "failed to get url property in" + - " property bean" - ) - } - - @Test - fun testSSLBasicProperties() { - val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.sslbasic" - ) - assertNotNull(properties, "failed to create property bean") - val p: SSLBasicAuthRestClientProperties = - properties as SSLBasicAuthRestClientProperties - - assertEquals(p.basicAuth!!.username, "admin") - assertEquals(p.basicAuth!!.password, "cds") - assertEquals(p.sslTrust, "src/test/resources/keystore.p12") - assertEquals(p.sslTrustPassword, "changeit") - assertEquals(p.keyStoreInstance, "PKCS12") - } - - @Test - fun testSSLTokenProperties() { - val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.ssltoken" - ) - assertNotNull(properties, "failed to create property bean") - - val p: SSLTokenAuthRestClientProperties = - properties as SSLTokenAuthRestClientProperties - - assertEquals(p.tokenAuth!!.token!!, "72178473kjshdkjgvbsdkjv903274908") - assertEquals(p.sslTrust, "src/test/resources/keystore.p12") - assertEquals(p.sslTrustPassword, "changeit") - assertEquals(p.keyStoreInstance, "PKCS12") - } - - @Test - fun testSSLNoAuthProperties() { - val properties = bluePrintRestLibPropertyService.restClientProperties( - "blueprintsprocessor.restclient.ssl" - ) - assertNotNull(properties, "failed to create property bean") - - val p: SSLRestClientProperties = - properties as SSLRestClientProperties - - assertEquals(p.sslTrust, "src/test/resources/keystore.p12") - assertEquals(p.sslTrustPassword, "changeit") - assertEquals(p.keyStoreInstance, "PKCS12") - assertEquals(p.sslKey, "src/test/resources/keystore.p12") - assertEquals(p.sslKeyPassword, "changeit") - } - - @Test - fun testSSLBasicPropertiesAsJson() { - val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField()) - val properties = bluePrintRestLibPropertyService.restClientProperties( - actualObj - ) - assertNotNull(properties, "failed to create property bean") - val p: SSLBasicAuthRestClientProperties = properties as SSLBasicAuthRestClientProperties - - assertEquals("admin", p.basicAuth!!.username) - assertEquals("cds", p.basicAuth!!.password) - assertEquals("src/test/resources/keystore.p12", p.sslTrust) - assertEquals("changeit", p.sslTrustPassword) - assertEquals("PKCS12", p.keyStoreInstance) - assertEquals("ssl-basic-auth", p.type) - assertEquals("https://localhost:8443", p.url) - } - - @Test - fun testSSLTokenPropertiesAsJson() { - val actualObj: JsonNode = defaultMapper.readTree(sslTokenAuthEndpointWithHeadersField()) - val properties = - bluePrintRestLibPropertyService.restClientProperties(actualObj) - assertNotNull(properties, "failed to create property bean") - - val p: SSLTokenAuthRestClientProperties = properties as SSLTokenAuthRestClientProperties - - assertEquals("72178473kjshdkjgvbsdkjv903274908", p.tokenAuth!!.token!!) - assertEquals("src/test/resources/keystore.p12", p.sslTrust) - assertEquals("changeit", p.sslTrustPassword) - assertEquals("PKCS12", p.keyStoreInstance) - assertEquals("ssl-token-auth", p.type) - assertEquals("https://localhost:8443", p.url) - } - - @Test - fun testSSLNoAuthPropertiesAsJson() { - val actualObj: JsonNode = defaultMapper.readTree(sslNoAuthEndpointWithHeadersField()) - val properties = bluePrintRestLibPropertyService.restClientProperties( - actualObj - ) - assertNotNull(properties, "failed to create property bean") - - val p: SSLRestClientProperties = - properties as SSLRestClientProperties - - assertEquals("src/test/resources/keystore.p12", p.sslTrust) - assertEquals("changeit", p.sslTrustPassword) - assertEquals("PKCS12", p.keyStoreInstance) - assertEquals("src/test/resources/keystore.p12", p.sslKey) - assertEquals("changeit", p.sslKeyPassword) - assertEquals("ssl-no-auth", p.type) - assertEquals("https://localhost:8443", p.url) - } - - @Test - fun testBlueprintWebClientService() { - val blueprintWebClientService = bluePrintRestLibPropertyService - .blueprintWebClientService("sample") - assertNotNull( - blueprintWebClientService, - "failed to create blueprintWebClientService" - ) - } - - @Test - fun testBlueprintWebClientServiceWithJsonNode() { - val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField()) - val blueprintWebClientService = bluePrintRestLibPropertyService - .blueprintWebClientService(actualObj) - assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService") - } - - // pass the result of $typeEndpointWithHeadersField() output with and without headers to compare. - private fun validateHeadersDidNotChangeWithEmptyAdditionalHeaders(noHeaders: String, withHeaders: String) { - val parsedObj: JsonNode = defaultMapper.readTree(noHeaders) - val bpWebClientService = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) - val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) - - val parsedObjWithHeaders: JsonNode = defaultMapper.readTree(withHeaders) - val bpWebClientServiceWithHeaders = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObjWithHeaders) - val extractedHeadersWithAdditionalHeaders = bpWebClientServiceWithHeaders.convertToBasicHeaders(mapOf()) - // Array> -> Map - val headersMap = extractedHeaders.map { it.name to it.value }.toMap() - val additionalHeadersMap = extractedHeadersWithAdditionalHeaders.map { it.name to it.value }.toMap() - assertEquals(headersMap, additionalHeadersMap) - } - - @Test - fun `BasicAuth WebClientService with empty additionalHeaders does not modify headers`() { - val endPointJson = basicAuthEndpointWithHeadersField() - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(emptyAdditionalHeaders) - validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) - } - - private fun acceptsOneAdditionalHeadersTest(endPointWithHeadersJson: String) { - val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) - val bpWebClientService = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) - val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) - assertEquals(1, extractedHeaders.filter { it.name == "key1" }.count()) - } - - @Test - fun `BasicAuth WebClientService accepts one additionalHeaders`() { - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(oneAdditionalParameter) - acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) - } - - private fun acceptsMultipleAdditionalHeaders(endPointWithHeadersJson: String) { - val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) - val bpWebClientService = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) - val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) - assertEquals(1, extractedHeaders.filter { it.name == "key1" }.count()) - assertEquals(1, extractedHeaders.filter { it.name == "key2" }.count()) - assertEquals(1, extractedHeaders.filter { it.name == "key3" }.count()) - } - - @Test - fun `BasicAuth WebClientService accepts multiple additionalHeaders`() { - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(threeAdditionalHeaders) - acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) - } - - private fun additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson: String) { - val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) - val bpWebClientService = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) - val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf()) - assertEquals( - MediaType.APPLICATION_XML.toString(), - extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!! - ) - } - - @Test - fun `BasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - // default content type is application/json - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) - additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) - } - - // called from within "assertFailsWith(exceptionClass = BlueprintProcessorException::class) {" - private fun attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson: String) { - val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson) - val bpWebClientService = - bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj) - bpWebClientService.convertToBasicHeaders(mapOf()) - } - - @Test - fun `BasicAuth WebClientService throws BlueprintProcessorException if additionalHeaders contain Authorization`() { - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuth) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - // spec says headers are case insensitive... - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - } - - @Test - fun `TokenAuth WebClientService with empty additionalHeaders does not modify headers`() { - val endPointJson = sslTokenAuthEndpointWithHeadersField() - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(emptyAdditionalHeaders) - validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) - } - - @Test - fun `TokenAuth WebClientService accepts one additionalHeaders`() { - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(oneAdditionalParameter) - acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) - } - - @Test - fun `TokenAuth WebClientService accepts multiple additionalHeaders`() { - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(threeAdditionalHeaders) - acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) - } - - @Test - fun `TokenAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - // default content type is application/json - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(contentTypeAdditionalHeader) - additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) - } - - @Test - fun `TokenAuth WebClientService throws BlueprintProcessorException if additionalHeaders contain Authorization`() { - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuth) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - // spec says headers are case insensitive... - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - } - - // TESTS FOR SSL BASIC AUTH headers - @Test - fun `SSLBasicAuth WebClientService with empty additionalHeaders does not modify headers`() { - val endPointJson = sslBasicAuthEndpointWithHeadersField() - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(emptyAdditionalHeaders) - validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) - } - - @Test - fun `SSLBasicAuth WebClientService accepts one additionalHeaders`() { - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(oneAdditionalParameter) - acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) - } - - @Test - fun `SSLBasicAuth WebClientService accepts multiple additionalHeaders`() { - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(threeAdditionalHeaders) - acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) - } - - @Test - fun `SSLBasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - // default content type is application/json - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(contentTypeAdditionalHeader) - additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) - } - - @Test - fun `SSLBasicAuth WebClientService throws BlueprintProcessorException if additionalHeaders contain Authorization`() { - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuth) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - // spec says headers are case insensitive... - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - } - - // SSL-NO-AUTH headers tests - @Test - fun `SSLNoAuth WebClientService with empty additionalHeaders does not modify headers`() { - val endPointJson = sslNoAuthEndpointWithHeadersField() - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(emptyAdditionalHeaders) - validateHeadersDidNotChangeWithEmptyAdditionalHeaders(endPointJson, endPointWithHeadersJson) - } - - @Test - fun `SSLNoAuth WebClientService accepts one additionalHeaders`() { - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(oneAdditionalParameter) - acceptsOneAdditionalHeadersTest(endPointWithHeadersJson) - } - - @Test - fun `SSLNoAuth WebClientService accepts multiple additionalHeaders`() { - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(threeAdditionalHeaders) - acceptsMultipleAdditionalHeaders(endPointWithHeadersJson) - } - - @Test - fun `SSLNoAuth WebClientService additionalHeaders can overwrite default Content-Type`() { - // default content type is application/json - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(contentTypeAdditionalHeader) - additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson) - } - - @Test - fun `SSLNoAuth WebClientService throws BlueprintProcessorException if additionalHeaders contain Authorization`() { - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuth) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - // spec says headers are case insensitive... - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased) - attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson) - } - } - - companion object BlueprintRestLibPropertyServiceTest { - - val defaultMapper = ObjectMapper() - val expectedTokenAuthDefaultHeaders = mapOf( - "Content-Type" to "application/json", - "Accept" to "application/json", - "Authorization" to "72178473kjshdkjgvbsdkjv903274908" - ) - - val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField( - """, - "additionalHeaders" : { - "authorization": "Basic aGF2ZTphbmljZWRheQo=" - } - """.trimIndent() - ) - - private fun sslTokenAuthEndpointWithHeadersField(headers: String = ""): String = - """{ - "type" : "ssl-token-auth", - "url" : "https://localhost:8443", - "keyStoreInstance" : "PKCS12", - "sslTrust" : "src/test/resources/keystore.p12", - "sslTrustPassword" : "changeit", - "tokenAuth" : { - "token" : "72178473kjshdkjgvbsdkjv903274908" - }$headers - } - """.trimIndent() - - private fun sslBasicAuthEndpointWithHeadersField(headers: String = ""): String = - """{ - "type" : "ssl-basic-auth", - "url" : "https://localhost:8443", - "keyStoreInstance" : "PKCS12", - "sslTrust" : "src/test/resources/keystore.p12", - "sslTrustPassword" : "changeit", - "basicAuth" : { - "username" : "admin", - "password" : "cds" - }$headers - } - """.trimIndent() - - private fun sslNoAuthEndpointWithHeadersField(headers: String = ""): String = """{ - "type" : "ssl-no-auth", - "url" : "https://localhost:8443", - "keyStoreInstance" : "PKCS12", - "sslTrust" : "src/test/resources/keystore.p12", - "sslTrustPassword" : "changeit", - "sslKey" : "src/test/resources/keystore.p12", - "sslKeyPassword" : "changeit"$headers - } - """.trimIndent() - - // Don't forget to supply "," as the first char to make valid JSON - private fun basicAuthEndpointWithHeadersField(headers: String = ""): String = - """{ - "type": "basic-auth", - "url": "http://127.0.0.1:8000", - "username": "user", - "password": "pass"$headers - } - """.trimIndent() - - private val emptyAdditionalHeaders = """, - "additionalHeaders" : { - } - """.trimIndent() - - private val oneAdditionalParameter = """, - "additionalHeaders" : { - "key1": "value1" - } - """.trimIndent() - - private val threeAdditionalHeaders = """, - "additionalHeaders" : { - "key1": "value1", - "key2": "value2", - "key3": "value3" - } - """.trimIndent() - - private val contentTypeAdditionalHeader = """, - "additionalHeaders" : { - "${HttpHeaders.CONTENT_TYPE}": "${MediaType.APPLICATION_XML}" - } - """.trimIndent() - - private val additionalHeadersWithAuth = """, - "additionalHeaders" : { - "Authorization": "Basic aGF2ZTphbmljZWRheQo=" - } - """.trimIndent() - - private val additionalHeadersWithAuthLowercased = """, - "additionalHeaders" : { - "authorization": "Basic aGF2ZTphbmljZWRheQo=" - } - """.trimIndent() - } -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt index 6b083aaad..f06f827ad 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt @@ -19,7 +19,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.rest.relationshipTemplateRestClient import org.onap.ccsdk.cds.blueprintsprocessor.rest.relationshipTypeConnectsToRestClient -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import kotlin.test.assertEquals @@ -73,12 +73,12 @@ class RestClientPropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_REST_CLIENT}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt index e14e035a9..030996685 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt @@ -27,9 +27,9 @@ import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.rest.BlueprintRestLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BluePrintRestLibConfiguration import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration @@ -66,9 +66,9 @@ import kotlin.test.assertNotNull @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @ContextConfiguration( classes = [ - BlueprintRestLibConfiguration::class, SampleController::class, + BluePrintRestLibConfiguration::class, SampleController::class, SecurityConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -96,7 +96,7 @@ import kotlin.test.assertNotNull class RestClientServiceTest { @Autowired - lateinit var bluePrintRestLibPropertyService: BlueprintRestLibPropertyService + lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService @Autowired lateinit var httpHandler: HttpHandler diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt new file mode 100644 index 000000000..dc10722cc --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt @@ -0,0 +1,51 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.ssh + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.BluePrintSshLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.BlueprintSshClientService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintSshLibConfiguration + +/** + * Exposed Dependency Service by this SSH Lib Module + */ +fun BluePrintDependencyService.sshLibPropertyService(): BluePrintSshLibPropertyService = + instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY) + +fun BluePrintDependencyService.sshClientService(selector: String): BlueprintSshClientService = + sshLibPropertyService().blueprintSshClientService(selector) + +fun BluePrintDependencyService.sshClientService(jsonNode: JsonNode): BlueprintSshClientService = + sshLibPropertyService().blueprintSshClientService(jsonNode) + +class SshLibConstants { + companion object { + + const val SERVICE_BLUEPRINT_SSH_LIB_PROPERTY = "blueprint-ssh-lib-property-service" + const val PROPERTY_SSH_CLIENT_PREFIX = "blueprintsprocessor.sshclient." + const val TYPE_BASIC_AUTH = "basic-auth" + } +} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt new file mode 100644 index 000000000..295021f21 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt @@ -0,0 +1,34 @@ +/* + * Copyright © 2019 IBM. + * + * Modifications Copyright © 2020 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.ssh + +open class SshClientProperties { + + lateinit var type: String + lateinit var host: String + var port: Int = 22 + var connectionTimeOut: Long = 3000 + var logging: Boolean = false // print command result in cds logs +} + +open class BasicAuthSshClientProperties : SshClientProperties() { + + lateinit var password: String + lateinit var username: String +} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibConfiguration.kt deleted file mode 100644 index 7b471870b..000000000 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibConfiguration.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.ssh - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.BlueprintSshLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.BlueprintSshClientService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BlueprintSshLibConfiguration - -/** - * Exposed Dependency Service by this SSH Lib Module - */ -fun BlueprintDependencyService.sshLibPropertyService(): BlueprintSshLibPropertyService = - instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY) - -fun BlueprintDependencyService.sshClientService(selector: String): BlueprintSshClientService = - sshLibPropertyService().blueprintSshClientService(selector) - -fun BlueprintDependencyService.sshClientService(jsonNode: JsonNode): BlueprintSshClientService = - sshLibPropertyService().blueprintSshClientService(jsonNode) - -class SshLibConstants { - companion object { - - const val SERVICE_BLUEPRINT_SSH_LIB_PROPERTY = "blueprint-ssh-lib-property-service" - const val PROPERTY_SSH_CLIENT_PREFIX = "blueprintsprocessor.sshclient." - const val TYPE_BASIC_AUTH = "basic-auth" - } -} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibData.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibData.kt deleted file mode 100644 index 295021f21..000000000 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BlueprintSshLibData.kt +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Modifications Copyright © 2020 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.ssh - -open class SshClientProperties { - - lateinit var type: String - lateinit var host: String - var port: Int = 22 - var connectionTimeOut: Long = 3000 - var logging: Boolean = false // print command result in cds logs -} - -open class BasicAuthSshClientProperties : SshClientProperties() { - - lateinit var password: String - lateinit var username: String -} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSL.kt index 256924c5f..a7702d4fb 100644 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSL.kt +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSL.kt @@ -19,8 +19,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.ssh import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType @@ -32,25 +32,25 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipType /** Relationships Types DSL for Message Producer */ fun ServiceTemplateBuilder.relationshipTypeConnectsToSshClient() { - val relationshipType = BlueprintTypes.relationshipTypeConnectsToSshClient() + val relationshipType = BluePrintTypes.relationshipTypeConnectsToSshClient() if (this.relationshipTypes == null) this.relationshipTypes = hashMapOf() this.relationshipTypes!![relationshipType.id!!] = relationshipType } -fun BlueprintTypes.relationshipTypeConnectsToSshClient(): RelationshipType { +fun BluePrintTypes.relationshipTypeConnectsToSshClient(): RelationshipType { return relationshipType( - id = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT, - version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, + id = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT, + version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO, description = "Relationship connects to through SSH Client." ) { property( - BlueprintConstants.PROPERTY_CONNECTION_CONFIG, - BlueprintConstants.DATA_TYPE_MAP, + BluePrintConstants.PROPERTY_CONNECTION_CONFIG, + BluePrintConstants.DATA_TYPE_MAP, true, "Connection Config details." ) - validTargetTypes(arrayListOf(BlueprintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) + validTargetTypes(arrayListOf(BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_ENDPOINT)) } } @@ -68,15 +68,15 @@ fun TopologyTemplateBuilder.relationshipTemplateSshClient( open class SshRelationshipTemplateBuilder(name: String, description: String) : RelationshipTemplateBuilder( name, - BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT, description + BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT, description ) { fun basicAuth(block: BasicAuthSshClientPropertiesAssignmentBuilder.() -> Unit) { - property(BlueprintConstants.PROPERTY_CONNECTION_CONFIG, BlueprintTypes.basicAuthSshProperties(block)) + property(BluePrintConstants.PROPERTY_CONNECTION_CONFIG, BluePrintTypes.basicAuthSshProperties(block)) } } -fun BlueprintTypes.basicAuthSshProperties(block: BasicAuthSshClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { +fun BluePrintTypes.basicAuthSshProperties(block: BasicAuthSshClientPropertiesAssignmentBuilder.() -> Unit): JsonNode { val sshProperties = BasicAuthSshClientPropertiesAssignmentBuilder().apply(block).build() sshProperties[SshClientProperties::type.name] = SshLibConstants.TYPE_BASIC_AUTH.asJsonPrimitive() return sshProperties.asJsonType() diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt index 46756e63a..6ee73c238 100644 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt @@ -25,7 +25,7 @@ import org.apache.sshd.client.channel.ClientChannelEvent import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier import org.apache.sshd.client.session.ClientSession import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream import java.io.IOException @@ -76,7 +76,7 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B channel!!.err = ByteArrayOutputStream() channel!!.open() } catch (e: Exception) { - throw BlueprintProcessorException("Failed to start Shell channel: ${e.message}") + throw BluePrintProcessorException("Failed to start Shell channel: ${e.message}") } } @@ -97,7 +97,7 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B } } } catch (e: Exception) { - throw BlueprintProcessorException("Failed to execute commands, below the error message : ${e.message}") + throw BluePrintProcessorException("Failed to execute commands, below the error message : ${e.message}") } return response } @@ -111,7 +111,7 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B teeOutput!!.flush() deviceOutput = waitForPrompt(timeOut) } catch (e: IOException) { - throw BlueprintProcessorException("Exception during command execution: ${e.message}", e) + throw BluePrintProcessorException("Exception during command execution: ${e.message}", e) } if (detectFailure(deviceOutput)) { @@ -130,7 +130,7 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B Collections.unmodifiableSet(EnumSet.of(ClientChannelEvent.CLOSED)), timeOut ) if (channel!!.out.toString().indexOfAny(arrayListOf("$", ">", "#")) <= 0 && waitMask.contains(ClientChannelEvent.TIMEOUT)) { - throw BlueprintProcessorException("Timeout: Failed to retrieve commands result in $timeOut ms") + throw BluePrintProcessorException("Timeout: Failed to retrieve commands result in $timeOut ms") } val outputResult = channel!!.out.toString() channel!!.out.flush() diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt new file mode 100644 index 000000000..90a1746e8 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.ssh.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.SshClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.SshLibConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY) +open class BluePrintSshLibPropertyService(private var bluePrintProperties: BluePrintPropertiesService) { + + fun blueprintSshClientService(jsonNode: JsonNode): BlueprintSshClientService { + val restClientProperties = sshClientProperties(jsonNode) + return blueprintSshClientService(restClientProperties) + } + + fun blueprintSshClientService(selector: String): BlueprintSshClientService { + val prefix = "${SshLibConstants.PROPERTY_SSH_CLIENT_PREFIX}$selector" + val sshClientProperties = sshClientProperties(prefix) + return blueprintSshClientService(sshClientProperties) + } + + fun sshClientProperties(prefix: String): SshClientProperties { + val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) + return when (type) { + SshLibConstants.TYPE_BASIC_AUTH -> { + basicAuthSshClientProperties(prefix) + } + else -> { + throw BluePrintProcessorException("SSH adaptor($type) is not supported") + } + } + } + + fun sshClientProperties(jsonNode: JsonNode): SshClientProperties { + val type = jsonNode.get("type")?.textValue() + ?: throw BluePrintProcessorException("missing type field in ssh client properties") + return when (type) { + SshLibConstants.TYPE_BASIC_AUTH -> { + JacksonUtils.readValue( + jsonNode, + BasicAuthSshClientProperties::class.java + )!! + } + else -> { + throw BluePrintProcessorException("SSH adaptor($type) is not supported") + } + } + } + + private fun blueprintSshClientService(sshClientProperties: SshClientProperties): BlueprintSshClientService { + + when (sshClientProperties) { + is BasicAuthSshClientProperties -> { + return BasicAuthSshClientService(sshClientProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get SSH client service for") + } + } + } + + private fun basicAuthSshClientProperties(prefix: String): BasicAuthSshClientProperties { + return bluePrintProperties.propertyBeanType( + prefix, BasicAuthSshClientProperties::class.java + ) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyService.kt deleted file mode 100644 index 4803d5f52..000000000 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyService.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.ssh.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.SshClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.SshLibConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY) -open class BlueprintSshLibPropertyService(private var bluePrintProperties: BlueprintPropertiesService) { - - fun blueprintSshClientService(jsonNode: JsonNode): BlueprintSshClientService { - val restClientProperties = sshClientProperties(jsonNode) - return blueprintSshClientService(restClientProperties) - } - - fun blueprintSshClientService(selector: String): BlueprintSshClientService { - val prefix = "${SshLibConstants.PROPERTY_SSH_CLIENT_PREFIX}$selector" - val sshClientProperties = sshClientProperties(prefix) - return blueprintSshClientService(sshClientProperties) - } - - fun sshClientProperties(prefix: String): SshClientProperties { - val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - SshLibConstants.TYPE_BASIC_AUTH -> { - basicAuthSshClientProperties(prefix) - } - else -> { - throw BlueprintProcessorException("SSH adaptor($type) is not supported") - } - } - } - - fun sshClientProperties(jsonNode: JsonNode): SshClientProperties { - val type = jsonNode.get("type")?.textValue() - ?: throw BlueprintProcessorException("missing type field in ssh client properties") - return when (type) { - SshLibConstants.TYPE_BASIC_AUTH -> { - JacksonUtils.readValue( - jsonNode, - BasicAuthSshClientProperties::class.java - )!! - } - else -> { - throw BlueprintProcessorException("SSH adaptor($type) is not supported") - } - } - } - - private fun blueprintSshClientService(sshClientProperties: SshClientProperties): BlueprintSshClientService { - - when (sshClientProperties) { - is BasicAuthSshClientProperties -> { - return BasicAuthSshClientService(sshClientProperties) - } - else -> { - throw BlueprintProcessorException("couldn't get SSH client service for") - } - } - } - - private fun basicAuthSshClientProperties(prefix: String): BasicAuthSshClientProperties { - return bluePrintProperties.propertyBeanType( - prefix, BasicAuthSshClientProperties::class.java - ) - } -} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSLTest.kt index 510dc7de8..85891b1b5 100644 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSLTest.kt +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/SshPropertiesDSLTest.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.ssh import org.junit.Test -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.dsl.relationshipTypeConnectsTo import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import kotlin.test.assertEquals @@ -53,12 +53,12 @@ class SshPropertiesDSLTest { assertNotNull(relationshipTypes, "failed to get relationship types") assertEquals(2, relationshipTypes.size, "relationshipTypes doesn't match") assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO}" ) assertNotNull( - relationshipTypes[BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT], - "failed to get ${BlueprintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT}" + relationshipTypes[BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT], + "failed to get ${BluePrintConstants.MODEL_TYPE_RELATIONSHIPS_CONNECTS_TO_SSH_CLIENT}" ) } } diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt new file mode 100644 index 000000000..43a997ae9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.ssh.service + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BluePrintSshLibConfiguration +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintSshLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class + ] +) +@TestPropertySource( + properties = + [ + "blueprintsprocessor.sshclient.sample.type=basic-auth", + "blueprintsprocessor.sshclient.sample.host=127.0.0.1", + "blueprintsprocessor.sshclient.sample.port=22", + "blueprintsprocessor.sshclient.sample.password=1234", + "blueprintsprocessor.sshclient.sample.username=dummy" + ] +) +class BluePrintSshLibPropertyServiceTest { + + @Autowired + lateinit var bluePrintSshLibPropertyService: BluePrintSshLibPropertyService + + @Test + fun testRestClientProperties() { + val properties = bluePrintSshLibPropertyService + .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties + assertNotNull(properties, "failed to create property bean") + assertEquals(properties.host, "127.0.0.1", "failed to match host property") + assertEquals(properties.port, 22, "failed to match port property") + assertEquals(properties.password, "1234", "failed to match host property") + assertEquals(properties.username, "dummy", "failed to match host property") + } +} diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt index 1c9d8d14b..1cf0de52b 100644 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt +++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt @@ -28,9 +28,9 @@ import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider import org.apache.sshd.server.session.ServerSession import org.apache.sshd.server.shell.ProcessShellCommandFactory import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BlueprintSshLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BluePrintSshLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.ssh.service.echoShell.EchoShellFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -47,8 +47,8 @@ import kotlin.test.assertTrue @RunWith(SpringRunner::class) @ContextConfiguration( classes = [ - BlueprintSshLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class + BluePrintSshLibConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class ] ) @TestPropertySource( @@ -64,9 +64,9 @@ import kotlin.test.assertTrue class BlueprintSshClientServiceTest { @Autowired - lateinit var bluePrintSshLibPropertyService: BlueprintSshLibPropertyService + lateinit var bluePrintSshLibPropertyService: BluePrintSshLibPropertyService - lateinit var bluePrintSshLibPropertyServiceMock: BlueprintSshLibPropertyService + lateinit var bluePrintSshLibPropertyServiceMock: BluePrintSshLibPropertyService private lateinit var sshServer: SshServer diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyServiceTest.kt deleted file mode 100644 index 88c734aa4..000000000 --- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshLibPropertyServiceTest.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.ssh.service - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BlueprintSshLibConfiguration -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintSshLibConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class - ] -) -@TestPropertySource( - properties = - [ - "blueprintsprocessor.sshclient.sample.type=basic-auth", - "blueprintsprocessor.sshclient.sample.host=127.0.0.1", - "blueprintsprocessor.sshclient.sample.port=22", - "blueprintsprocessor.sshclient.sample.password=1234", - "blueprintsprocessor.sshclient.sample.username=dummy" - ] -) -class BlueprintSshLibPropertyServiceTest { - - @Autowired - lateinit var bluePrintSshLibPropertyService: BlueprintSshLibPropertyService - - @Test - fun testRestClientProperties() { - val properties = bluePrintSshLibPropertyService - .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties - assertNotNull(properties, "failed to create property bean") - assertEquals(properties.host, "127.0.0.1", "failed to match host property") - assertEquals(properties.port, 22, "failed to match port property") - assertEquals(properties.password, "1234", "failed to match host property") - assertEquals(properties.username, "dummy", "failed to match host property") - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt index 58d5726bb..634c3368b 100644 --- a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt @@ -19,8 +19,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.configs.api import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest @@ -35,7 +35,7 @@ import org.springframework.web.reactive.function.BodyInserters @RunWith(SpringRunner::class) @WebFluxTest @ContextConfiguration( - classes = [BlueprintCoreConfiguration::class, BlueprintCatalogService::class, ErrorCatalogTestConfiguration::class] + classes = [BluePrintCoreConfiguration::class, BluePrintCatalogService::class, ErrorCatalogTestConfiguration::class] ) @ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) @TestPropertySource(locations = ["classpath:application-test.properties"]) diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt index 9567ebc88..ee4c0a544 100644 --- a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.configs.api -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution", diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt new file mode 100644 index 000000000..54f8dbc9d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt @@ -0,0 +1,320 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api + +import com.google.protobuf.ByteString +import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BluePrintModelHandler +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString +import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull +import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk +import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.GrpcErrorCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault +import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService +import org.slf4j.LoggerFactory +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.stereotype.Service + +// TODO("Convert to coroutines handler") +@Service +open class BluePrintManagementGRPCHandler( + private val bluePrintModelHandler: BluePrintModelHandler, + private val errorCatalogService: ErrorCatalogService +) : + BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() { + + private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java) + + @PreAuthorize("hasRole('USER')") + override fun uploadBlueprint( + request: BluePrintUploadInput, + responseObserver: StreamObserver + ) { + + runBlocking { + // TODO("catch if request id is missing") + log.info("request(${request.commonHeader.requestId})") + try { + /** Get the file byte array */ + val byteArray = request.fileChunk.chunk.toByteArray() + + /** Get the Upload Action */ + val uploadAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: UploadAction.DRAFT.toString() + + when (uploadAction) { + UploadAction.DRAFT.toString() -> { + val blueprintModel = bluePrintModelHandler.upload(byteArray, false) + responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) + } + UploadAction.PUBLISH.toString() -> { + val blueprintModel = bluePrintModelHandler.upload(byteArray, true) + responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) + } + UploadAction.VALIDATE.toString() -> { + // TODO("Not Implemented") + responseObserver.onNext( + failStatus( + request.commonHeader, + "Upload action($uploadAction) not implemented", + BluePrintProcessorException("Not Implemented") + ) + ) + } + UploadAction.ENRICH.toString() -> { + val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray) + responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Upload action($uploadAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to upload CBA", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + @PreAuthorize("hasRole('USER')") + override fun downloadBlueprint( + request: BluePrintDownloadInput, + responseObserver: StreamObserver + ) { + runBlocking { + val blueprintName = request.actionIdentifiers.blueprintName + val blueprintVersion = request.actionIdentifiers.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + /** Get the Search Action */ + val searchAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: DownloadAction.SEARCH.toString() + + log.info("request(${request.commonHeader.requestId}): Received download $blueprint") + try { + when (searchAction) { + DownloadAction.SEARCH.toString() -> { + val downloadByteArray = bluePrintModelHandler.download(blueprintName, blueprintVersion) + responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Search action($searchAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + @PreAuthorize("hasRole('USER')") + override fun removeBlueprint( + request: BluePrintRemoveInput, + responseObserver: + StreamObserver + ) { + + runBlocking { + val blueprintName = request.actionIdentifiers.blueprintName + val blueprintVersion = request.actionIdentifiers.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") + + /** Get the Remove Action */ + val removeAction = request.actionIdentifiers?.actionName.emptyTONull() + ?: RemoveAction.DEFAULT.toString() + + try { + when (removeAction) { + RemoveAction.DEFAULT.toString() -> { + bluePrintModelHandler.deleteBlueprintModel(blueprintName, blueprintVersion) + responseObserver.onNext(successStatus(request.commonHeader)) + } + else -> { + responseObserver.onNext( + failStatus( + request.commonHeader, + "Remove action($removeAction) not implemented", + BluePrintProcessorException("Not implemented") + ) + ) + } + } + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + override fun bootstrapBlueprint( + request: BluePrintBootstrapInput, + responseObserver: StreamObserver + ) { + runBlocking { + try { + log.info("request(${request.commonHeader.requestId}): Received bootstrap request") + val bootstrapRequest = BootstrapRequest().apply { + loadModelType = request.loadModelType + loadResourceDictionary = request.loadResourceDictionary + loadCBA = request.loadCBA + } + /** Perform bootstrap of Model Types, Resource Definitions and CBA */ + bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest) + responseObserver.onNext(successStatus(request.commonHeader)) + } catch (e: Exception) { + responseObserver.onNext( + failStatus( + request.commonHeader, + "request(${request.commonHeader.requestId}): Failed to bootstrap", e + ) + ) + } finally { + responseObserver.onCompleted() + } + } + } + + private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BluePrintManagementOutput = + BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray))) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .setMessage(BluePrintConstants.STATUS_SUCCESS) + .setCode(200) + .build() + ) + .build() + + private fun successStatus(header: CommonHeader, propertyContent: String? = null): BluePrintManagementOutput { + // Populate Response Payload + val propertiesBuilder = BluePrintManagementOutput.newBuilder().propertiesBuilder + propertyContent?.let { + JsonFormat.parser().merge(propertyContent, propertiesBuilder) + } + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setProperties(propertiesBuilder.build()) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_SUCCESS) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .setCode(200) + .build() + ) + .build() + } + + private fun failStatus(header: CommonHeader, message: String, e: Exception): BluePrintManagementOutput { + log.error(message, e) + return if (e is BluePrintProcessorException) onErrorCatalog(header, message, e) else onError(header, message, e) + } + + private fun onError(header: CommonHeader, message: String, error: Exception): BluePrintManagementOutput { + val code = GrpcErrorCodes.code(ErrorCatalogCodes.GENERIC_FAILURE) + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_FAILURE) + .setEventType(EventType.EVENT_COMPONENT_FAILURE) + .setErrorMessage("Error : $message \n Details: ${error.errorMessageOrDefault()}") + .setCode(code) + .build() + ) + .build() + } + + private fun onErrorCatalog(header: CommonHeader, message: String, error: BluePrintProcessorException): + BluePrintManagementOutput { + val err = if (error.protocol == "") { + error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) + } else { + error.convertToGrpc() + } + val errorPayload = errorCatalogService.errorPayload(err.addErrorPayloadMessage(message)) + return BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus( + Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(BluePrintConstants.STATUS_FAILURE) + .setEventType(EventType.EVENT_COMPONENT_FAILURE) + .setErrorMessage("Error : ${errorPayload.message}") + .setCode(errorPayload.code) + .build() + ) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt deleted file mode 100644 index 97e43ec89..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandler.kt +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api - -import com.google.protobuf.ByteString -import com.google.protobuf.util.JsonFormat -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BlueprintModelHandler -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString -import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull -import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintBootstrapInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintDownloadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementOutput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintRemoveInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk -import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.GrpcErrorCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault -import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService -import org.slf4j.LoggerFactory -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.stereotype.Service - -// TODO("Convert to coroutines handler") -@Service -open class BlueprintManagementGRPCHandler( - private val bluePrintModelHandler: BlueprintModelHandler, - private val errorCatalogService: ErrorCatalogService -) : - BlueprintManagementServiceGrpc.BlueprintManagementServiceImplBase() { - - private val log = LoggerFactory.getLogger(BlueprintManagementGRPCHandler::class.java) - - @PreAuthorize("hasRole('USER')") - override fun uploadBlueprint( - request: BlueprintUploadInput, - responseObserver: StreamObserver - ) { - - runBlocking { - // TODO("catch if request id is missing") - log.info("request(${request.commonHeader.requestId})") - try { - /** Get the file byte array */ - val byteArray = request.fileChunk.chunk.toByteArray() - - /** Get the Upload Action */ - val uploadAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: UploadAction.DRAFT.toString() - - when (uploadAction) { - UploadAction.DRAFT.toString() -> { - val blueprintModel = bluePrintModelHandler.upload(byteArray, false) - responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) - } - UploadAction.PUBLISH.toString() -> { - val blueprintModel = bluePrintModelHandler.upload(byteArray, true) - responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString())) - } - UploadAction.VALIDATE.toString() -> { - // TODO("Not Implemented") - responseObserver.onNext( - failStatus( - request.commonHeader, - "Upload action($uploadAction) not implemented", - BlueprintProcessorException("Not Implemented") - ) - ) - } - UploadAction.ENRICH.toString() -> { - val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray) - responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Upload action($uploadAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to upload CBA", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - @PreAuthorize("hasRole('USER')") - override fun downloadBlueprint( - request: BlueprintDownloadInput, - responseObserver: StreamObserver - ) { - runBlocking { - val blueprintName = request.actionIdentifiers.blueprintName - val blueprintVersion = request.actionIdentifiers.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - /** Get the Search Action */ - val searchAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: DownloadAction.SEARCH.toString() - - log.info("request(${request.commonHeader.requestId}): Received download $blueprint") - try { - when (searchAction) { - DownloadAction.SEARCH.toString() -> { - val downloadByteArray = bluePrintModelHandler.download(blueprintName, blueprintVersion) - responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Search action($searchAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - @PreAuthorize("hasRole('USER')") - override fun removeBlueprint( - request: BlueprintRemoveInput, - responseObserver: - StreamObserver - ) { - - runBlocking { - val blueprintName = request.actionIdentifiers.blueprintName - val blueprintVersion = request.actionIdentifiers.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") - - /** Get the Remove Action */ - val removeAction = request.actionIdentifiers?.actionName.emptyTONull() - ?: RemoveAction.DEFAULT.toString() - - try { - when (removeAction) { - RemoveAction.DEFAULT.toString() -> { - bluePrintModelHandler.deleteBlueprintModel(blueprintName, blueprintVersion) - responseObserver.onNext(successStatus(request.commonHeader)) - } - else -> { - responseObserver.onNext( - failStatus( - request.commonHeader, - "Remove action($removeAction) not implemented", - BlueprintProcessorException("Not implemented") - ) - ) - } - } - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - override fun bootstrapBlueprint( - request: BlueprintBootstrapInput, - responseObserver: StreamObserver - ) { - runBlocking { - try { - log.info("request(${request.commonHeader.requestId}): Received bootstrap request") - val bootstrapRequest = BootstrapRequest().apply { - loadModelType = request.loadModelType - loadResourceDictionary = request.loadResourceDictionary - loadCBA = request.loadCBA - } - /** Perform bootstrap of Model Types, Resource Definitions and CBA */ - bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest) - responseObserver.onNext(successStatus(request.commonHeader)) - } catch (e: Exception) { - responseObserver.onNext( - failStatus( - request.commonHeader, - "request(${request.commonHeader.requestId}): Failed to bootstrap", e - ) - ) - } finally { - responseObserver.onCompleted() - } - } - } - - private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BlueprintManagementOutput = - BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray))) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .setMessage(BlueprintConstants.STATUS_SUCCESS) - .setCode(200) - .build() - ) - .build() - - private fun successStatus(header: CommonHeader, propertyContent: String? = null): BlueprintManagementOutput { - // Populate Response Payload - val propertiesBuilder = BlueprintManagementOutput.newBuilder().propertiesBuilder - propertyContent?.let { - JsonFormat.parser().merge(propertyContent, propertiesBuilder) - } - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setProperties(propertiesBuilder.build()) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_SUCCESS) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .setCode(200) - .build() - ) - .build() - } - - private fun failStatus(header: CommonHeader, message: String, e: Exception): BlueprintManagementOutput { - log.error(message, e) - return if (e is BlueprintProcessorException) onErrorCatalog(header, message, e) else onError(header, message, e) - } - - private fun onError(header: CommonHeader, message: String, error: Exception): BlueprintManagementOutput { - val code = GrpcErrorCodes.code(ErrorCatalogCodes.GENERIC_FAILURE) - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_FAILURE) - .setEventType(EventType.EVENT_COMPONENT_FAILURE) - .setErrorMessage("Error : $message \n Details: ${error.errorMessageOrDefault()}") - .setCode(code) - .build() - ) - .build() - } - - private fun onErrorCatalog(header: CommonHeader, message: String, error: BlueprintProcessorException): - BlueprintManagementOutput { - val err = if (error.protocol == "") { - error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) - } else { - error.convertToGrpc() - } - val errorPayload = errorCatalogService.errorPayload(err.addErrorPayloadMessage(message)) - return BlueprintManagementOutput.newBuilder() - .setCommonHeader(header) - .setStatus( - Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(BlueprintConstants.STATUS_FAILURE) - .setEventType(EventType.EVENT_COMPONENT_FAILURE) - .setErrorMessage("Error : ${errorPayload.message}") - .setCode(errorPayload.code) - .build() - ) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt index f19824d47..66d4b0e16 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt @@ -25,10 +25,10 @@ import io.swagger.annotations.ApiResponse import io.swagger.annotations.ApiResponses import org.jetbrains.annotations.NotNull import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BlueprintModelHandler +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.BluePrintModelHandler import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintSortByOption import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString import org.springframework.core.io.Resource import org.springframework.data.domain.Page @@ -62,7 +62,7 @@ import org.springframework.web.bind.annotation.RestController value = "Blueprint Model Catalog", description = "Manages all blueprint models which are available in CDS" ) -open class BlueprintModelController(private val bluePrintModelHandler: BlueprintModelHandler) { +open class BlueprintModelController(private val bluePrintModelHandler: BluePrintModelHandler) { @PostMapping( path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE), @@ -79,7 +79,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 500, message = "Internal Server Error") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun bootstrap( @ApiParam(required = true, value = "Specifies which elements to load") @@ -100,7 +100,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 500, message = "Internal Server Error") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun saveBlueprint( @ApiParam(name = "file", value = "CBA file to be uploaded (example: cba.zip)", required = true) @@ -162,7 +162,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint @PathVariable(value = "keyword") keyWord: String ): List = mdcWebCoroutineScope { - bluePrintModelHandler.searchBlueprintModelsByKeyWord(keyWord) + bluePrintModelHandler.searchBluePrintModelsByKeyWord(keyWord) } @GetMapping("/paged/meta-data/{keyword}", produces = [MediaType.APPLICATION_JSON_VALUE]) @@ -186,7 +186,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint offset, limit, Sort.Direction.fromString(sortType), sort.columnName ) - return this.bluePrintModelHandler.searchBlueprintModelsByKeyWordPaged(keyWord, pageRequest) + return this.bluePrintModelHandler.searchBluePrintModelsByKeyWordPaged(keyWord, pageRequest) } @DeleteMapping("/{id}") @@ -198,7 +198,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 200, message = "OK"), ApiResponse(code = 404, message = "RESOURCE_NOT_FOUND") ) - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun deleteBlueprint( @ApiParam(value = "ID of the blueprint model to delete", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @@ -218,7 +218,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getBlueprintByNameAndVersion( @ApiParam(value = "Name of the blueprint model", required = true, example = "pnf_netconf") @PathVariable(value = "name") name: String, @@ -242,7 +242,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun downloadBlueprintByNameAndVersion( @ApiParam(value = "Name of the blueprint model", required = true, example = "pnf_netconf") @PathVariable(value = "name") name: String, @@ -262,7 +262,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getBlueprintModel( @ApiParam(value = "ID of the blueprint model to search for", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @@ -281,9 +281,9 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 404, message = "Not Found") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") - suspend fun downloadBlueprint( + suspend fun downloadBluePrint( @ApiParam(value = "ID of the blueprint model to download", required = true, example = "67ec1f96-ab55-4b81-aff9-23ee0ed1d7a4") @PathVariable(value = "id") id: String ): ResponseEntity = @@ -304,7 +304,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint "The enrichment process will complete the package by providing all the definition of types used." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun enrichBlueprint( @ApiParam(name = "file", value = "CBA zip file to be uploaded (example: cba_unenriched.zip)", required = true) @@ -330,7 +330,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint ApiResponse(code = 503, message = "Service Unavailable") ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun enrichAndPubishlueprint( @ApiParam(name = "file", value = "Unenriched CBA zip file to be uploaded (example: cba_unenriched.zip)", required = true) @@ -346,7 +346,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint response = BlueprintModelSearch::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun publishBlueprint( @ApiParam(name = "file", value = "Enriched CBA zip file to be uploaded (example: cba_enriched.zip)", required = true) @@ -405,7 +405,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint "Inputs, outputs and data types of workflow is returned." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun workflowSpec( @ApiParam(required = true, value = "Blueprint and workflow identification") @@ -428,7 +428,7 @@ open class BlueprintModelController(private val bluePrintModelHandler: Blueprint notes = "Get all available workflows of a Blueprint identified by its name and version." ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) @PreAuthorize("hasRole('USER')") suspend fun getWorkflowList( @ApiParam(value = "Name of the blueprint model", example = "pnf_netconf", required = true) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt index 5406b7792..741a9115c 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt @@ -20,9 +20,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.DATA_TYPE_JSON -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.DEFAULT_VERSION_NUMBER -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants.TOSCA_SPEC +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.DATA_TYPE_JSON +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.DEFAULT_VERSION_NUMBER +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.TOSCA_SPEC import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt index eb9a98091..3689f735e 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt @@ -22,7 +22,7 @@ import io.swagger.annotations.ApiOperation import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.springframework.http.MediaType import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping @@ -86,7 +86,7 @@ open class ModelTypeController(private val modelTypeHandler: ModelTypeHandler) { response = ModelType::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveModelType(@RequestBody modelType: ModelType): ModelType = mdcWebCoroutineScope { modelTypeHandler.saveModel(modelType) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt index 62997cc1b..8d69ccdde 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt @@ -22,7 +22,7 @@ import io.swagger.annotations.ApiParam import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ResourceDictionaryHandler import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping import org.springframework.http.MediaType @@ -50,7 +50,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDictionary::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun getResourceDictionaryByName( @ApiParam(value = "Name of the resource", required = true, example = "\"hostname\"") @PathVariable(value = "name") name: String @@ -69,7 +69,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDictionary::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary( @ApiParam(value = "Resource dictionary to store", required = true) @RequestBody dataDictionary: ResourceDictionary @@ -90,7 +90,7 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R response = ResourceDefinition::class ) @ResponseBody - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary( @ApiParam(value = "Resource definition to generate", required = true) @RequestBody resourceDefinition: ResourceDefinition diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..c63c7260d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt @@ -0,0 +1,92 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.springframework.stereotype.Service + +@Service +open class BluePrintArtifactDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService +) : + BluePrintArtifactDefinitionEnhancer { + + companion object { + + const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" + } + + private val log = logger(BluePrintArtifactDefinitionEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) { + log.info("enhancing ArtifactDefinition($name)") + + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val artifactTypeName = artifactDefinition.type + ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)") + + // Populate Artifact Type + BluePrintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName) + + when (artifactTypeName) { + ARTIFACT_TYPE_MAPPING_SOURCE -> { + enhanceMappingType(name, artifactDefinition) + } + } + } + + // Enhance Resource Mapping + open fun enhanceMappingType(name: String, artifactDefinition: ArtifactDefinition) { + + val artifactFilePath = "${bluePrintContext.rootPath}/${artifactDefinition.file}" + + val alreadyEnhancedKey = "enhanced-${artifactDefinition.file}" + val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) + + log.info("enhancing resource mapping file(${artifactDefinition.file}) already enhanced($alreadyEnhanced)") + + if (!alreadyEnhanced) { + val resourceAssignments: MutableList = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java) + as? MutableList + ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)") + + // Call Resource Assignment Enhancer + resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) + + bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..030fbe8ae --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + +class BluePrintAttributeDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintAttributeDefinitionEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val propertyType = attributeDefinition.type + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) { + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + val entrySchema = attributeDefinition.entrySchema + ?: throw BluePrintException("Entry Schema is missing for collection property($name)") + + if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) + } + } else { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt new file mode 100644 index 000000000..8240b1de1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt @@ -0,0 +1,103 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault +import org.springframework.stereotype.Service +import java.io.IOException +import java.util.UUID + +@Service +open class BluePrintEnhancerServiceImpl( + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService +) : BluePrintEnhancerService { + + private val log = logger(BluePrintEnhancerServiceImpl::class) + + override suspend fun enhance(basePath: String, enrichedBasePath: String): BluePrintContext { + + // Copy the Blueprint Content to Target Location + BluePrintFileUtils.copyBluePrint(basePath, enrichedBasePath) + + // Enhance the Blueprint + return enhance(enrichedBasePath) + } + + @Throws(BluePrintException::class) + override suspend fun enhance(basePath: String): BluePrintContext { + + log.info("Enhancing blueprint($basePath)") + val blueprintRuntimeService = BluePrintMetadataUtils + .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath) + + try { + + bluePrintTypeEnhancerService.enhanceServiceTemplate( + blueprintRuntimeService, "service_template", + blueprintRuntimeService.bluePrintContext().serviceTemplate + ) + + log.info("##### Enhancing blueprint Resource Definitions") + val resourceDefinitions = resourceDefinitionEnhancerService.enhance( + bluePrintTypeEnhancerService, + blueprintRuntimeService + ) + + // Write the Enhanced Blueprint Definitions + BluePrintFileUtils.writeEnhancedBluePrint(blueprintRuntimeService.bluePrintContext()) + + // Write the Enhanced Blueprint Resource Definitions + ResourceDictionaryUtils.writeResourceDefinitionTypes(basePath, resourceDefinitions) + + if (blueprintRuntimeService.getBluePrintError().allErrors().isNotEmpty()) { + throw BluePrintException(blueprintRuntimeService.getBluePrintError().allErrors().toString()) + } + } catch (e: BluePrintProcessorException) { + val errorMsg = "Error while enriching the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong blueprint definitions or resource definitions." + ) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "IO Error: CBA file failed enrichment - ${e.message}", e.errorCauseOrDefault() + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Enriching CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + return blueprintRuntimeService.bluePrintContext() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt new file mode 100644 index 000000000..6ca0b2d14 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintNodeTemplateEnhancer { + + private val log = logger(BluePrintNodeTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { + log.info("***** Enhancing NodeTemplate($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val nodeTypeName = nodeTemplate.type + // Get NodeType from Repo and Update Service Template + val nodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName) + + // Enrich NodeType + bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) + + // Enrich Node Template Artifacts + enhanceNodeTemplateArtifactDefinition(name, nodeTemplate) + } + + open fun enhanceNodeTemplateArtifactDefinition(nodeTemplateName: String, nodeTemplate: NodeTemplate) { + + nodeTemplate.artifacts?.forEach { artifactDefinitionName, artifactDefinition -> + // Enhance Artifacct Definitions + bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt new file mode 100644 index 000000000..bb178b1e6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt @@ -0,0 +1,157 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintNodeTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : BluePrintNodeTypeEnhancer { + + private val log = logger(BluePrintNodeTypeEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val derivedFrom = nodeType.derivedFrom + + if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) { + val derivedFromNodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, name) + // Enrich NodeType + enhance(bluePrintRuntimeService, derivedFrom, derivedFromNodeType) + } + + // NodeType Attribute Definitions + enrichNodeTypeAttributes(name, nodeType) + + // NodeType Property Definitions + enrichNodeTypeProperties(name, nodeType) + + // NodeType Requirement + enrichNodeTypeRequirements(name, nodeType) + + // NodeType Capability + enrichNodeTypeCapabilityProperties(name, nodeType) + + // NodeType Interface + enrichNodeTypeInterfaces(name, nodeType) + } + + open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) { + nodeType.attributes?.let { + bluePrintTypeEnhancerService.enhanceAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) + } + } + + open fun enrichNodeTypeProperties(nodeTypeName: String, nodeType: NodeType) { + nodeType.properties?.let { + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) + } + } + + open fun enrichNodeTypeRequirements(nodeTypeName: String, nodeType: NodeType) { + + nodeType.requirements?.forEach { requirementName, requirementDefinition -> + // Populate Requirement Node + requirementDefinition.node?.let { requirementNodeTypeName -> + // Get Requirement NodeType from Repo and Update Service Template + val requirementNodeType = BluePrintEnhancerUtils.populateNodeType( + bluePrintContext, + bluePrintRepoService, requirementNodeTypeName + ) + // Enhance Node Type + enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType) + + // Enhance Relationship Type + val relationShipTypeName = requirementDefinition.relationship + ?: throw BluePrintException( + "couldn't get relationship name for the NodeType($nodeTypeName) " + + "Requirement($requirementName)" + ) + enrichRelationShipType(relationShipTypeName) + } + } + } + + open fun enrichNodeTypeCapabilityProperties(nodeTypeName: String, nodeType: NodeType) { + nodeType.capabilities?.forEach { _, capabilityDefinition -> + capabilityDefinition.properties?.let { properties -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, properties) + } + } + } + + open fun enrichNodeTypeInterfaces(nodeTypeName: String, nodeType: NodeType) { + nodeType.interfaces?.forEach { interfaceName, interfaceObj -> + // Populate Node type Interface Operation + log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName) + populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj) + } + } + + open fun populateNodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, interfaceObj: InterfaceDefinition) { + + interfaceObj.operations?.forEach { operationName, operation -> + enrichNodeTypeInterfaceOperationInputs(nodeTypeName, operationName, operation) + enrichNodeTypeInterfaceOperationOutputs(nodeTypeName, operationName, operation) + } + } + + open fun enrichNodeTypeInterfaceOperationInputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) { + operation.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enrichNodeTypeInterfaceOperationOutputs( + nodeTypeName: String, + operationName: String, + operation: OperationDefinition + ) { + operation.outputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + /** + * Get the Relationship Type from database and add to Blueprint Context + */ + open fun enrichRelationShipType(relationshipName: String) { + BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName) + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt new file mode 100644 index 000000000..212dc440d --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +class BluePrintPolicyTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintPolicyTypeEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: PolicyType) { + + this.bluePrintRuntimeService = bluePrintRuntimeService + + // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt new file mode 100644 index 000000000..eb7443443 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintPropertyDefinitionEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintPropertyDefinitionEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val propertyType = propertyDefinition.type + if (BluePrintTypes.validPrimitiveTypes().contains(propertyType) || + BluePrintTypes.validComplexTypes().contains(propertyType) + ) { + // Do Nothing, + } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) { + val entrySchema = propertyDefinition.entrySchema + ?: throw BluePrintException("Entry Schema is missing for collection property($name)") + + if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) + } + } else { + BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt new file mode 100644 index 000000000..c208f68e5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTemplateEnhancerImpl.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintRelationshipTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintRelationshipTemplateEnhancer { + + private val log = logger(BluePrintRelationshipTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipTemplate: RelationshipTemplate + ) { + log.info("***** Enhancing RelationshipTemplate($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val relationshipTypeName = relationshipTemplate.type + // Get RelationshipType from Repo and Update Service Template + val relationshipType = + BluePrintEnhancerUtils.populateRelationshipType( + bluePrintContext, + bluePrintRepoService, + relationshipTypeName + ) + + // Enrich NodeType + bluePrintTypeEnhancerService.enhanceRelationshipType( + bluePrintRuntimeService, + relationshipTypeName, + relationshipType + ) + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt new file mode 100644 index 000000000..b0e166090 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintRelationshipTypeEnhancerImpl.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintRelationshipTypeEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : BluePrintRelationshipTypeEnhancer { + + private val log = logger(BluePrintRelationshipTypeEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + name: String, + relationshipType: RelationshipType + ) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val derivedFrom = relationshipType.derivedFrom + + if (!BluePrintTypes.rootRelationshipTypes().contains(derivedFrom)) { + val derivedFromRelationshipType = + BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, name) + // Enrich RelationshipType + enhance(bluePrintRuntimeService, derivedFrom, derivedFromRelationshipType) + } + + // NodeType Attribute Definitions + enrichRelationshipTypeAttributes(name, relationshipType) + + // NodeType Property Definitions + enrichRelationshipTypeProperties(name, relationshipType) + + // TODO("Interface Enrichment, If needed") + } + + open fun enrichRelationshipTypeAttributes(nodeTypeName: String, relationshipType: RelationshipType) { + relationshipType.attributes?.let { + bluePrintTypeEnhancerService.enhanceAttributeDefinitions( + bluePrintRuntimeService, + relationshipType.attributes!! + ) + } + } + + open fun enrichRelationshipTypeProperties(nodeTypeName: String, relationshipType: RelationshipType) { + relationshipType.properties?.let { + bluePrintTypeEnhancerService.enhancePropertyDefinitions( + bluePrintRuntimeService, + relationshipType.properties!! + ) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt new file mode 100644 index 000000000..9f4a4592a --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : + BluePrintServiceTemplateEnhancer { + + private val log = logger(BluePrintServiceTemplateEnhancerImpl::class) + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: ServiceTemplate) { + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + initialCleanUp() + enhanceTopologyTemplate() + } + + open fun initialCleanUp() { + bluePrintContext.serviceTemplate.artifactTypes?.clear() + bluePrintContext.serviceTemplate.nodeTypes?.clear() + bluePrintContext.serviceTemplate.dataTypes?.clear() + bluePrintContext.serviceTemplate.policyTypes?.clear() + bluePrintContext.serviceTemplate.relationshipTypes?.clear() + + bluePrintContext.serviceTemplate.artifactTypes = mutableMapOf() + bluePrintContext.serviceTemplate.nodeTypes = mutableMapOf() + bluePrintContext.serviceTemplate.dataTypes = mutableMapOf() + bluePrintContext.serviceTemplate.policyTypes = mutableMapOf() + bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf() + log.info("reinitialized all type definitions") + } + + open fun enhanceTopologyTemplate() { + bluePrintContext.serviceTemplate.topologyTemplate?.let { topologyTemplate -> + bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt new file mode 100644 index 000000000..750cd0ff4 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt @@ -0,0 +1,74 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintTopologyTemplateEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService +) : + BluePrintTopologyTemplateEnhancer { + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: TopologyTemplate) { + this.bluePrintRuntimeService = bluePrintRuntimeService + + enhanceTopologyTemplateInputs(type) + enhanceTopologyTemplateNodeTemplates(type) + enhanceTopologyTemplateRelationshipTemplates(type) + enhanceTopologyTemplateWorkflows(type) + } + + open fun enhanceTopologyTemplateInputs(topologyTemplate: TopologyTemplate) { + topologyTemplate.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enhanceTopologyTemplateNodeTemplates(topologyTemplate: TopologyTemplate) { + topologyTemplate.nodeTemplates?.forEach { nodeTemplateName, nodeTemplate -> + bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) + } + } + + open fun enhanceTopologyTemplateRelationshipTemplates(topologyTemplate: TopologyTemplate) { + topologyTemplate.relationshipTemplates?.forEach { relationshipTemplateName, relationshipTemplate -> + bluePrintTypeEnhancerService.enhanceRelationshipTemplate( + bluePrintRuntimeService, + relationshipTemplateName, + relationshipTemplate + ) + } + } + + open fun enhanceTopologyTemplateWorkflows(topologyTemplate: TopologyTemplate) { + topologyTemplate.workflows?.forEach { workflowName, workflow -> + bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt new file mode 100644 index 000000000..c27c206fa --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt @@ -0,0 +1,84 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRelationshipTypeEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service + +@Service +open class BluePrintTypeEnhancerServiceImpl : BluePrintTypeEnhancerService { + + @Autowired + private lateinit var context: ApplicationContext + + override fun getServiceTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintServiceTemplateEnhancer::class.java).map { it.value } + } + + override fun getTopologyTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintTopologyTemplateEnhancer::class.java).map { it.value } + } + + override fun getWorkflowEnhancers(): List { + return context.getBeansOfType(BluePrintWorkflowEnhancer::class.java).map { it.value } + } + + override fun getNodeTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintNodeTemplateEnhancer::class.java).map { it.value } + } + + override fun getNodeTypeEnhancers(): List { + return context.getBeansOfType(BluePrintNodeTypeEnhancer::class.java).map { it.value } + } + + override fun getRelationshipTemplateEnhancers(): List { + return context.getBeansOfType(BluePrintRelationshipTemplateEnhancer::class.java).map { it.value } + } + + override fun getRelationshipTypeEnhancers(): List { + return context.getBeansOfType(BluePrintRelationshipTypeEnhancer::class.java).map { it.value } + } + + override fun getArtifactDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintArtifactDefinitionEnhancer::class.java).map { it.value } + } + + override fun getPolicyTypeEnhancers(): List { + return context.getBeansOfType(BluePrintPolicyTypeEnhancer::class.java).map { it.value } + } + + override fun getPropertyDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintPropertyDefinitionEnhancer::class.java).map { it.value } + } + + override fun getAttributeDefinitionEnhancers(): List { + return context.getBeansOfType(BluePrintAttributeDefinitionEnhancer::class.java).map { it.value } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt new file mode 100644 index 000000000..dd60acac1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt @@ -0,0 +1,233 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class BluePrintWorkflowEnhancerImpl( + private val bluePrintRepoService: BluePrintRepoService, + private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService +) : + BluePrintWorkflowEnhancer { + + private val log = logger(BluePrintWorkflowEnhancerImpl::class) + + companion object { + + const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" + const val PROPERTY_DEPENDENCY_NODE_TEMPLATES = "dependency-node-templates" + } + + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintContext: BluePrintContext + + private val workflowDataTypes: MutableMap = hashMapOf() + + override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) { + log.info("##### Enhancing Workflow($name)") + this.bluePrintRuntimeService = bluePrintRuntimeService + this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val dynamicPropertyName = "$name-properties" + if (workflow.inputs == null) { + workflow.inputs = hashMapOf() + } + // Clean Dynamic Property Field, If present + workflow.inputs?.remove(dynamicPropertyName) + + // Enrich Workflow Inputs + enhanceWorkflowInputs(name, workflow) + + // Enrich Workflow Outputs + enhanceWorkflowOutputs(name, workflow) + + // Enrich Only for Resource Assignment and Dynamic Input Properties if any + enhanceStepTargets(name, workflow) + } + + open fun enhanceWorkflowInputs(name: String, workflow: Workflow) { + + workflow.inputs?.let { inputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) + } + } + + open fun enhanceWorkflowOutputs(name: String, workflow: Workflow) { + workflow.outputs?.let { outputs -> + bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, outputs) + } + } + + private fun enhanceStepTargets(name: String, workflow: Workflow) { + + // Get the first Step Target NodeTemplate name( It may be Component or DG Node Template) + val firstNodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(name) + + val derivedFrom = bluePrintContext.nodeTemplateNodeType(firstNodeTemplateName).derivedFrom + + when { + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { + enhanceStepTargets(name, workflow, firstNodeTemplateName, false) + } + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { + enhanceStepTargets(name, workflow, firstNodeTemplateName, true) + } + else -> { + throw BluePrintProcessorException( + "couldn't execute workflow($name) step mapped " + + "to node template($firstNodeTemplateName) derived from($derivedFrom)" + ) + } + } + } + + private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) { + + val dependencyNodeTemplates: List + if (isDG) { + val dgNodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) + + // Get the Dependent Component Node Template Names + val dependencyNodeTemplateNodes = dgNodeTemplate.properties?.get(PROPERTY_DEPENDENCY_NODE_TEMPLATES) + ?: throw BluePrintException("couldn't get property($PROPERTY_DEPENDENCY_NODE_TEMPLATES) ") + + dependencyNodeTemplates = + JacksonUtils.getListFromJsonNode(dependencyNodeTemplateNodes, String::class.java) + } else { + dependencyNodeTemplates = listOf(nodeTemplateName) + } + + log.info("workflow($name) dependent component NodeTemplates($dependencyNodeTemplates)") + + // Check and Get Resource Assignment File + val resourceAssignmentArtifacts = dependencyNodeTemplates?.mapNotNull { componentNodeTemplateName -> + log.info("identified workflow($name) targets($componentNodeTemplateName)") + + val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName) + .artifacts?.filter { + it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE + }?.map { + log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)") + it.value.file + } + resourceAssignmentArtifacts + }?.flatten() + + log.info("workflow($name) resource assignment files($resourceAssignmentArtifacts") + + if (resourceAssignmentArtifacts != null && resourceAssignmentArtifacts.isNotEmpty()) { + + // Add Workflow Dynamic Property + addWorkFlowDynamicPropertyDefinitions(name, workflow) + + resourceAssignmentArtifacts.forEach { fileName -> + // Enhance Resource Assignment File + val resourceAssignmentProperties = enhanceResourceAssignmentFile(fileName!!) + // Add Workflow Dynamic DataType + addWorkFlowDynamicDataType(name, resourceAssignmentProperties) + } + } + } + + // Enhancement for Dynamic Properties, Resource Assignment Properties, Resource Sources + private fun enhanceResourceAssignmentFile(fileName: String): MutableMap { + + val filePath = "${bluePrintContext.rootPath}/$fileName" + + log.info("enriching artifacts file($filePath") + + val resourceAssignmentProperties: MutableMap = hashMapOf() + + val resourceAssignments: MutableList = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java) + as? MutableList + ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") + + val alreadyEnhancedKey = "enhanced-$fileName" + val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) + + log.info("enhancing workflow resource mapping file($fileName) already enhanced($alreadyEnhanced)") + + if (!alreadyEnhanced) { + // Call Resource Assignment Enhancer + resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) + bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) + } + + resourceAssignments.forEach { resourceAssignment -> + resourceAssignmentProperties[resourceAssignment.name] = resourceAssignment.property!! + } + return resourceAssignmentProperties + } + + private fun addWorkFlowDynamicPropertyDefinitions(name: String, workflow: Workflow) { + val dynamicPropertyName = "$name-properties" + val propertyDefinition = PropertyDefinition() + propertyDefinition.description = "Dynamic PropertyDefinition for workflow($name)." + propertyDefinition.type = "dt-$dynamicPropertyName" + propertyDefinition.required = true + // Add to Workflow Inputs + workflow.inputs?.put(dynamicPropertyName, propertyDefinition) + } + + private fun addWorkFlowDynamicDataType(workflowName: String, mappingProperties: MutableMap) { + + val dataTypeName = "dt-$workflowName-properties" + + var dynamicDataType: DataType? = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) + + if (dynamicDataType == null) { + log.info("dataType not present for the recipe({})", dataTypeName) + dynamicDataType = DataType() + dynamicDataType.version = "1.0.0" + dynamicDataType.description = "Dynamic DataType definition for workflow($workflowName)." + dynamicDataType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC + + val dataTypeProperties: MutableMap = hashMapOf() + dynamicDataType.properties = dataTypeProperties + + // Overwrite WorkFlow DataType + bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType) + } else { + log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).") + } + // Merge all the Recipe Properties + mappingProperties.forEach { (propertyName, propertyDefinition) -> + dynamicDataType.properties?.put(propertyName, propertyDefinition) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt deleted file mode 100644 index a85d71f31..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintArtifactDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.springframework.stereotype.Service - -@Service -open class BlueprintArtifactDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService -) : - BlueprintArtifactDefinitionEnhancer { - - companion object { - - const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" - } - - private val log = logger(BlueprintArtifactDefinitionEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) { - log.info("enhancing ArtifactDefinition($name)") - - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val artifactTypeName = artifactDefinition.type - ?: throw BlueprintException("artifact type is missing for ArtifactDefinition($name)") - - // Populate Artifact Type - BlueprintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName) - - when (artifactTypeName) { - ARTIFACT_TYPE_MAPPING_SOURCE -> { - enhanceMappingType(name, artifactDefinition) - } - } - } - - // Enhance Resource Mapping - open fun enhanceMappingType(name: String, artifactDefinition: ArtifactDefinition) { - - val artifactFilePath = "${bluePrintContext.rootPath}/${artifactDefinition.file}" - - val alreadyEnhancedKey = "enhanced-${artifactDefinition.file}" - val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) - - log.info("enhancing resource mapping file(${artifactDefinition.file}) already enhanced($alreadyEnhanced)") - - if (!alreadyEnhanced) { - val resourceAssignments: MutableList = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java) - as? MutableList - ?: throw BlueprintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)") - - // Call Resource Assignment Enhancer - resourceAssignmentEnhancerService.enhanceBlueprint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) - - bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt deleted file mode 100644 index cd05c62e1..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintAttributeDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService - -class BlueprintAttributeDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintAttributeDefinitionEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val propertyType = attributeDefinition.type - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType)) { - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { - val entrySchema = attributeDefinition.entrySchema - ?: throw BlueprintException("Entry Schema is missing for collection property($name)") - - if (!BlueprintTypes.validPrimitiveTypes().contains(entrySchema.type)) { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) - } - } else { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt deleted file mode 100644 index 7603963a1..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImpl.kt +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault -import org.springframework.stereotype.Service -import java.io.IOException -import java.util.UUID - -@Service -open class BlueprintEnhancerServiceImpl( - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService -) : BlueprintEnhancerService { - - private val log = logger(BlueprintEnhancerServiceImpl::class) - - override suspend fun enhance(basePath: String, enrichedBasePath: String): BlueprintContext { - - // Copy the Blueprint Content to Target Location - BlueprintFileUtils.copyBlueprint(basePath, enrichedBasePath) - - // Enhance the Blueprint - return enhance(enrichedBasePath) - } - - @Throws(BlueprintException::class) - override suspend fun enhance(basePath: String): BlueprintContext { - - log.info("Enhancing blueprint($basePath)") - val blueprintRuntimeService = BlueprintMetadataUtils - .getBaseEnhancementBlueprintRuntime(UUID.randomUUID().toString(), basePath) - - try { - - bluePrintTypeEnhancerService.enhanceServiceTemplate( - blueprintRuntimeService, "service_template", - blueprintRuntimeService.bluePrintContext().serviceTemplate - ) - - log.info("##### Enhancing blueprint Resource Definitions") - val resourceDefinitions = resourceDefinitionEnhancerService.enhance( - bluePrintTypeEnhancerService, - blueprintRuntimeService - ) - - // Write the Enhanced Blueprint Definitions - BlueprintFileUtils.writeEnhancedBlueprint(blueprintRuntimeService.bluePrintContext()) - - // Write the Enhanced Blueprint Resource Definitions - ResourceDictionaryUtils.writeResourceDefinitionTypes(basePath, resourceDefinitions) - - if (blueprintRuntimeService.getBlueprintError().allErrors().isNotEmpty()) { - throw BlueprintException(blueprintRuntimeService.getBlueprintError().allErrors().toString()) - } - } catch (e: BlueprintProcessorException) { - val errorMsg = "Error while enriching the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong blueprint definitions or resource definitions." - ) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "IO Error: CBA file failed enrichment - ${e.message}", e.errorCauseOrDefault() - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Enriching CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - return blueprintRuntimeService.bluePrintContext() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt deleted file mode 100644 index 0dd5ed19a..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTemplateEnhancerImpl.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintNodeTemplateEnhancer { - - private val log = logger(BlueprintNodeTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) { - log.info("***** Enhancing NodeTemplate($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val nodeTypeName = nodeTemplate.type - // Get NodeType from Repo and Update Service Template - val nodeType = BlueprintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName) - - // Enrich NodeType - bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType) - - // Enrich Node Template Artifacts - enhanceNodeTemplateArtifactDefinition(name, nodeTemplate) - } - - open fun enhanceNodeTemplateArtifactDefinition(nodeTemplateName: String, nodeTemplate: NodeTemplate) { - - nodeTemplate.artifacts?.forEach { artifactDefinitionName, artifactDefinition -> - // Enhance Artifacct Definitions - bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt deleted file mode 100644 index 4011918f7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintNodeTypeEnhancerImpl.kt +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintNodeTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : BlueprintNodeTypeEnhancer { - - private val log = logger(BlueprintNodeTypeEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, nodeType: NodeType) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val derivedFrom = nodeType.derivedFrom - - if (!BlueprintTypes.rootNodeTypes().contains(derivedFrom)) { - val derivedFromNodeType = BlueprintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, name) - // Enrich NodeType - enhance(bluePrintRuntimeService, derivedFrom, derivedFromNodeType) - } - - // NodeType Attribute Definitions - enrichNodeTypeAttributes(name, nodeType) - - // NodeType Property Definitions - enrichNodeTypeProperties(name, nodeType) - - // NodeType Requirement - enrichNodeTypeRequirements(name, nodeType) - - // NodeType Capability - enrichNodeTypeCapabilityProperties(name, nodeType) - - // NodeType Interface - enrichNodeTypeInterfaces(name, nodeType) - } - - open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) { - nodeType.attributes?.let { - bluePrintTypeEnhancerService.enhanceAttributeDefinitions(bluePrintRuntimeService, nodeType.attributes!!) - } - } - - open fun enrichNodeTypeProperties(nodeTypeName: String, nodeType: NodeType) { - nodeType.properties?.let { - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, nodeType.properties!!) - } - } - - open fun enrichNodeTypeRequirements(nodeTypeName: String, nodeType: NodeType) { - - nodeType.requirements?.forEach { requirementName, requirementDefinition -> - // Populate Requirement Node - requirementDefinition.node?.let { requirementNodeTypeName -> - // Get Requirement NodeType from Repo and Update Service Template - val requirementNodeType = BlueprintEnhancerUtils.populateNodeType( - bluePrintContext, - bluePrintRepoService, requirementNodeTypeName - ) - // Enhance Node Type - enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType) - - // Enhance Relationship Type - val relationShipTypeName = requirementDefinition.relationship - ?: throw BlueprintException( - "couldn't get relationship name for the NodeType($nodeTypeName) " + - "Requirement($requirementName)" - ) - enrichRelationShipType(relationShipTypeName) - } - } - } - - open fun enrichNodeTypeCapabilityProperties(nodeTypeName: String, nodeType: NodeType) { - nodeType.capabilities?.forEach { _, capabilityDefinition -> - capabilityDefinition.properties?.let { properties -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, properties) - } - } - } - - open fun enrichNodeTypeInterfaces(nodeTypeName: String, nodeType: NodeType) { - nodeType.interfaces?.forEach { interfaceName, interfaceObj -> - // Populate Node type Interface Operation - log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName) - populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj) - } - } - - open fun populateNodeTypeInterfaceOperation(nodeTypeName: String, interfaceName: String, interfaceObj: InterfaceDefinition) { - - interfaceObj.operations?.forEach { operationName, operation -> - enrichNodeTypeInterfaceOperationInputs(nodeTypeName, operationName, operation) - enrichNodeTypeInterfaceOperationOutputs(nodeTypeName, operationName, operation) - } - } - - open fun enrichNodeTypeInterfaceOperationInputs(nodeTypeName: String, operationName: String, operation: OperationDefinition) { - operation.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enrichNodeTypeInterfaceOperationOutputs( - nodeTypeName: String, - operationName: String, - operation: OperationDefinition - ) { - operation.outputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - /** - * Get the Relationship Type from database and add to Blueprint Context - */ - open fun enrichRelationShipType(relationshipName: String) { - BlueprintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName) - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt deleted file mode 100644 index d58c82f07..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPolicyTypeEnhancerImpl.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.PolicyType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPolicyTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -class BlueprintPolicyTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintPolicyTypeEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: PolicyType) { - - this.bluePrintRuntimeService = bluePrintRuntimeService - - // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt deleted file mode 100644 index 4ac52bb17..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintPropertyDefinitionEnhancerImpl.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintPropertyDefinitionEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintPropertyDefinitionEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val propertyType = propertyDefinition.type - if (BlueprintTypes.validPrimitiveTypes().contains(propertyType) || - BlueprintTypes.validComplexTypes().contains(propertyType) - ) { - // Do Nothing, - } else if (BlueprintTypes.validCollectionTypes().contains(propertyType)) { - val entrySchema = propertyDefinition.entrySchema - ?: throw BlueprintException("Entry Schema is missing for collection property($name)") - - if (!BlueprintTypes.validPrimitiveTypes().contains(entrySchema.type)) { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type) - } - } else { - BlueprintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt deleted file mode 100644 index cd345a81c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTemplateEnhancerImpl.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintRelationshipTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintRelationshipTemplateEnhancer { - - private val log = logger(BlueprintRelationshipTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipTemplate: RelationshipTemplate - ) { - log.info("***** Enhancing RelationshipTemplate($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val relationshipTypeName = relationshipTemplate.type - // Get RelationshipType from Repo and Update Service Template - val relationshipType = - BlueprintEnhancerUtils.populateRelationshipType( - bluePrintContext, - bluePrintRepoService, - relationshipTypeName - ) - - // Enrich NodeType - bluePrintTypeEnhancerService.enhanceRelationshipType( - bluePrintRuntimeService, - relationshipTypeName, - relationshipType - ) - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt deleted file mode 100644 index 2216cafb6..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintRelationshipTypeEnhancerImpl.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintRelationshipTypeEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : BlueprintRelationshipTypeEnhancer { - - private val log = logger(BlueprintRelationshipTypeEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - name: String, - relationshipType: RelationshipType - ) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val derivedFrom = relationshipType.derivedFrom - - if (!BlueprintTypes.rootRelationshipTypes().contains(derivedFrom)) { - val derivedFromRelationshipType = - BlueprintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, name) - // Enrich RelationshipType - enhance(bluePrintRuntimeService, derivedFrom, derivedFromRelationshipType) - } - - // NodeType Attribute Definitions - enrichRelationshipTypeAttributes(name, relationshipType) - - // NodeType Property Definitions - enrichRelationshipTypeProperties(name, relationshipType) - - // TODO("Interface Enrichment, If needed") - } - - open fun enrichRelationshipTypeAttributes(nodeTypeName: String, relationshipType: RelationshipType) { - relationshipType.attributes?.let { - bluePrintTypeEnhancerService.enhanceAttributeDefinitions( - bluePrintRuntimeService, - relationshipType.attributes!! - ) - } - } - - open fun enrichRelationshipTypeProperties(nodeTypeName: String, relationshipType: RelationshipType) { - relationshipType.properties?.let { - bluePrintTypeEnhancerService.enhancePropertyDefinitions( - bluePrintRuntimeService, - relationshipType.properties!! - ) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt deleted file mode 100644 index 80855ce4c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintServiceTemplateEnhancerImpl.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService) : - BlueprintServiceTemplateEnhancer { - - private val log = logger(BlueprintServiceTemplateEnhancerImpl::class) - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: ServiceTemplate) { - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - initialCleanUp() - enhanceTopologyTemplate() - } - - open fun initialCleanUp() { - bluePrintContext.serviceTemplate.artifactTypes?.clear() - bluePrintContext.serviceTemplate.nodeTypes?.clear() - bluePrintContext.serviceTemplate.dataTypes?.clear() - bluePrintContext.serviceTemplate.policyTypes?.clear() - bluePrintContext.serviceTemplate.relationshipTypes?.clear() - - bluePrintContext.serviceTemplate.artifactTypes = mutableMapOf() - bluePrintContext.serviceTemplate.nodeTypes = mutableMapOf() - bluePrintContext.serviceTemplate.dataTypes = mutableMapOf() - bluePrintContext.serviceTemplate.policyTypes = mutableMapOf() - bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf() - log.info("reinitialized all type definitions") - } - - open fun enhanceTopologyTemplate() { - bluePrintContext.serviceTemplate.topologyTemplate?.let { topologyTemplate -> - bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt deleted file mode 100644 index 768f5abe4..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTopologyTemplateEnhancerImpl.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintTopologyTemplateEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService -) : - BlueprintTopologyTemplateEnhancer { - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, type: TopologyTemplate) { - this.bluePrintRuntimeService = bluePrintRuntimeService - - enhanceTopologyTemplateInputs(type) - enhanceTopologyTemplateNodeTemplates(type) - enhanceTopologyTemplateRelationshipTemplates(type) - enhanceTopologyTemplateWorkflows(type) - } - - open fun enhanceTopologyTemplateInputs(topologyTemplate: TopologyTemplate) { - topologyTemplate.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enhanceTopologyTemplateNodeTemplates(topologyTemplate: TopologyTemplate) { - topologyTemplate.nodeTemplates?.forEach { nodeTemplateName, nodeTemplate -> - bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate) - } - } - - open fun enhanceTopologyTemplateRelationshipTemplates(topologyTemplate: TopologyTemplate) { - topologyTemplate.relationshipTemplates?.forEach { relationshipTemplateName, relationshipTemplate -> - bluePrintTypeEnhancerService.enhanceRelationshipTemplate( - bluePrintRuntimeService, - relationshipTemplateName, - relationshipTemplate - ) - } - } - - open fun enhanceTopologyTemplateWorkflows(topologyTemplate: TopologyTemplate) { - topologyTemplate.workflows?.forEach { workflowName, workflow -> - bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt deleted file mode 100644 index d3b28596c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintTypeEnhancerServiceImpl.kt +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintArtifactDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintAttributeDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintNodeTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPolicyTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintPropertyDefinitionEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRelationshipTypeEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintServiceTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTopologyTemplateEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowEnhancer -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service - -@Service -open class BlueprintTypeEnhancerServiceImpl : BlueprintTypeEnhancerService { - - @Autowired - private lateinit var context: ApplicationContext - - override fun getServiceTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintServiceTemplateEnhancer::class.java).map { it.value } - } - - override fun getTopologyTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintTopologyTemplateEnhancer::class.java).map { it.value } - } - - override fun getWorkflowEnhancers(): List { - return context.getBeansOfType(BlueprintWorkflowEnhancer::class.java).map { it.value } - } - - override fun getNodeTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintNodeTemplateEnhancer::class.java).map { it.value } - } - - override fun getNodeTypeEnhancers(): List { - return context.getBeansOfType(BlueprintNodeTypeEnhancer::class.java).map { it.value } - } - - override fun getRelationshipTemplateEnhancers(): List { - return context.getBeansOfType(BlueprintRelationshipTemplateEnhancer::class.java).map { it.value } - } - - override fun getRelationshipTypeEnhancers(): List { - return context.getBeansOfType(BlueprintRelationshipTypeEnhancer::class.java).map { it.value } - } - - override fun getArtifactDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintArtifactDefinitionEnhancer::class.java).map { it.value } - } - - override fun getPolicyTypeEnhancers(): List { - return context.getBeansOfType(BlueprintPolicyTypeEnhancer::class.java).map { it.value } - } - - override fun getPropertyDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintPropertyDefinitionEnhancer::class.java).map { it.value } - } - - override fun getAttributeDefinitionEnhancers(): List { - return context.getBeansOfType(BlueprintAttributeDefinitionEnhancer::class.java).map { it.value } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt deleted file mode 100644 index 8b19af0a7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintWorkflowEnhancerImpl.kt +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowEnhancer -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class BlueprintWorkflowEnhancerImpl( - private val bluePrintRepoService: BlueprintRepoService, - private val bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService -) : - BlueprintWorkflowEnhancer { - - private val log = logger(BlueprintWorkflowEnhancerImpl::class) - - companion object { - - const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource" - const val PROPERTY_DEPENDENCY_NODE_TEMPLATES = "dependency-node-templates" - } - - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> - lateinit var bluePrintContext: BlueprintContext - - private val workflowDataTypes: MutableMap = hashMapOf() - - override fun enhance(bluePrintRuntimeService: BlueprintRuntimeService<*>, name: String, workflow: Workflow) { - log.info("##### Enhancing Workflow($name)") - this.bluePrintRuntimeService = bluePrintRuntimeService - this.bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val dynamicPropertyName = "$name-properties" - if (workflow.inputs == null) { - workflow.inputs = hashMapOf() - } - // Clean Dynamic Property Field, If present - workflow.inputs?.remove(dynamicPropertyName) - - // Enrich Workflow Inputs - enhanceWorkflowInputs(name, workflow) - - // Enrich Workflow Outputs - enhanceWorkflowOutputs(name, workflow) - - // Enrich Only for Resource Assignment and Dynamic Input Properties if any - enhanceStepTargets(name, workflow) - } - - open fun enhanceWorkflowInputs(name: String, workflow: Workflow) { - - workflow.inputs?.let { inputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs) - } - } - - open fun enhanceWorkflowOutputs(name: String, workflow: Workflow) { - workflow.outputs?.let { outputs -> - bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, outputs) - } - } - - private fun enhanceStepTargets(name: String, workflow: Workflow) { - - // Get the first Step Target NodeTemplate name( It may be Component or DG Node Template) - val firstNodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(name) - - val derivedFrom = bluePrintContext.nodeTemplateNodeType(firstNodeTemplateName).derivedFrom - - when { - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { - enhanceStepTargets(name, workflow, firstNodeTemplateName, false) - } - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { - enhanceStepTargets(name, workflow, firstNodeTemplateName, true) - } - else -> { - throw BlueprintProcessorException( - "couldn't execute workflow($name) step mapped " + - "to node template($firstNodeTemplateName) derived from($derivedFrom)" - ) - } - } - } - - private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) { - - val dependencyNodeTemplates: List - if (isDG) { - val dgNodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName) - - // Get the Dependent Component Node Template Names - val dependencyNodeTemplateNodes = dgNodeTemplate.properties?.get(PROPERTY_DEPENDENCY_NODE_TEMPLATES) - ?: throw BlueprintException("couldn't get property($PROPERTY_DEPENDENCY_NODE_TEMPLATES) ") - - dependencyNodeTemplates = - JacksonUtils.getListFromJsonNode(dependencyNodeTemplateNodes, String::class.java) - } else { - dependencyNodeTemplates = listOf(nodeTemplateName) - } - - log.info("workflow($name) dependent component NodeTemplates($dependencyNodeTemplates)") - - // Check and Get Resource Assignment File - val resourceAssignmentArtifacts = dependencyNodeTemplates?.mapNotNull { componentNodeTemplateName -> - log.info("identified workflow($name) targets($componentNodeTemplateName)") - - val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName) - .artifacts?.filter { - it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE - }?.map { - log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)") - it.value.file - } - resourceAssignmentArtifacts - }?.flatten() - - log.info("workflow($name) resource assignment files($resourceAssignmentArtifacts") - - if (resourceAssignmentArtifacts != null && resourceAssignmentArtifacts.isNotEmpty()) { - - // Add Workflow Dynamic Property - addWorkFlowDynamicPropertyDefinitions(name, workflow) - - resourceAssignmentArtifacts.forEach { fileName -> - // Enhance Resource Assignment File - val resourceAssignmentProperties = enhanceResourceAssignmentFile(fileName!!) - // Add Workflow Dynamic DataType - addWorkFlowDynamicDataType(name, resourceAssignmentProperties) - } - } - } - - // Enhancement for Dynamic Properties, Resource Assignment Properties, Resource Sources - private fun enhanceResourceAssignmentFile(fileName: String): MutableMap { - - val filePath = "${bluePrintContext.rootPath}/$fileName" - - log.info("enriching artifacts file($filePath") - - val resourceAssignmentProperties: MutableMap = hashMapOf() - - val resourceAssignments: MutableList = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java) - as? MutableList - ?: throw BlueprintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)") - - val alreadyEnhancedKey = "enhanced-$fileName" - val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey) - - log.info("enhancing workflow resource mapping file($fileName) already enhanced($alreadyEnhanced)") - - if (!alreadyEnhanced) { - // Call Resource Assignment Enhancer - resourceAssignmentEnhancerService.enhanceBlueprint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments) - bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive()) - } - - resourceAssignments.forEach { resourceAssignment -> - resourceAssignmentProperties[resourceAssignment.name] = resourceAssignment.property!! - } - return resourceAssignmentProperties - } - - private fun addWorkFlowDynamicPropertyDefinitions(name: String, workflow: Workflow) { - val dynamicPropertyName = "$name-properties" - val propertyDefinition = PropertyDefinition() - propertyDefinition.description = "Dynamic PropertyDefinition for workflow($name)." - propertyDefinition.type = "dt-$dynamicPropertyName" - propertyDefinition.required = true - // Add to Workflow Inputs - workflow.inputs?.put(dynamicPropertyName, propertyDefinition) - } - - private fun addWorkFlowDynamicDataType(workflowName: String, mappingProperties: MutableMap) { - - val dataTypeName = "dt-$workflowName-properties" - - var dynamicDataType: DataType? = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) - - if (dynamicDataType == null) { - log.info("dataType not present for the recipe({})", dataTypeName) - dynamicDataType = DataType() - dynamicDataType.version = "1.0.0" - dynamicDataType.description = "Dynamic DataType definition for workflow($workflowName)." - dynamicDataType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC - - val dataTypeProperties: MutableMap = hashMapOf() - dynamicDataType.properties = dataTypeProperties - - // Overwrite WorkFlow DataType - bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType) - } else { - log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).") - } - // Merge all the Recipe Properties - mappingProperties.forEach { (propertyName, propertyDefinition) -> - dynamicDataType.properties?.put(propertyName, propertyDefinition) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt index 4d1995d53..621b046e6 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt @@ -17,11 +17,11 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants @@ -37,10 +37,10 @@ import org.springframework.stereotype.Service */ interface ResourceAssignmentEnhancerService { - @Throws(BlueprintException::class) - fun enhanceBlueprint( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + @Throws(BluePrintException::class) + fun enhanceBluePrint( + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceAssignments: List ) } @@ -61,9 +61,9 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR * Get the defined source instance from the ResourceAssignment, * then get the NodeType of the Sources assigned */ - override fun enhanceBlueprint( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + override fun enhanceBluePrint( + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*>, resourceAssignments: List ) { @@ -91,7 +91,7 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR val resourceDefinition: ResourceDefinition = getResourceDefinition(dictionaryName) val sourceNodeTemplate = resourceDefinition.sources[dictionarySource] - ?: throw BlueprintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)") + ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)") // Enrich as NodeTemplate bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, dictionarySource, sourceNodeTemplate) @@ -110,7 +110,7 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT) || resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT) ) && - BlueprintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!) + BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!) ) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt index 08a41f7be..bbec8e685 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt @@ -21,12 +21,12 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeEnhancerService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils @@ -34,10 +34,10 @@ import org.springframework.stereotype.Service interface ResourceDefinitionEnhancerService { - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) fun enhance( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*> + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*> ): List } @@ -58,8 +58,8 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe // 3. Collect the Resource Definition for Resource Assignment names from database. // 4. Create the Resource Definition under blueprint base path. override fun enhance( - bluePrintTypeEnhancerService: BlueprintTypeEnhancerService, - bluePrintRuntimeService: BlueprintRuntimeService<*> + bluePrintTypeEnhancerService: BluePrintTypeEnhancerService, + bluePrintRuntimeService: BluePrintRuntimeService<*> ): List { var resourceDefinitions: List = mutableListOf() @@ -77,7 +77,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } // Get all the Mapping files from all node templates. - private fun getAllResourceMappingFiles(blueprintContext: BlueprintContext): List? { + private fun getAllResourceMappingFiles(blueprintContext: BluePrintContext): List? { return blueprintContext.nodeTemplates()?.mapNotNull { nodeTemplateMap -> @@ -91,7 +91,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } // Convert file content to ResourceAssignments asynchronously - private fun getResourceDefinition(blueprintContext: BlueprintContext, files: List) = runBlocking { + private fun getResourceDefinition(blueprintContext: BluePrintContext, files: List) = runBlocking { val blueprintBasePath = blueprintContext.rootPath val deferredResourceAssignments = mutableListOf>>() for (file in files) { @@ -124,7 +124,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe } private fun enrichResourceDefinitionSources( - bluePrintContext: BlueprintContext, + bluePrintContext: BluePrintContext, resourceDefinitions: List ) { val sources = resourceDefinitions @@ -138,7 +138,7 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe .flatten().distinct() log.info("Enriching Resource Definition sources Node Template: $sources") sources.forEach { - BlueprintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it) + BluePrintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it) } } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt new file mode 100644 index 000000000..7bbaa8c59 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt @@ -0,0 +1,643 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * Modifications Copyright © 2019 Orange. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler + +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelContentRepository +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelSearchRepository +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowData +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecRequest +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecResponse +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowsResponse +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BluePrintDatabaseLoadService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir +import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault +import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.data.domain.Page +import org.springframework.data.domain.PageRequest +import org.springframework.data.domain.Pageable +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import org.springframework.stereotype.Service +import org.springframework.transaction.annotation.Transactional +import java.io.File +import java.io.IOException +import java.util.UUID + +/** + * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest + * + * @author Brinda Santh + * @version 1.0 + */ + +@Service +open class BluePrintModelHandler( + private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService, + private val blueprintsProcessorCatalogService: BluePrintCatalogService, + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintModelSearchRepository: BlueprintModelSearchRepository, + private val blueprintModelRepository: BlueprintModelRepository, + private val blueprintModelContentRepository: BlueprintModelContentRepository, + private val bluePrintEnhancerService: BluePrintEnhancerService +) { + + private val log = logger(BluePrintModelHandler::class) + + open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) { + log.info( + "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " + + "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " + + "cba load(${bootstrapRequest.loadCBA})" + ) + if (bootstrapRequest.loadModelType) { + bluePrintDatabaseLoadService.initModelTypes() + } + if (bootstrapRequest.loadResourceDictionary) { + bluePrintDatabaseLoadService.initResourceDictionary() + } + if (bootstrapRequest.loadCBA) { + bluePrintDatabaseLoadService.initBluePrintCatalog() + } + } + + @Throws(BluePrintException::class) + open suspend fun prepareWorkFlowSpec(req: WorkFlowSpecRequest): + WorkFlowSpecResponse { + val basePath = blueprintsProcessorCatalogService.getFromDatabase( + req + .blueprintName, + req.version + ) + log.info("blueprint base path $basePath") + + val blueprintContext = BluePrintMetadataUtils.getBluePrintContext(basePath.toString()) + val workFlow = blueprintContext.workflowByName(req.workflowName) + + val wfRes = WorkFlowSpecResponse() + wfRes.blueprintName = req.blueprintName + wfRes.version = req.version + + val workFlowData = WorkFlowData() + workFlowData.workFlowName = req.workflowName + workFlowData.inputs = workFlow.inputs + workFlowData.outputs = workFlow.outputs + wfRes.workFlowData = workFlowData + + if (workFlow.inputs != null) { + for ((k, v) in workFlow.inputs!!) { + addPropertyInfo(k, v, blueprintContext, wfRes) + } + } + + if (workFlow.outputs != null) { + for ((k, v) in workFlow.outputs!!) { + addPropertyInfo(k, v, blueprintContext, wfRes) + } + } + + return wfRes + } + + private fun addPropertyInfo(propName: String, prop: PropertyDefinition, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + updatePropertyInfo(propName, prop, ctx, res) + addDataType(prop.type, ctx, res) + if (prop.entrySchema != null && prop.entrySchema!!.type != null) { + addDataType(prop.entrySchema!!.type, ctx, res) + } + } + + private fun updatePropertyInfo(name: String, prop: PropertyDefinition, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + if (prop.inputparam == null || prop.inputparam == false) { + var workflow = ctx.workflowByName(res.workFlowData.workFlowName) + for ((k, v) in workflow.steps!!) { + var arts = ctx.nodeTemplateArtifacts(v.target!!) + if (arts != null) { + for ((k, v) in arts.entries!!) { + if (v.type == "artifact-mapping-resource") { + val file: String = v.file + val completePath = ctx.rootPath.plus(File.separator).plus(file) + val resourceAssignment = JacksonUtils.getListFromFile(completePath, ResourceAssignment::class.java) + for (res in resourceAssignment) { + if (res.name == name && res.inputParameter) { + prop.inputparam = true + return + } + } + } + } + } + } + } + } + + private fun addDataType(name: String, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + var data = ctx.dataTypeByName(name) + if (data != null) { + res.dataTypes?.put(name, data) + addParentDataType(data, ctx, res) + } + } + + private fun addParentDataType(data: DataType, ctx: BluePrintContext, res: WorkFlowSpecResponse) { + if (data.properties != null) { + for ((k, v) in data.properties!!) { + addPropertyInfo(k, v, ctx, res) + } + } + } + + @Throws(BluePrintException::class) + open suspend fun getWorkflowNames(name: String, version: String): WorkFlowsResponse { + val basePath = blueprintsProcessorCatalogService.getFromDatabase( + name, version + ) + log.info("blueprint base path $basePath") + + var res = WorkFlowsResponse() + res.blueprintName = name + res.version = version + + val blueprintContext = BluePrintMetadataUtils.getBluePrintContext( + basePath.toString() + ) + if (blueprintContext.workflows() != null) { + res.workflows = blueprintContext.workflows()!!.keys + } + return res + } + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List list of the controller blueprint archives + */ + open fun allBlueprintModel(): List { + return blueprintModelSearchRepository.findAll() + } + + /** + * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database + * + * @return List list of the controller blueprint archives + */ + open fun allBlueprintModel(pageRequest: Pageable): Page { + return blueprintModelSearchRepository.findAll(pageRequest) + } + + /** + * This is a saveBlueprintModel method + * + * @param filePart filePart + * @return Mono + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun saveBlueprintModel(filePart: FilePart): BlueprintModelSearch { + try { + return upload(filePart, false) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Save CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * This is a searchBlueprintModels method + * + * @param tags tags + * @return List + */ + open fun searchBlueprintModels(tags: String): List { + return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) + } + + /** + * This is a getBlueprintModelSearchByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch? { + return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version) + /*?: throw BluePrintException( + ErrorCode.RESOURCE_NOT_FOUND.value, + String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + )*/ + } + + /** + * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version + * + * @param name name + * @param version version + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFileByNameAndVersion( + name: String, + version: String + ): ResponseEntity { + try { + val archiveByteArray = download(name, version) + val fileName = "${name}_$version.zip" + return prepareResourceEntity(fileName, archiveByteArray) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) + val errorMsg = "Error while downloading the CBA file by Blueprint Name ($name) and Version ($version)." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong resource definition or resolution failed." + ) + } + } + + /** + * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource + * + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun downloadBlueprintModelFile(id: String): ResponseEntity { + val blueprintModel: BlueprintModel + try { + blueprintModel = getBlueprintModel(id) + } catch (e: BluePrintException) { + throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get blueprint modelby ID ($id)", + e.errorCauseOrDefault() + ) + } + + val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip" + val file = blueprintModel.blueprintModelContent?.content + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get model content" + ) + return prepareResourceEntity(fileName, file) + } + + /** + * @return ResponseEntity + */ + private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(file)) + } + + /** + * This is a getBlueprintModel method + * + * @param id id + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModel(id: String): BlueprintModel { + val blueprintModel: BlueprintModel + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModel = dbBlueprintModel.get() + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + return blueprintModel + } + + /** + * This is a getBlueprintModelByNameAndVersion method + * + * @param name name + * @param version version + * @return BlueprintModel + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { + val blueprintModel = blueprintModelRepository + .findByArtifactNameAndArtifactVersion(name, version) + if (blueprintModel != null) { + return blueprintModel + } else { + val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + } + + /** + * This is a getBlueprintModelSearch method + * + * @param id id + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { + return blueprintModelSearchRepository.findById(id) + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + ) + } + + /** + * This is a searchBluePrintModelsByKeyWord method to retrieve specific BlueprintModel in Database + * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type + * @author Shaaban Ebrahim + * @param keyWord + * + * @return List list of the controller blueprint + */ + open fun searchBluePrintModelsByKeyWord(keyWord: String): List { + return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType( + keyWord, keyWord, keyWord, keyWord, keyWord + ) + } + + /** + * This is a searchBluePrintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database + * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable + * @author Shaaban Ebrahim + * @param keyWord + * + * @return List list of the controller blueprint + */ + open fun searchBluePrintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page { + return blueprintModelSearchRepository.findByUpdatedByContainingIgnoreCaseOrTagsContainingIgnoreCaseOrArtifactNameContainingIgnoreCaseOrArtifactVersionContainingIgnoreCaseOrArtifactTypeContainingIgnoreCase( + keyWord, + keyWord, + keyWord, + keyWord, + keyWord, + pageRequest + ) + } + + /** + * This is a deleteBlueprintModel method + * + * @param id id + * @throws BluePrintException BluePrintException + */ + @Transactional + @Throws(BluePrintException::class) + open fun deleteBlueprintModel(id: String) { + val dbBlueprintModel = blueprintModelRepository.findById(id) + if (dbBlueprintModel.isPresent) { + blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) + blueprintModelRepository.delete(dbBlueprintModel.get()) + } else { + val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) + throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) + } + } + + open suspend fun deleteBlueprintModel(name: String, version: String) { + blueprintsProcessorCatalogService.deleteFromDatabase(name, version) + } + + /** + * This is a CBA enrichBlueprint method + * Save the Zip File in archive location and extract the cba content. + * Populate the Enhancement Location + * Enhance the CBA content + * Compress the Enhanced Content + * Return back the the compressed content back to the caller. + * + * @param filePart filePart + * @return ResponseEntity + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity { + try { + val enhancedByteArray = enrichBlueprintFileSource(filePart) + return BluePrintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error while enhancing the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA file provided, please verify and enrich Again." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * This is a publishBlueprintModel method to change the status published to YES + * NOTE: this method is meant for enriched blueprints only. + * + * @param filePart filePart + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun publishBlueprint(filePart: FilePart): BlueprintModelSearch { + try { + return upload(filePart, true) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error in Publishing CBA." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA provided, please verify and enrich your CBA." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Publishing CBA: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** + * Enrich and publish the blueprint. + * NOTE: this method is meant for the unenriched vs publishBlueprint(filePart) + * which is used for enriched blueprints. + * + * @param filePart filePart + * @return BlueprintModelSearch + * @throws BluePrintException BluePrintException + */ + @Throws(BluePrintException::class) + open suspend fun enrichAndPublishBlueprint(filePart: FilePart): BlueprintModelSearch { + try { + val enhancedByteArray = enrichBlueprintFileSource(filePart) + return upload(enhancedByteArray, true) + } catch (e: BluePrintProcessorException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error while enhancing and uploading the CBA package." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong CBA file provided, please verify the source CBA." + ) + } catch (e: Exception) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() + ) + } + } + + /** Common CBA Save and Publish function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open suspend fun upload(fileSource: Any, validate: Boolean): BlueprintModelSearch { + val saveId = UUID.randomUUID().toString() + val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId) + val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId) + try { + val compressedFile = normalizedFile(blueprintArchive, "cba.zip") + when (fileSource) { + is FilePart -> BluePrintEnhancerUtils.filePartAsFile(fileSource, compressedFile) + is ByteArray -> BluePrintEnhancerUtils.byteArrayAsFile(fileSource, compressedFile) + } + // Save the Copied file to Database + val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate) + + return blueprintModelSearchRepository.findById(blueprintId) + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId) + ) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Error in Upload CBA." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong enriched CBA." + ) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error in Upload CBA: ${e.errorMessageOrDefault()}", e.errorCauseOrDefault() + ) + } finally { + // Clean blueprint script cache + val cacheKey = BluePrintFileUtils + .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId)) + BluePrintCompileCache.cleanClassLoader(cacheKey) + deleteNBDir(blueprintArchive) + deleteNBDir(blueprintWorking) + } + } + + /** Common CBA download function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open fun download(name: String, version: String): ByteArray { + try { + val blueprintModel = getBlueprintModelByNameAndVersion(name, version) + return blueprintModel.blueprintModelContent?.content + ?: throw httpProcessorException( + ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, + "Error while downloading the CBA file: couldn't get model content" + ) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) + val errorMsg = "Fail to get Blueprint Model content." + throw e.updateErrorMessage( + DesignerApiDomains.DESIGNER_API, errorMsg, + "Wrong name and version was provide." + ) + } + } + + /** Common CBA Enrich function for RestController and GRPC Handler, the [fileSource] may be + * byteArray or File Part type.*/ + open suspend fun enrichBlueprintFileSource(fileSource: Any): ByteArray { + val enhanceId = UUID.randomUUID().toString() + val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, enhanceId) + val blueprintWorkingDir = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, enhanceId) + try { + when (fileSource) { + is FilePart -> + BluePrintEnhancerUtils + .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) + is ByteArray -> + BluePrintEnhancerUtils + .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) + } // Enhance the Blue Prints + bluePrintEnhancerService.enhance(blueprintWorkingDir) + + return BluePrintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive) + } catch (e: BluePrintException) { + e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) + val errorMsg = "Fail Enriching the CBA." + throw e.updateErrorMessage(DesignerApiDomains.DESIGNER_API, errorMsg) + } catch (e: IOException) { + throw httpProcessorException( + ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, + "Error while Enriching the CBA file.", e.errorCauseOrDefault() + ) + } finally { + BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir) + } + } + + companion object { + + private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" + private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt deleted file mode 100644 index 42954c16e..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BlueprintModelHandler.kt +++ /dev/null @@ -1,643 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * Modifications Copyright © 2019 Orange. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler - -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelContentRepository -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository -import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelSearchRepository -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowData -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecRequest -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowSpecResponse -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.WorkFlowsResponse -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BlueprintDatabaseLoadService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BlueprintEnhancerUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir -import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintCompileCache -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintFileUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault -import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault -import org.springframework.core.io.ByteArrayResource -import org.springframework.core.io.Resource -import org.springframework.data.domain.Page -import org.springframework.data.domain.PageRequest -import org.springframework.data.domain.Pageable -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.springframework.http.ResponseEntity -import org.springframework.http.codec.multipart.FilePart -import org.springframework.stereotype.Service -import org.springframework.transaction.annotation.Transactional -import java.io.File -import java.io.IOException -import java.util.UUID - -/** - * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest - * - * @author Brinda Santh - * @version 1.0 - */ - -@Service -open class BlueprintModelHandler( - private val bluePrintDatabaseLoadService: BlueprintDatabaseLoadService, - private val blueprintsProcessorCatalogService: BlueprintCatalogService, - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val blueprintModelSearchRepository: BlueprintModelSearchRepository, - private val blueprintModelRepository: BlueprintModelRepository, - private val blueprintModelContentRepository: BlueprintModelContentRepository, - private val bluePrintEnhancerService: BlueprintEnhancerService -) { - - private val log = logger(BlueprintModelHandler::class) - - open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) { - log.info( - "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " + - "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " + - "cba load(${bootstrapRequest.loadCBA})" - ) - if (bootstrapRequest.loadModelType) { - bluePrintDatabaseLoadService.initModelTypes() - } - if (bootstrapRequest.loadResourceDictionary) { - bluePrintDatabaseLoadService.initResourceDictionary() - } - if (bootstrapRequest.loadCBA) { - bluePrintDatabaseLoadService.initBlueprintCatalog() - } - } - - @Throws(BlueprintException::class) - open suspend fun prepareWorkFlowSpec(req: WorkFlowSpecRequest): - WorkFlowSpecResponse { - val basePath = blueprintsProcessorCatalogService.getFromDatabase( - req - .blueprintName, - req.version - ) - log.info("blueprint base path $basePath") - - val blueprintContext = BlueprintMetadataUtils.getBlueprintContext(basePath.toString()) - val workFlow = blueprintContext.workflowByName(req.workflowName) - - val wfRes = WorkFlowSpecResponse() - wfRes.blueprintName = req.blueprintName - wfRes.version = req.version - - val workFlowData = WorkFlowData() - workFlowData.workFlowName = req.workflowName - workFlowData.inputs = workFlow.inputs - workFlowData.outputs = workFlow.outputs - wfRes.workFlowData = workFlowData - - if (workFlow.inputs != null) { - for ((k, v) in workFlow.inputs!!) { - addPropertyInfo(k, v, blueprintContext, wfRes) - } - } - - if (workFlow.outputs != null) { - for ((k, v) in workFlow.outputs!!) { - addPropertyInfo(k, v, blueprintContext, wfRes) - } - } - - return wfRes - } - - private fun addPropertyInfo(propName: String, prop: PropertyDefinition, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - updatePropertyInfo(propName, prop, ctx, res) - addDataType(prop.type, ctx, res) - if (prop.entrySchema != null && prop.entrySchema!!.type != null) { - addDataType(prop.entrySchema!!.type, ctx, res) - } - } - - private fun updatePropertyInfo(name: String, prop: PropertyDefinition, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - if (prop.inputparam == null || prop.inputparam == false) { - var workflow = ctx.workflowByName(res.workFlowData.workFlowName) - for ((k, v) in workflow.steps!!) { - var arts = ctx.nodeTemplateArtifacts(v.target!!) - if (arts != null) { - for ((k, v) in arts.entries!!) { - if (v.type == "artifact-mapping-resource") { - val file: String = v.file - val completePath = ctx.rootPath.plus(File.separator).plus(file) - val resourceAssignment = JacksonUtils.getListFromFile(completePath, ResourceAssignment::class.java) - for (res in resourceAssignment) { - if (res.name == name && res.inputParameter) { - prop.inputparam = true - return - } - } - } - } - } - } - } - } - - private fun addDataType(name: String, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - var data = ctx.dataTypeByName(name) - if (data != null) { - res.dataTypes?.put(name, data) - addParentDataType(data, ctx, res) - } - } - - private fun addParentDataType(data: DataType, ctx: BlueprintContext, res: WorkFlowSpecResponse) { - if (data.properties != null) { - for ((k, v) in data.properties!!) { - addPropertyInfo(k, v, ctx, res) - } - } - } - - @Throws(BlueprintException::class) - open suspend fun getWorkflowNames(name: String, version: String): WorkFlowsResponse { - val basePath = blueprintsProcessorCatalogService.getFromDatabase( - name, version - ) - log.info("blueprint base path $basePath") - - var res = WorkFlowsResponse() - res.blueprintName = name - res.version = version - - val blueprintContext = BlueprintMetadataUtils.getBlueprintContext( - basePath.toString() - ) - if (blueprintContext.workflows() != null) { - res.workflows = blueprintContext.workflows()!!.keys - } - return res - } - - /** - * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database - * - * @return List list of the controller blueprint archives - */ - open fun allBlueprintModel(): List { - return blueprintModelSearchRepository.findAll() - } - - /** - * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database - * - * @return List list of the controller blueprint archives - */ - open fun allBlueprintModel(pageRequest: Pageable): Page { - return blueprintModelSearchRepository.findAll(pageRequest) - } - - /** - * This is a saveBlueprintModel method - * - * @param filePart filePart - * @return Mono - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun saveBlueprintModel(filePart: FilePart): BlueprintModelSearch { - try { - return upload(filePart, false) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Save CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * This is a searchBlueprintModels method - * - * @param tags tags - * @return List - */ - open fun searchBlueprintModels(tags: String): List { - return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags) - } - - /** - * This is a getBlueprintModelSearchByNameAndVersion method - * - * @param name name - * @param version version - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch? { - return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version) - /*?: throw BlueprintException( - ErrorCode.RESOURCE_NOT_FOUND.value, - String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) - )*/ - } - - /** - * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version - * - * @param name name - * @param version version - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun downloadBlueprintModelFileByNameAndVersion( - name: String, - version: String - ): ResponseEntity { - try { - val archiveByteArray = download(name, version) - val fileName = "${name}_$version.zip" - return prepareResourceEntity(fileName, archiveByteArray) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) - val errorMsg = "Error while downloading the CBA file by Blueprint Name ($name) and Version ($version)." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong resource definition or resolution failed." - ) - } - } - - /** - * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource - * - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun downloadBlueprintModelFile(id: String): ResponseEntity { - val blueprintModel: BlueprintModel - try { - blueprintModel = getBlueprintModel(id) - } catch (e: BlueprintException) { - throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get blueprint modelby ID ($id)", - e.errorCauseOrDefault() - ) - } - - val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip" - val file = blueprintModel.blueprintModelContent?.content - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get model content" - ) - return prepareResourceEntity(fileName, file) - } - - /** - * @return ResponseEntity - */ - private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity { - return ResponseEntity.ok() - .contentType(MediaType.parseMediaType("text/plain")) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") - .body(ByteArrayResource(file)) - } - - /** - * This is a getBlueprintModel method - * - * @param id id - * @return BlueprintModel - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModel(id: String): BlueprintModel { - val blueprintModel: BlueprintModel - val dbBlueprintModel = blueprintModelRepository.findById(id) - if (dbBlueprintModel.isPresent) { - blueprintModel = dbBlueprintModel.get() - } else { - val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - return blueprintModel - } - - /** - * This is a getBlueprintModelByNameAndVersion method - * - * @param name name - * @param version version - * @return BlueprintModel - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel { - val blueprintModel = blueprintModelRepository - .findByArtifactNameAndArtifactVersion(name, version) - if (blueprintModel != null) { - return blueprintModel - } else { - val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - } - - /** - * This is a getBlueprintModelSearch method - * - * @param id id - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open fun getBlueprintModelSearch(id: String): BlueprintModelSearch { - return blueprintModelSearchRepository.findById(id) - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - ) - } - - /** - * This is a searchBlueprintModelsByKeyWord method to retrieve specific BlueprintModel in Database - * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type - * @author Shaaban Ebrahim - * @param keyWord - * - * @return List list of the controller blueprint - */ - open fun searchBlueprintModelsByKeyWord(keyWord: String): List { - return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType( - keyWord, keyWord, keyWord, keyWord, keyWord - ) - } - - /** - * This is a searchBlueprintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database - * where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable - * @author Shaaban Ebrahim - * @param keyWord - * - * @return List list of the controller blueprint - */ - open fun searchBlueprintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page { - return blueprintModelSearchRepository.findByUpdatedByContainingIgnoreCaseOrTagsContainingIgnoreCaseOrArtifactNameContainingIgnoreCaseOrArtifactVersionContainingIgnoreCaseOrArtifactTypeContainingIgnoreCase( - keyWord, - keyWord, - keyWord, - keyWord, - keyWord, - pageRequest - ) - } - - /** - * This is a deleteBlueprintModel method - * - * @param id id - * @throws BlueprintException BlueprintException - */ - @Transactional - @Throws(BlueprintException::class) - open fun deleteBlueprintModel(id: String) { - val dbBlueprintModel = blueprintModelRepository.findById(id) - if (dbBlueprintModel.isPresent) { - blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get()) - blueprintModelRepository.delete(dbBlueprintModel.get()) - } else { - val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id) - throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, msg) - } - } - - open suspend fun deleteBlueprintModel(name: String, version: String) { - blueprintsProcessorCatalogService.deleteFromDatabase(name, version) - } - - /** - * This is a CBA enrichBlueprint method - * Save the Zip File in archive location and extract the cba content. - * Populate the Enhancement Location - * Enhance the CBA content - * Compress the Enhanced Content - * Return back the the compressed content back to the caller. - * - * @param filePart filePart - * @return ResponseEntity - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity { - try { - val enhancedByteArray = enrichBlueprintFileSource(filePart) - return BlueprintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error while enhancing the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA file provided, please verify and enrich Again." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * This is a publishBlueprintModel method to change the status published to YES - * NOTE: this method is meant for enriched blueprints only. - * - * @param filePart filePart - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun publishBlueprint(filePart: FilePart): BlueprintModelSearch { - try { - return upload(filePart, true) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error in Publishing CBA." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA provided, please verify and enrich your CBA." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Publishing CBA: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** - * Enrich and publish the blueprint. - * NOTE: this method is meant for the unenriched vs publishBlueprint(filePart) - * which is used for enriched blueprints. - * - * @param filePart filePart - * @return BlueprintModelSearch - * @throws BlueprintException BlueprintException - */ - @Throws(BlueprintException::class) - open suspend fun enrichAndPublishBlueprint(filePart: FilePart): BlueprintModelSearch { - try { - val enhancedByteArray = enrichBlueprintFileSource(filePart) - return upload(enhancedByteArray, true) - } catch (e: BlueprintProcessorException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error while enhancing and uploading the CBA package." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong CBA file provided, please verify the source CBA." - ) - } catch (e: Exception) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "EnrichBlueprint: ${e.message}", e.errorCauseOrDefault() - ) - } - } - - /** Common CBA Save and Publish function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open suspend fun upload(fileSource: Any, validate: Boolean): BlueprintModelSearch { - val saveId = UUID.randomUUID().toString() - val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId) - val blueprintWorking = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId) - try { - val compressedFile = normalizedFile(blueprintArchive, "cba.zip") - when (fileSource) { - is FilePart -> BlueprintEnhancerUtils.filePartAsFile(fileSource, compressedFile) - is ByteArray -> BlueprintEnhancerUtils.byteArrayAsFile(fileSource, compressedFile) - } - // Save the Copied file to Database - val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate) - - return blueprintModelSearchRepository.findById(blueprintId) - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId) - ) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Error in Upload CBA." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong enriched CBA." - ) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error in Upload CBA: ${e.errorMessageOrDefault()}", e.errorCauseOrDefault() - ) - } finally { - // Clean blueprint script cache - val cacheKey = BlueprintFileUtils - .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId)) - BlueprintCompileCache.cleanClassLoader(cacheKey) - deleteNBDir(blueprintArchive) - deleteNBDir(blueprintWorking) - } - } - - /** Common CBA download function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open fun download(name: String, version: String): ByteArray { - try { - val blueprintModel = getBlueprintModelByNameAndVersion(name, version) - return blueprintModel.blueprintModelContent?.content - ?: throw httpProcessorException( - ErrorCatalogCodes.RESOURCE_NOT_FOUND, DesignerApiDomains.DESIGNER_API, - "Error while downloading the CBA file: couldn't get model content" - ) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.RESOURCE_NOT_FOUND) - val errorMsg = "Fail to get Blueprint Model content." - throw e.updateErrorMessage( - DesignerApiDomains.DESIGNER_API, errorMsg, - "Wrong name and version was provide." - ) - } - } - - /** Common CBA Enrich function for RestController and GRPC Handler, the [fileSource] may be - * byteArray or File Part type.*/ - open suspend fun enrichBlueprintFileSource(fileSource: Any): ByteArray { - val enhanceId = UUID.randomUUID().toString() - val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, enhanceId) - val blueprintWorkingDir = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, enhanceId) - try { - when (fileSource) { - is FilePart -> - BlueprintEnhancerUtils - .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) - is ByteArray -> - BlueprintEnhancerUtils - .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir) - } // Enhance the Blue Prints - bluePrintEnhancerService.enhance(blueprintWorkingDir) - - return BlueprintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive) - } catch (e: BlueprintException) { - e.http(ErrorCatalogCodes.IO_FILE_INTERRUPT) - val errorMsg = "Fail Enriching the CBA." - throw e.updateErrorMessage(DesignerApiDomains.DESIGNER_API, errorMsg) - } catch (e: IOException) { - throw httpProcessorException( - ErrorCatalogCodes.IO_FILE_INTERRUPT, DesignerApiDomains.DESIGNER_API, - "Error while Enriching the CBA file.", e.errorCauseOrDefault() - ) - } finally { - BlueprintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir) - } - } - - companion object { - - private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo" - private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo" - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt index 864fe7ca9..0d94aab27 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt @@ -21,7 +21,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.ModelTypeValidator -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes import org.slf4j.LoggerFactory @@ -68,9 +68,9 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository * * @param modelType modelType * @return ModelType - * @throws BlueprintException BlueprintException + * @throws BluePrintException BluePrintException */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) open suspend fun saveModel(modelType: ModelType): ModelType { lateinit var dbModel: ModelType ModelTypeValidator.validateModelType(modelType) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt index e2e726843..3f06a4a98 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt @@ -23,7 +23,7 @@ import org.apache.commons.lang3.StringUtils import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiDomains import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition @@ -40,9 +40,9 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * * @param name name * @return DataDictionary - * @throws BlueprintException BlueprintException + * @throws BluePrintException BluePrintException */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun getResourceDictionaryByName(name: String): ResourceDictionary { Preconditions.checkArgument(StringUtils.isNotBlank(name), "Resource dictionary Name Information is missing.") val resourceDictionaryDb = resourceDictionaryRepository.findByName(name) @@ -84,7 +84,7 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * @param resourceDictionary resourceDictionary * @return DataDictionary */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDictionary(resourceDictionary: ResourceDictionary): ResourceDictionary { var resourceDictionary = resourceDictionary @@ -133,7 +133,7 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour * @param resourceDefinition ResourceDefinition * @return ResourceDefinition */ - @Throws(BlueprintException::class) + @Throws(BluePrintException::class) suspend fun saveResourceDefinition(resourceDefinition: ResourceDefinition): ResourceDefinition { val resourceDictionary = ResourceDictionary() resourceDictionary.name = resourceDefinition.name diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt new file mode 100644 index 000000000..8d209449c --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load + +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import org.apache.commons.lang.text.StrBuilder +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service +import java.io.File +import java.util.UUID + +@Service +open class BluePrintCatalogLoadService(private val controllerBlueprintsCatalogService: BluePrintCatalogService) { + + private val log = LoggerFactory.getLogger(BluePrintCatalogLoadService::class.java) + + open fun loadPathsBluePrintModelCatalog(paths: List) { + paths.forEach { loadPathBluePrintModelCatalog(it) } + } + + open fun loadPathBluePrintModelCatalog(path: String) { + + val files = File(path).listFiles() + runBlocking { + val errorBuilder = StrBuilder() + val deferredResults = mutableListOf>() + + for (file in files) { + deferredResults += async { + loadBluePrintModelCatalog(errorBuilder, file) + } + } + + for (deferredResult in deferredResults) { + deferredResult.await() + } + + if (!errorBuilder.isEmpty) { + log.error(errorBuilder.toString()) + } + } + } + + open suspend fun loadBluePrintModelCatalog(errorBuilder: StrBuilder, file: File) { + try { + controllerBlueprintsCatalogService.saveToDatabase(UUID.randomUUID().toString(), file) + } catch (e: Exception) { + errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}") + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt new file mode 100644 index 000000000..02d6ad3c1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load + +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service + +@Service +open class BluePrintDatabaseLoadService( + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val modelTypeLoadService: ModelTypeLoadService, + private val resourceDictionaryLoadService: ResourceDictionaryLoadService, + private val bluePrintCatalogLoadService: BluePrintCatalogLoadService +) { + + private val log = LoggerFactory.getLogger(BluePrintDatabaseLoadService::class.java) + + open fun init() = runBlocking { + initModelTypes() + initResourceDictionary() + initBluePrintCatalog() + } + + open suspend fun initModelTypes() { + log.info("model types load from paths(${bluePrintLoadConfiguration.loadModeTypePaths})") + + val paths = bluePrintLoadConfiguration.loadModeTypePaths?.split(",") + paths?.let { + modelTypeLoadService.loadPathsModelType(paths) + } + } + + open suspend fun initResourceDictionary() { + log.info("resource dictionary load from paths(${bluePrintLoadConfiguration.loadResourceDictionaryPaths})") + + val paths = bluePrintLoadConfiguration.loadResourceDictionaryPaths?.split(",") + paths?.let { + resourceDictionaryLoadService.loadPathsResourceDictionary(paths) + } + } + + open suspend fun initBluePrintCatalog() { + log.info("cba load from paths(${bluePrintLoadConfiguration.loadBluePrintPaths})") + + val paths = bluePrintLoadConfiguration.loadBluePrintPaths?.split(",") + paths?.let { + bluePrintCatalogLoadService.loadPathsBluePrintModelCatalog(paths) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt deleted file mode 100644 index bcb1ebbed..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintCatalogLoadService.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load - -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.async -import kotlinx.coroutines.runBlocking -import org.apache.commons.lang.text.StrBuilder -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service -import java.io.File -import java.util.UUID - -@Service -open class BlueprintCatalogLoadService(private val controllerBlueprintsCatalogService: BlueprintCatalogService) { - - private val log = LoggerFactory.getLogger(BlueprintCatalogLoadService::class.java) - - open fun loadPathsBlueprintModelCatalog(paths: List) { - paths.forEach { loadPathBlueprintModelCatalog(it) } - } - - open fun loadPathBlueprintModelCatalog(path: String) { - - val files = File(path).listFiles() - runBlocking { - val errorBuilder = StrBuilder() - val deferredResults = mutableListOf>() - - for (file in files) { - deferredResults += async { - loadBlueprintModelCatalog(errorBuilder, file) - } - } - - for (deferredResult in deferredResults) { - deferredResult.await() - } - - if (!errorBuilder.isEmpty) { - log.error(errorBuilder.toString()) - } - } - } - - open suspend fun loadBlueprintModelCatalog(errorBuilder: StrBuilder, file: File) { - try { - controllerBlueprintsCatalogService.saveToDatabase(UUID.randomUUID().toString(), file) - } catch (e: Exception) { - errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}") - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt deleted file mode 100644 index 0534e16a5..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BlueprintDatabaseLoadService.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load - -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service - -@Service -open class BlueprintDatabaseLoadService( - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val modelTypeLoadService: ModelTypeLoadService, - private val resourceDictionaryLoadService: ResourceDictionaryLoadService, - private val bluePrintCatalogLoadService: BlueprintCatalogLoadService -) { - - private val log = LoggerFactory.getLogger(BlueprintDatabaseLoadService::class.java) - - open fun init() = runBlocking { - initModelTypes() - initResourceDictionary() - initBlueprintCatalog() - } - - open suspend fun initModelTypes() { - log.info("model types load from paths(${bluePrintLoadConfiguration.loadModeTypePaths})") - - val paths = bluePrintLoadConfiguration.loadModeTypePaths?.split(",") - paths?.let { - modelTypeLoadService.loadPathsModelType(paths) - } - } - - open suspend fun initResourceDictionary() { - log.info("resource dictionary load from paths(${bluePrintLoadConfiguration.loadResourceDictionaryPaths})") - - val paths = bluePrintLoadConfiguration.loadResourceDictionaryPaths?.split(",") - paths?.let { - resourceDictionaryLoadService.loadPathsResourceDictionary(paths) - } - } - - open suspend fun initBlueprintCatalog() { - log.info("cba load from paths(${bluePrintLoadConfiguration.loadBlueprintPaths})") - - val paths = bluePrintLoadConfiguration.loadBlueprintPaths?.split(",") - paths?.let { - bluePrintCatalogLoadService.loadPathsBlueprintModelCatalog(paths) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt index cb7953363..e96daf9f0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt @@ -24,8 +24,8 @@ import org.apache.commons.io.FilenameUtils import org.apache.commons.lang3.text.StrBuilder import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType @@ -118,19 +118,19 @@ open class ModelTypeLoadService(private val modelTypeHandler: ModelTypeHandler) val definitionType: String? when (T::class) { DataType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE } RelationshipType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE } ArtifactType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE } NodeType::class -> { - definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE + definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE } else -> { - throw BlueprintException("couldn't process model type($classType) definition") + throw BluePrintException("couldn't process model type($classType) definition") } } modelType.definitionType = definitionType diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt index 295e89a9e..15cf3dcb0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt @@ -22,7 +22,7 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import org.apache.commons.lang3.text.StrBuilder import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ResourceDictionaryHandler -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.readNBText import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -75,7 +75,7 @@ open class ResourceDictionaryLoadService(private val resourceDictionaryHandler: resourceDictionaryHandler.saveResourceDefinition(resourceDefinition) log.trace("Resource dictionary(${file.name}) loaded successfully ") } else { - throw BlueprintException("couldn't get dictionary from content information") + throw BluePrintException("couldn't get dictionary from content information") } } catch (e: Exception) { errorBuilder.appendln("Couldn't load Resource dictionary (${file.name}: ${e.message})") diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt new file mode 100644 index 000000000..420a9fcd7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service + +import com.fasterxml.jackson.databind.JsonNode +import com.google.common.base.Preconditions +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition +import org.springframework.stereotype.Service + +interface ResourceDefinitionRepoService : BluePrintRepoService { + + @Throws(BluePrintException::class) + fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition +} + +@Service +open class BluePrintRepoFileService( + private val modelTypeRepository: ModelTypeRepository, + private val resourceDictionaryRepository: ResourceDictionaryRepository +) : ResourceDefinitionRepoService { + + @Throws(BluePrintException::class) + override fun getNodeType(nodeTypeName: String): NodeType { + return getModelType(nodeTypeName, NodeType::class.java) + ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)") + } + + @Throws(BluePrintException::class) + override fun getDataType(dataTypeName: String): DataType { + return getModelType(dataTypeName, DataType::class.java) + ?: throw BluePrintException("couldn't get DataType($dataTypeName)") + } + + @Throws(BluePrintException::class) + override fun getArtifactType(artifactTypeName: String): ArtifactType { + return getModelType(artifactTypeName, ArtifactType::class.java) + ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)") + } + + @Throws(BluePrintException::class) + override fun getRelationshipType(relationshipTypeName: String): RelationshipType { + return getModelType(relationshipTypeName, RelationshipType::class.java) + ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)") + } + + @Throws(BluePrintException::class) + override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { + return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java) + ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)") + } + + @Throws(BluePrintException::class) + override fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition { + val dbResourceDictionary = resourceDictionaryRepository.findByName(resourceDefinitionName) + return if (dbResourceDictionary != null) { + dbResourceDictionary.definition + } else { + throw BluePrintException(String.format("failed to get resource dictionary (%s) from repo", resourceDefinitionName)) + } + } + + @Throws(BluePrintException::class) + private fun getModelType(modelName: String, valueClass: Class): T? { + Preconditions.checkArgument( + StringUtils.isNotBlank(modelName), + "Failed to get model from repo, model name is missing" + ) + + val modelDefinition = getModelDefinition(modelName) + Preconditions.checkNotNull( + modelDefinition, + String.format("Failed to get model content for model name (%s)", modelName) + ) + + return JacksonUtils.readValue(modelDefinition, valueClass) + } + + @Throws(BluePrintException::class) + private fun getModelDefinition(modelName: String): JsonNode { + val modelDefinition: JsonNode + val modelTypeDb = modelTypeRepository.findByModelName(modelName) + if (modelTypeDb != null) { + modelDefinition = modelTypeDb.definition + } else { + throw BluePrintException(String.format("failed to get model definition (%s) from repo", modelName)) + } + return modelDefinition + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt deleted file mode 100644 index 19f4e61b7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BlueprintRepoServiceImpl.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service - -import com.fasterxml.jackson.databind.JsonNode -import com.google.common.base.Preconditions -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition -import org.springframework.stereotype.Service - -interface ResourceDefinitionRepoService : BlueprintRepoService { - - @Throws(BlueprintException::class) - fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition -} - -@Service -open class BlueprintRepoFileService( - private val modelTypeRepository: ModelTypeRepository, - private val resourceDictionaryRepository: ResourceDictionaryRepository -) : ResourceDefinitionRepoService { - - @Throws(BlueprintException::class) - override fun getNodeType(nodeTypeName: String): NodeType { - return getModelType(nodeTypeName, NodeType::class.java) - ?: throw BlueprintException("couldn't get NodeType($nodeTypeName)") - } - - @Throws(BlueprintException::class) - override fun getDataType(dataTypeName: String): DataType { - return getModelType(dataTypeName, DataType::class.java) - ?: throw BlueprintException("couldn't get DataType($dataTypeName)") - } - - @Throws(BlueprintException::class) - override fun getArtifactType(artifactTypeName: String): ArtifactType { - return getModelType(artifactTypeName, ArtifactType::class.java) - ?: throw BlueprintException("couldn't get ArtifactType($artifactTypeName)") - } - - @Throws(BlueprintException::class) - override fun getRelationshipType(relationshipTypeName: String): RelationshipType { - return getModelType(relationshipTypeName, RelationshipType::class.java) - ?: throw BlueprintException("couldn't get RelationshipType($relationshipTypeName)") - } - - @Throws(BlueprintException::class) - override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition { - return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java) - ?: throw BlueprintException("couldn't get CapabilityDefinition($capabilityDefinitionName)") - } - - @Throws(BlueprintException::class) - override fun getResourceDefinition(resourceDefinitionName: String): ResourceDefinition { - val dbResourceDictionary = resourceDictionaryRepository.findByName(resourceDefinitionName) - return if (dbResourceDictionary != null) { - dbResourceDictionary.definition - } else { - throw BlueprintException(String.format("failed to get resource dictionary (%s) from repo", resourceDefinitionName)) - } - } - - @Throws(BlueprintException::class) - private fun getModelType(modelName: String, valueClass: Class): T? { - Preconditions.checkArgument( - StringUtils.isNotBlank(modelName), - "Failed to get model from repo, model name is missing" - ) - - val modelDefinition = getModelDefinition(modelName) - Preconditions.checkNotNull( - modelDefinition, - String.format("Failed to get model content for model name (%s)", modelName) - ) - - return JacksonUtils.readValue(modelDefinition, valueClass) - } - - @Throws(BlueprintException::class) - private fun getModelDefinition(modelName: String): JsonNode { - val modelDefinition: JsonNode - val modelTypeDb = modelTypeRepository.findByModelName(modelName) - if (modelTypeDb != null) { - modelDefinition = modelTypeDb.definition - } else { - throw BlueprintException(String.format("failed to get model definition (%s) from repo", modelName)) - } - return modelDefinition - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt new file mode 100644 index 000000000..6d72c2741 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt @@ -0,0 +1,191 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils + +import kotlinx.coroutines.reactive.awaitSingle +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType +import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType +import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType +import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType +import org.onap.ccsdk.cds.controllerblueprints.core.deCompress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.springframework.core.io.ByteArrayResource +import org.springframework.core.io.Resource +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.codec.multipart.FilePart +import java.io.File +import java.nio.file.Paths + +class BluePrintEnhancerUtils { + companion object { + + val log = logger(BluePrintEnhancerUtils) + + fun populateDataTypes( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + dataTypeName: String + ): DataType { + val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) + ?: bluePrintRepoService.getDataType(dataTypeName) + ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.") + bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType) + return dataType + } + + fun populateRelationshipType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + relationshipName: String + ): RelationshipType { + + val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName) + ?: bluePrintRepoService.getRelationshipType(relationshipName) + ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.") + bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType) + return relationshipType + } + + fun populateNodeType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + nodeTypeName: String + ): NodeType { + + val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName) + ?: bluePrintRepoService.getNodeType(nodeTypeName) + ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.") + bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType) + return nodeType + } + + fun populateArtifactType( + bluePrintContext: BluePrintContext, + bluePrintRepoService: BluePrintRepoService, + artifactTypeName: String + ): ArtifactType { + + val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) + ?: bluePrintRepoService.getArtifactType(artifactTypeName) + ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.") + bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType) + return artifactType + } + + suspend fun byteArrayAsFile(byteArray: ByteArray, targetFile: File): File { + // Recreate Folder + targetFile.parentFile.reCreateNBDirs() + targetFile.writeBytes(byteArray).apply { + log.info("CBA file(${targetFile.absolutePath} written successfully") + } + return targetFile + } + + suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File { + // Delete the Directory + targetFile.parentFile.reCreateNBDirs() + return filePart.transferTo(targetFile) + .thenReturn(targetFile) + .awaitSingle() + } + + private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { + // Recreate the Base Directories + normalizedFile(archiveDir).reCreateNBDirs() + normalizedFile(enhanceDir).reCreateNBDirs() + val archiveFile = normalizedFile(archiveDir, "cba.zip") + // Copy the File Part to ZIP + return byteArrayAsFile(byteArray, archiveFile) + } + + private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File { + // Recreate the Base Directories + normalizedFile(archiveDir).reCreateNBDirs() + normalizedFile(enhanceDir).reCreateNBDirs() + val archiveFile = normalizedFile(archiveDir, "cba.zip") + // Copy the File Part to ZIP + return filePartAsFile(filePart, archiveFile) + } + + /** copy the [byteArray] zip file to [archiveDir] and then decompress to [enhanceDir] */ + suspend fun copyByteArrayToEnhanceDir(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { + val archiveFile = byteArrayAsArchiveFile(byteArray, archiveDir, enhanceDir) + val deCompressFileName = normalizedPathName(enhanceDir) + return archiveFile.deCompress(deCompressFileName) + } + + /** copy the [filePart] zip file to [archiveDir] and then decompress to [enhanceDir] */ + suspend fun copyFilePartToEnhanceDir(filePart: FilePart, archiveDir: String, enhanceDir: String): File { + val filePartFile = filePartAsArchiveFile(filePart, archiveDir, enhanceDir) + val deCompressFileName = normalizedPathName(enhanceDir) + return filePartFile.deCompress(deCompressFileName) + } + + /** compress [enhanceDir] to [archiveDir] and return ByteArray */ + suspend fun compressEnhanceDirAndReturnByteArray( + enhanceDir: String, + archiveDir: String, + outputFileName: String = "enhanced-cba.zip" + ): ByteArray { + val compressedFile = normalizedFile(archiveDir, outputFileName) + BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) + return compressedFile.readBytes() + } + + /** compress [enhanceDir] to [archiveDir] and return ResponseEntity */ + suspend fun compressEnhanceDirAndReturnFilePart( + enhanceDir: String, + archiveDir: String, + outputFileName: String = "enhanced-cba.zip" + ): + ResponseEntity { + val compressedFile = normalizedFile(archiveDir, outputFileName) + BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) + return prepareResourceEntity(compressedFile) + } + + /** convert [file] to ResourceEntity */ + suspend fun prepareResourceEntity(file: File): ResponseEntity { + return prepareResourceEntity(file.name, file.readBytes()) + } + + /** convert [byteArray] to ResourceEntity with [fileName]*/ + fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity { + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType("text/plain")) + .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") + .body(ByteArrayResource(byteArray)) + } + + suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) { + deleteNBDir(archiveLocation) + deleteNBDir(enhancementLocation) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt deleted file mode 100644 index b10b17025..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtils.kt +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils - -import kotlinx.coroutines.reactive.awaitSingle -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType -import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType -import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType -import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType -import org.onap.ccsdk.cds.controllerblueprints.core.deCompress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintRepoService -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintArchiveUtils -import org.springframework.core.io.ByteArrayResource -import org.springframework.core.io.Resource -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import org.springframework.http.ResponseEntity -import org.springframework.http.codec.multipart.FilePart -import java.io.File -import java.nio.file.Paths - -class BlueprintEnhancerUtils { - companion object { - - val log = logger(BlueprintEnhancerUtils) - - fun populateDataTypes( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - dataTypeName: String - ): DataType { - val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName) - ?: bluePrintRepoService.getDataType(dataTypeName) - ?: throw BlueprintException("couldn't get DataType($dataTypeName) from repo.") - bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType) - return dataType - } - - fun populateRelationshipType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - relationshipName: String - ): RelationshipType { - - val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName) - ?: bluePrintRepoService.getRelationshipType(relationshipName) - ?: throw BlueprintException("couldn't get RelationshipType($relationshipName) from repo.") - bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType) - return relationshipType - } - - fun populateNodeType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - nodeTypeName: String - ): NodeType { - - val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName) - ?: bluePrintRepoService.getNodeType(nodeTypeName) - ?: throw BlueprintException("couldn't get NodeType($nodeTypeName) from repo.") - bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType) - return nodeType - } - - fun populateArtifactType( - bluePrintContext: BlueprintContext, - bluePrintRepoService: BlueprintRepoService, - artifactTypeName: String - ): ArtifactType { - - val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName) - ?: bluePrintRepoService.getArtifactType(artifactTypeName) - ?: throw BlueprintException("couldn't get ArtifactType($artifactTypeName) from repo.") - bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType) - return artifactType - } - - suspend fun byteArrayAsFile(byteArray: ByteArray, targetFile: File): File { - // Recreate Folder - targetFile.parentFile.reCreateNBDirs() - targetFile.writeBytes(byteArray).apply { - log.info("CBA file(${targetFile.absolutePath} written successfully") - } - return targetFile - } - - suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File { - // Delete the Directory - targetFile.parentFile.reCreateNBDirs() - return filePart.transferTo(targetFile) - .thenReturn(targetFile) - .awaitSingle() - } - - private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { - // Recreate the Base Directories - normalizedFile(archiveDir).reCreateNBDirs() - normalizedFile(enhanceDir).reCreateNBDirs() - val archiveFile = normalizedFile(archiveDir, "cba.zip") - // Copy the File Part to ZIP - return byteArrayAsFile(byteArray, archiveFile) - } - - private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File { - // Recreate the Base Directories - normalizedFile(archiveDir).reCreateNBDirs() - normalizedFile(enhanceDir).reCreateNBDirs() - val archiveFile = normalizedFile(archiveDir, "cba.zip") - // Copy the File Part to ZIP - return filePartAsFile(filePart, archiveFile) - } - - /** copy the [byteArray] zip file to [archiveDir] and then decompress to [enhanceDir] */ - suspend fun copyByteArrayToEnhanceDir(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File { - val archiveFile = byteArrayAsArchiveFile(byteArray, archiveDir, enhanceDir) - val deCompressFileName = normalizedPathName(enhanceDir) - return archiveFile.deCompress(deCompressFileName) - } - - /** copy the [filePart] zip file to [archiveDir] and then decompress to [enhanceDir] */ - suspend fun copyFilePartToEnhanceDir(filePart: FilePart, archiveDir: String, enhanceDir: String): File { - val filePartFile = filePartAsArchiveFile(filePart, archiveDir, enhanceDir) - val deCompressFileName = normalizedPathName(enhanceDir) - return filePartFile.deCompress(deCompressFileName) - } - - /** compress [enhanceDir] to [archiveDir] and return ByteArray */ - suspend fun compressEnhanceDirAndReturnByteArray( - enhanceDir: String, - archiveDir: String, - outputFileName: String = "enhanced-cba.zip" - ): ByteArray { - val compressedFile = normalizedFile(archiveDir, outputFileName) - BlueprintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) - return compressedFile.readBytes() - } - - /** compress [enhanceDir] to [archiveDir] and return ResponseEntity */ - suspend fun compressEnhanceDirAndReturnFilePart( - enhanceDir: String, - archiveDir: String, - outputFileName: String = "enhanced-cba.zip" - ): - ResponseEntity { - val compressedFile = normalizedFile(archiveDir, outputFileName) - BlueprintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile) - return prepareResourceEntity(compressedFile) - } - - /** convert [file] to ResourceEntity */ - suspend fun prepareResourceEntity(file: File): ResponseEntity { - return prepareResourceEntity(file.name, file.readBytes()) - } - - /** convert [byteArray] to ResourceEntity with [fileName]*/ - fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity { - return ResponseEntity.ok() - .contentType(MediaType.parseMediaType("text/plain")) - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"") - .body(ByteArrayResource(byteArray)) - } - - suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) { - deleteNBDir(archiveLocation) - deleteNBDir(enhancementLocation) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt index 78f9e1688..08de136d8 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt @@ -18,9 +18,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType @@ -41,25 +41,25 @@ class ModelTypeValidator { fun validateModelTypeDefinition(definitionType: String, definitionContent: JsonNode): Boolean { when (definitionType) { - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> { JacksonUtils.readValue(definitionContent, DataType::class.java) - ?: throw BlueprintException("Model type definition is not DataType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> { JacksonUtils.readValue(definitionContent, NodeType::class.java) - ?: throw BlueprintException("Model type definition is not NodeType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> { JacksonUtils.readValue(definitionContent, ArtifactType::class.java) - ?: throw BlueprintException("Model type definition is not ArtifactType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> { JacksonUtils.readValue(definitionContent, CapabilityDefinition::class.java) - ?: throw BlueprintException("Model type definition is not CapabilityDefinition valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent") } - BlueprintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> { + BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> { JacksonUtils.readValue(definitionContent, RelationshipType::class.java) - ?: throw BlueprintException("Model type definition is not RelationshipType valid content $definitionContent") + ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent") } } return true @@ -74,7 +74,7 @@ class ModelTypeValidator { fun validateModelType(modelType: ModelType?): Boolean { checkNotNull(modelType) { "Model Type Information is missing." } - val validRootTypes = BlueprintTypes.validModelTypes() + val validRootTypes = BluePrintTypes.validModelTypes() check(validRootTypes.contains(modelType.definitionType)) { "Not Valid Model Root Type(${modelType.definitionType}), It should be $validRootTypes" diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt new file mode 100644 index 000000000..a2f208367 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt @@ -0,0 +1,252 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api + +import com.google.protobuf.ByteString +import io.grpc.testing.GrpcServerRule +import kotlinx.coroutines.runBlocking +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.compress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk +import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction +import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [DesignerApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintManagementGRPCHandlerTest { + + @get:Rule + val grpcServerRule = GrpcServerRule().directExecutor() + + @Autowired + lateinit var bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler + + @BeforeTest + fun init() { + + deleteDir("target", "blueprints") + + // Create sample CBA zip + normalizedFile("./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + .compress(normalizedFile("./target/blueprints/generated-cba.zip")) + + // Create a server, add service, start, and register for automatic graceful shutdown. + grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) + } + + @AfterTest + fun cleanDir() { + deleteDir("target", "blueprints") + } + + @Test + fun testBootstrap() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_Bootstrap" + val req = createBootstrapInputRequest(id) + val bootstrapOutput = blockingStub.bootstrapBlueprint(req) + assertEquals(200, bootstrapOutput.status.code) + assertTrue( + bootstrapOutput.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, bootstrapOutput.status.eventType) + assertEquals(id, bootstrapOutput.commonHeader.requestId) + } + + @Test + fun `test upload and download blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_upload" + val req = createUploadInputRequest(id, UploadAction.PUBLISH.toString()) + val output = blockingStub.uploadBlueprint(req) + + assertEquals(200, output.status.code) + assertTrue( + output.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) + assertEquals(id, output.commonHeader.requestId) + + val downloadId = "123_download" + val downloadReq = createDownloadInputRequest(downloadId, DownloadAction.SEARCH.toString()) + + val downloadOutput = blockingStub.downloadBlueprint(downloadReq) + assertEquals(200, downloadOutput.status.code) + assertTrue( + downloadOutput.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, downloadOutput.status.eventType) + assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks") + assertEquals(downloadId, downloadOutput.commonHeader.requestId) + } + + @Test + fun `test delete blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_delete" + val req = createUploadInputRequest(id, UploadAction.DRAFT.toString()) + + var output = blockingStub.uploadBlueprint(req) + assertEquals(200, output.status.code) + assertTrue( + output.status.message!!.contentEquals(BluePrintConstants.STATUS_SUCCESS), + "failed to get success status" + ) + assertEquals(id, output.commonHeader.requestId) + assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) + + val removeReq = createRemoveInputRequest(id) + output = blockingStub.removeBlueprint(removeReq) + assertEquals(200, output.status.code) + } + + /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ + private fun integrationTestGrpcManagement() { + runBlocking { + val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { + host = "127.0.0.1" + port = 9111 + type = GRPCLibConstants.TYPE_TOKEN_AUTH + token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" + } + val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) + val channel = basicAuthGrpcClientService.channel() + + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(channel) + + val bluePrintUploadInput = createUploadInputRequest("12345", UploadAction.DRAFT.toString()) + + val bluePrintManagementOutput = blockingStub.uploadBlueprint(bluePrintUploadInput) + assertNotNull(bluePrintManagementOutput, "failed to get response") + } + } + + private fun createBootstrapInputRequest(id: String): BluePrintBootstrapInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintBootstrapInput.newBuilder() + .setCommonHeader(commonHeader) + .setLoadModelType(false) + .setLoadResourceDictionary(false) + .setLoadCBA(false) + .build() + } + + private fun createUploadInputRequest(id: String, action: String): BluePrintUploadInput { + val file = normalizedFile("./target/blueprints/generated-cba.zip") + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + val actionIdentifier = ActionIdentifiers.newBuilder() + .setActionName(action) + .setBlueprintName("sample") + .setBlueprintVersion("1.0.0") + .build() + + val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) + .build() + + return BluePrintUploadInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers(actionIdentifier) + .setFileChunk(fileChunk) + .build() + } + + private fun createDownloadInputRequest(id: String, action: String): BluePrintDownloadInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintDownloadInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers( + ActionIdentifiers.newBuilder() + .setBlueprintName("baseconfiguration") + .setBlueprintVersion("1.0.0") + .setActionName(action).build() + ) + .build() + } + + private fun createRemoveInputRequest(id: String): BluePrintRemoveInput { + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + return BluePrintRemoveInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers( + ActionIdentifiers.newBuilder() + .setBlueprintName("sample") + .setBlueprintVersion("1.0.0") + .setActionName(RemoveAction.DEFAULT.toString()).build() + ) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt deleted file mode 100644 index ed60f721a..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintManagementGRPCHandlerTest.kt +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api - -import com.google.protobuf.ByteString -import io.grpc.testing.GrpcServerRule -import kotlinx.coroutines.runBlocking -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintBootstrapInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintDownloadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintRemoveInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput -import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk -import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction -import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [DesignerApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintManagementGRPCHandlerTest { - - @get:Rule - val grpcServerRule = GrpcServerRule().directExecutor() - - @Autowired - lateinit var bluePrintManagementGRPCHandler: BlueprintManagementGRPCHandler - - @BeforeTest - fun init() { - - deleteDir("target", "blueprints") - - // Create sample CBA zip - normalizedFile("./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - .compress(normalizedFile("./target/blueprints/generated-cba.zip")) - - // Create a server, add service, start, and register for automatic graceful shutdown. - grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) - } - - @AfterTest - fun cleanDir() { - deleteDir("target", "blueprints") - } - - @Test - fun testBootstrap() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_Bootstrap" - val req = createBootstrapInputRequest(id) - val bootstrapOutput = blockingStub.bootstrapBlueprint(req) - assertEquals(200, bootstrapOutput.status.code) - assertTrue( - bootstrapOutput.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, bootstrapOutput.status.eventType) - assertEquals(id, bootstrapOutput.commonHeader.requestId) - } - - @Test - fun `test upload and download blueprint`() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_upload" - val req = createUploadInputRequest(id, UploadAction.PUBLISH.toString()) - val output = blockingStub.uploadBlueprint(req) - - assertEquals(200, output.status.code) - assertTrue( - output.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) - assertEquals(id, output.commonHeader.requestId) - - val downloadId = "123_download" - val downloadReq = createDownloadInputRequest(downloadId, DownloadAction.SEARCH.toString()) - - val downloadOutput = blockingStub.downloadBlueprint(downloadReq) - assertEquals(200, downloadOutput.status.code) - assertTrue( - downloadOutput.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, downloadOutput.status.eventType) - assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks") - assertEquals(downloadId, downloadOutput.commonHeader.requestId) - } - - @Test - fun `test delete blueprint`() { - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_delete" - val req = createUploadInputRequest(id, UploadAction.DRAFT.toString()) - - var output = blockingStub.uploadBlueprint(req) - assertEquals(200, output.status.code) - assertTrue( - output.status.message!!.contentEquals(BlueprintConstants.STATUS_SUCCESS), - "failed to get success status" - ) - assertEquals(id, output.commonHeader.requestId) - assertEquals(EventType.EVENT_COMPONENT_EXECUTED, output.status.eventType) - - val removeReq = createRemoveInputRequest(id) - output = blockingStub.removeBlueprint(removeReq) - assertEquals(200, output.status.code) - } - - /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ - private fun integrationTestGrpcManagement() { - runBlocking { - val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { - host = "127.0.0.1" - port = 9111 - type = GRPCLibConstants.TYPE_TOKEN_AUTH - token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" - } - val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) - val channel = basicAuthGrpcClientService.channel() - - val blockingStub = BlueprintManagementServiceGrpc.newBlockingStub(channel) - - val bluePrintUploadInput = createUploadInputRequest("12345", UploadAction.DRAFT.toString()) - - val bluePrintManagementOutput = blockingStub.uploadBlueprint(bluePrintUploadInput) - assertNotNull(bluePrintManagementOutput, "failed to get response") - } - } - - private fun createBootstrapInputRequest(id: String): BlueprintBootstrapInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintBootstrapInput.newBuilder() - .setCommonHeader(commonHeader) - .setLoadModelType(false) - .setLoadResourceDictionary(false) - .setLoadCBA(false) - .build() - } - - private fun createUploadInputRequest(id: String, action: String): BlueprintUploadInput { - val file = normalizedFile("./target/blueprints/generated-cba.zip") - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - val actionIdentifier = ActionIdentifiers.newBuilder() - .setActionName(action) - .setBlueprintName("sample") - .setBlueprintVersion("1.0.0") - .build() - - val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) - .build() - - return BlueprintUploadInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers(actionIdentifier) - .setFileChunk(fileChunk) - .build() - } - - private fun createDownloadInputRequest(id: String, action: String): BlueprintDownloadInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintDownloadInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers( - ActionIdentifiers.newBuilder() - .setBlueprintName("baseconfiguration") - .setBlueprintVersion("1.0.0") - .setActionName(action).build() - ) - .build() - } - - private fun createRemoveInputRequest(id: String): BlueprintRemoveInput { - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - return BlueprintRemoveInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers( - ActionIdentifiers.newBuilder() - .setBlueprintName("sample") - .setBlueprintVersion("1.0.0") - .setActionName(RemoveAction.DEFAULT.toString()).build() - ) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt index 92f369b01..a42ac05e7 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt @@ -28,7 +28,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile @@ -79,7 +79,7 @@ class BlueprintModelControllerTest { @Autowired lateinit var webTestClient: WebTestClient - private var bluePrintLoadConfiguration: BlueprintLoadConfiguration? = null + private var bluePrintLoadConfiguration: BluePrintLoadConfiguration? = null private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" private var zipBlueprintFileName: String? = null @@ -90,7 +90,7 @@ class BlueprintModelControllerTest { fun setUp() { assertNotNull(webTestClient, " Failed to create WebTestClient") - bluePrintLoadConfiguration = BlueprintLoadConfiguration().apply { + bluePrintLoadConfiguration = BluePrintLoadConfiguration().apply { blueprintArchivePath = "./target/blueprints/archive" blueprintWorkingPath = "./target/blueprints/work" blueprintDeployPath = "./target/blueprints/deploy" @@ -113,7 +113,7 @@ class BlueprintModelControllerTest { } @Test - fun test01_saveBlueprint() { + fun test01_saveBluePrint() { bp = runBlocking { val body = MultipartBodyBuilder().apply { part( @@ -146,7 +146,7 @@ class BlueprintModelControllerTest { @Test @Throws(JSONException::class) - fun test02_getBlueprintByNameAndVersion() { + fun test02_getBluePrintByNameAndVersion() { webTestClient( HttpMethod.GET, null, "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}", @@ -172,7 +172,7 @@ class BlueprintModelControllerTest { @Test @Throws(JSONException::class) - fun test05_downloadBlueprint() { + fun test05_downloadBluePrint() { webTestClient( HttpMethod.GET, null, "/api/v1/blueprint-model/download/${bp!!.id}", @@ -237,7 +237,7 @@ class BlueprintModelControllerTest { } @Test - fun test10_deleteBlueprint() { + fun test10_deleteBluePrint() { // webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}") // .header("Authorization", "Basic " + Base64Utils // .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))) diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt index bcce13e4c..8226aaad0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt @@ -23,7 +23,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired @@ -56,15 +56,15 @@ class ModelTypeControllerTest { val content = JacksonUtils.getClassPathFileContent("model_type/data_type/datatype-property.json") var modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" modelType = modelTypeController.saveModelType(modelType) @@ -108,7 +108,7 @@ class ModelTypeControllerTest { Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbModelType!!.modelName) val dbDatatypeModelTypes = - modelTypeController.getModelTypeByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + modelTypeController.getModelTypeByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) Assert.assertNotNull("Failed to find getModelTypeByDefinitionType by tags", dbDatatypeModelTypes) Assert.assertTrue("Failed to find getModelTypeByDefinitionType by count", dbDatatypeModelTypes.isNotEmpty()) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt index 7fcea4dcc..6808a2717 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary", diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt new file mode 100644 index 000000000..a866dcad3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt @@ -0,0 +1,114 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer + +import kotlinx.coroutines.runBlocking +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ModelTypeLoadService +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ResourceDictionaryLoadService +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [DesignerApiTestConfiguration::class] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintEnhancerServiceImplTest { + + @Autowired + lateinit var modelTypeLoadService: ModelTypeLoadService + + @Autowired + lateinit var resourceDictionaryLoadService: ResourceDictionaryLoadService + + @Autowired + lateinit var bluePrintEnhancerService: BluePrintEnhancerService + + @Autowired + lateinit var bluePrintValidatorService: BluePrintValidatorService + + @Test + @Throws(Exception::class) + fun testEnhancementAndValidation() { + + runBlocking { + modelTypeLoadService.loadPathModelType("./../../../../../components/model-catalog/definition-type/starter-type") + + val dictPaths: MutableList = arrayListOf() + dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary") + dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/test-dictionary") + resourceDictionaryLoadService.loadPathsResourceDictionary(dictPaths) + + testBaseConfigEnhancementAndValidation() + testGoldenEnhancementAndValidation() + testRemoteScriptsEnhancementAndValidation() + testCapabilityCliEnhancementAndValidation() + } + } + + private fun testBaseConfigEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + testComponentInvokeEnhancementAndValidation(basePath, "base-enhance") + } + + private fun testGoldenEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/golden" + testComponentInvokeEnhancementAndValidation(basePath, "golden-enhance") + } + + private fun testRemoteScriptsEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" + testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance") + } + + private fun testCapabilityCliEnhancementAndValidation() { + val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/capability_cli" + testComponentInvokeEnhancementAndValidation(basePath, "capability_cli-enhance") + } + + private fun testComponentInvokeEnhancementAndValidation(basePath: String, targetDirName: String) { + runBlocking { + val targetPath = normalizedPathName("target/blueprints/enrichment", targetDirName) + + deleteDir(targetPath) + + val bluePrintContext = bluePrintEnhancerService.enhance(basePath, targetPath) + Assert.assertNotNull("failed to get blueprintContext ", bluePrintContext) + + // Validate the Generated BluePrints + val valid = bluePrintValidatorService.validateBluePrints(targetPath) + Assert.assertTrue("blueprint($basePath) validation failed ", valid) + + // Enable this to get the enhanced zip file + // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip") + // normalizedFile(targetPath).compress(compressFile) + + deleteDir(targetPath) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt deleted file mode 100644 index 8bdfbbb22..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BlueprintEnhancerServiceImplTest.kt +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer - -import kotlinx.coroutines.runBlocking -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ModelTypeLoadService -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ResourceDictionaryLoadService -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintEnhancerService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintValidatorService -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [DesignerApiTestConfiguration::class] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintEnhancerServiceImplTest { - - @Autowired - lateinit var modelTypeLoadService: ModelTypeLoadService - - @Autowired - lateinit var resourceDictionaryLoadService: ResourceDictionaryLoadService - - @Autowired - lateinit var bluePrintEnhancerService: BlueprintEnhancerService - - @Autowired - lateinit var bluePrintValidatorService: BlueprintValidatorService - - @Test - @Throws(Exception::class) - fun testEnhancementAndValidation() { - - runBlocking { - modelTypeLoadService.loadPathModelType("./../../../../../components/model-catalog/definition-type/starter-type") - - val dictPaths: MutableList = arrayListOf() - dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary") - dictPaths.add("./../../../../../components/model-catalog/resource-dictionary/test-dictionary") - resourceDictionaryLoadService.loadPathsResourceDictionary(dictPaths) - - testBaseConfigEnhancementAndValidation() - testGoldenEnhancementAndValidation() - testRemoteScriptsEnhancementAndValidation() - testCapabilityCliEnhancementAndValidation() - } - } - - private fun testBaseConfigEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - testComponentInvokeEnhancementAndValidation(basePath, "base-enhance") - } - - private fun testGoldenEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/golden" - testComponentInvokeEnhancementAndValidation(basePath, "golden-enhance") - } - - private fun testRemoteScriptsEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts" - testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance") - } - - private fun testCapabilityCliEnhancementAndValidation() { - val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/capability_cli" - testComponentInvokeEnhancementAndValidation(basePath, "capability_cli-enhance") - } - - private fun testComponentInvokeEnhancementAndValidation(basePath: String, targetDirName: String) { - runBlocking { - val targetPath = normalizedPathName("target/blueprints/enrichment", targetDirName) - - deleteDir(targetPath) - - val bluePrintContext = bluePrintEnhancerService.enhance(basePath, targetPath) - Assert.assertNotNull("failed to get blueprintContext ", bluePrintContext) - - // Validate the Generated Blueprints - val valid = bluePrintValidatorService.validateBlueprints(targetPath) - Assert.assertTrue("blueprint($basePath) validation failed ", valid) - - // Enable this to get the enhanced zip file - // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip") - // normalizedFile(targetPath).compress(compressFile) - - deleteDir(targetPath) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt index 3112bfb66..8ee2eb3a2 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt @@ -24,7 +24,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired @@ -57,15 +57,15 @@ class ModelTypeServiceTest { val content = JacksonUtils.getClassPathFileContent("model_type/data_type/datatype-property.json") var modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" modelType = modelTypeHandler!!.saveModel(modelType) @@ -110,11 +110,11 @@ class ModelTypeServiceTest { Assert.assertNotNull("Failed to get response for api call getModelByName ", dbModelType) Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbModelType!!.modelName) - val dbDatatypeModelTypes = modelTypeHandler.getModelTypeByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) + val dbDatatypeModelTypes = modelTypeHandler.getModelTypeByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE) Assert.assertNotNull("Failed to find getModelTypeByDefinitionType by tags", dbDatatypeModelTypes) Assert.assertTrue("Failed to find getModelTypeByDefinitionType by count", dbDatatypeModelTypes.size > 0) - val dbModelTypeByDerivedFroms = modelTypeHandler.getModelTypeByDerivedFrom(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT) + val dbModelTypeByDerivedFroms = modelTypeHandler.getModelTypeByDerivedFrom(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT) Assert.assertNotNull("Failed to find getModelTypeByDerivedFrom by tags", dbModelTypeByDerivedFroms) Assert.assertTrue("Failed to find getModelTypeByDerivedFrom by count", dbModelTypeByDerivedFroms.size > 0) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt index 9bc8c6291..ca85ed22f 100644 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt @@ -23,7 +23,7 @@ import org.junit.runner.RunWith import org.junit.runners.MethodSorters import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired @@ -59,15 +59,15 @@ class ModelTypeReactRepositoryTest { val content = normalizedFile("./src/test/resources/model_type/data_type/datatype-property.json") .readText(Charset.defaultCharset()) val modelType = ModelType() - modelType.definitionType = BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE - modelType.derivedFrom = BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT modelType.description = "Definition for Sample Datatype " modelType.definition = JacksonUtils.jsonNode(content) modelType.modelName = modelName modelType.version = "1.0.0" modelType.tags = ( - "test-datatype ," + BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + - BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE + "test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," + + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE ) modelType.updatedBy = "xxxxxx@xxx.com" @@ -81,11 +81,11 @@ class ModelTypeReactRepositoryTest { Assert.assertNotNull("Failed to findByModelName ", dbFindByModelName) val dbFindByDefinitionType = - modelTypeReactRepository.findByDefinitionType(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block() + modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block() Assert.assertNotNull("Failed to findByDefinitionType ", dbFindByDefinitionType) Assert.assertTrue("Failed to findByDefinitionType count", dbFindByDefinitionType!!.size > 0) - val dbFindByDerivedFrom = modelTypeReactRepository.findByDerivedFrom(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT).collectList().block() + val dbFindByDerivedFrom = modelTypeReactRepository.findByDerivedFrom(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT).collectList().block() Assert.assertNotNull("Failed to find findByDerivedFrom", dbFindByDerivedFrom) Assert.assertTrue("Failed to find findByDerivedFrom by count", dbFindByDerivedFrom!!.size > 0) @@ -94,12 +94,12 @@ class ModelTypeReactRepositoryTest { Assert.assertTrue("Failed to findByModelNameIn by count", dbFindByModelNameIn!!.size > 0) val dbFindByDefinitionTypeIn = - modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BlueprintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block() + modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block() Assert.assertNotNull("Failed to findByDefinitionTypeIn", dbFindByDefinitionTypeIn) Assert.assertTrue("Failed to findByDefinitionTypeIn by count", dbFindByDefinitionTypeIn!!.size > 0) val dbFindByDerivedFromIn = - modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BlueprintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block() + modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block() Assert.assertNotNull("Failed to find findByDerivedFromIn", dbFindByDerivedFromIn) Assert.assertTrue("Failed to find findByDerivedFromIn by count", dbFindByDerivedFromIn!!.size > 0) } diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt new file mode 100644 index 000000000..c644aeedd --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils + +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart +import org.onap.ccsdk.cds.controllerblueprints.core.compress +import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile +import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName +import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs +import java.util.UUID +import kotlin.test.assertTrue + +class BluePrintEnhancerUtilsTest { + + private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + private val blueprintArchivePath: String = "./target/blueprints/archive" + private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment" + private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip") + + @Before + fun setUp() { + val archiveDir = normalizedFile(blueprintArchivePath).reCreateDirs() + assertTrue(archiveDir.exists(), "failed to create archiveDir(${archiveDir.absolutePath}") + val enhancerDir = normalizedFile(blueprintEnrichmentPath).reCreateDirs() + assertTrue(enhancerDir.exists(), "failed to create enhancerDir(${enhancerDir.absolutePath}") + val blueprintFile = normalizedFile(blueprintDir) + val testZipFile = blueprintFile.compress(zipBlueprintFileName) + assertTrue(testZipFile.exists(), "Failed to create blueprint test zip(${testZipFile.absolutePath}") + } + + @After + fun tearDown() { + deleteDir(blueprintArchivePath) + deleteDir(blueprintEnrichmentPath) + } + + @Test + fun testFilePartCompressionNDeCompression() { + val filePart = MockFilePart(zipBlueprintFileName) + + runBlocking { + val enhanceId = UUID.randomUUID().toString() + val blueprintArchiveLocation = normalizedPathName(blueprintArchivePath, enhanceId) + val blueprintEnrichmentLocation = normalizedPathName(blueprintEnrichmentPath, enhanceId) + BluePrintEnhancerUtils.copyFilePartToEnhanceDir(filePart, blueprintArchiveLocation, blueprintEnrichmentLocation) + BluePrintEnhancerUtils.compressEnhanceDirAndReturnFilePart(blueprintEnrichmentLocation, blueprintArchiveLocation) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt deleted file mode 100644 index 461af84c4..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintEnhancerUtilsTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils - -import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Test -import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart -import org.onap.ccsdk.cds.controllerblueprints.core.compress -import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile -import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs -import java.util.UUID -import kotlin.test.assertTrue - -class BlueprintEnhancerUtilsTest { - - private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - private val blueprintArchivePath: String = "./target/blueprints/archive" - private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment" - private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip") - - @Before - fun setUp() { - val archiveDir = normalizedFile(blueprintArchivePath).reCreateDirs() - assertTrue(archiveDir.exists(), "failed to create archiveDir(${archiveDir.absolutePath}") - val enhancerDir = normalizedFile(blueprintEnrichmentPath).reCreateDirs() - assertTrue(enhancerDir.exists(), "failed to create enhancerDir(${enhancerDir.absolutePath}") - val blueprintFile = normalizedFile(blueprintDir) - val testZipFile = blueprintFile.compress(zipBlueprintFileName) - assertTrue(testZipFile.exists(), "Failed to create blueprint test zip(${testZipFile.absolutePath}") - } - - @After - fun tearDown() { - deleteDir(blueprintArchivePath) - deleteDir(blueprintEnrichmentPath) - } - - @Test - fun testFilePartCompressionNDeCompression() { - val filePart = MockFilePart(zipBlueprintFileName) - - runBlocking { - val enhanceId = UUID.randomUUID().toString() - val blueprintArchiveLocation = normalizedPathName(blueprintArchivePath, enhanceId) - val blueprintEnrichmentLocation = normalizedPathName(blueprintEnrichmentPath, enhanceId) - BlueprintEnhancerUtils.copyFilePartToEnhanceDir(filePart, blueprintArchiveLocation, blueprintEnrichmentLocation) - BlueprintEnhancerUtils.compressEnhanceDirAndReturnFilePart(blueprintEnrichmentLocation, blueprintArchiveLocation) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt index ab1f9eb54..c1532cd35 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt @@ -38,7 +38,7 @@ open class HealthCheckProperties { @Value("#{'\${cdslistener.healthcheck.mapping-service-name-with-service-link:}'.split(']')}") private val cdsListenerServiceMapping: List? = null - open fun getBlueprintBaseURL(): String? { + open fun getBluePrintBaseURL(): String? { return bluePrintProcessorBaseURL } @@ -46,7 +46,7 @@ open class HealthCheckProperties { return cdsListenerBaseURL } - open fun getBlueprintServiceInformation(): List { + open fun getBluePrintServiceInformation(): List { val serviceName = ServiceName.BLUEPRINT return getListOfServiceEndPoints(blueprintprocessorServiceMapping, serviceName) } diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt index 6bfc182e4..6d49ebe65 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt @@ -33,7 +33,7 @@ import org.slf4j.LoggerFactory */ abstract class AbstractHealthCheck(private val endPointExecution: EndPointExecution) { - private var logger = LoggerFactory.getLogger(BlueprintProcessorHealthCheck::class.java) + private var logger = LoggerFactory.getLogger(BluePrintProcessorHealthCheck::class.java) private fun retrieveSystemStatus(list: List): HealthApiResponse { val healthApiResponse: HealthApiResponse diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt new file mode 100644 index 000000000..dddad52e2 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt @@ -0,0 +1,40 @@ +/* + * Copyright © 2019-2020 Orange. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health + +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution +import org.springframework.stereotype.Service + +/** + * Service for checking health for other CDS services . + * + * @author Shaaban Ebrahim + * @version 1.0 + */ +@Service +open class BluePrintProcessorHealthCheck( + private val endPointExecution: EndPointExecution, + private val healthCheckProperties: HealthCheckProperties +) : + AbstractHealthCheck(endPointExecution) { + + override fun setupServiceEndpoint(): List { + return healthCheckProperties.getBluePrintServiceInformation() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BlueprintProcessorHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BlueprintProcessorHealthCheck.kt deleted file mode 100644 index 9ffa82442..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BlueprintProcessorHealthCheck.kt +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright © 2019-2020 Orange. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health - -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution -import org.springframework.stereotype.Service - -/** - * Service for checking health for other CDS services . - * - * @author Shaaban Ebrahim - * @version 1.0 - */ -@Service -open class BlueprintProcessorHealthCheck( - private val endPointExecution: EndPointExecution, - private val healthCheckProperties: HealthCheckProperties -) : - AbstractHealthCheck(endPointExecution) { - - override fun setupServiceEndpoint(): List { - return healthCheckProperties.getBlueprintServiceInformation() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt index 186d4190b..e3ba72428 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt @@ -31,7 +31,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthChec import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution -import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.BlueprintProcessorHealthCheck +import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.BluePrintProcessorHealthCheck import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService @@ -52,12 +52,12 @@ class HealthCheckServiceTest { @InjectMocks private var endPointExecution: EndPointExecution? = null - private var bluePrintProcessorHealthCheck: BlueprintProcessorHealthCheck? = null + private var bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck? = null @Before fun setup() { endPointExecution = Mockito.spy(endPointExecution!!) - Mockito.`when`(healthCheckProperties!!.getBlueprintServiceInformation()).thenReturn( + Mockito.`when`(healthCheckProperties!!.getBluePrintServiceInformation()).thenReturn( Arrays.asList( ServiceEndpoint("Execution service ", "http://cds-blueprints-processor-http:8080/api/v1/execution-service/health-check"), ServiceEndpoint("Resources service", "http://cds-blueprints-processor-http:8080/api/v1/resources/health-check"), @@ -65,7 +65,7 @@ class HealthCheckServiceTest { ) ) - bluePrintProcessorHealthCheck = BlueprintProcessorHealthCheck(endPointExecution!!, healthCheckProperties) + bluePrintProcessorHealthCheck = BluePrintProcessorHealthCheck(endPointExecution!!, healthCheckProperties) } @Test diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt index d2206df51..d2f02028c 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt @@ -28,7 +28,7 @@ import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.bind.annotation.RestController /** - * Exposes API for checking Metrics of Blueprint processor and CDSListener. + * Exposes API for checking Metrics of BluePrint processor and CDSListener. * * @author Shaaban Ebrahim * @version 1.0 @@ -37,7 +37,7 @@ import org.springframework.web.bind.annotation.RestController @RequestMapping("/api/v1/combinedMetrics") @Api( value = "/api/v1/combinedMetrics", - description = "gather all Metrics info from Blueprint and CDSListener" + description = "gather all Metrics info from BluePrint and CDSListener" ) open class CombinedMetrics(private val combinedMetricsService: CombinedMetricsService) { diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt index c7652010b..f4c3e93bf 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt @@ -23,7 +23,7 @@ import org.springframework.boot.actuate.health.Status import org.springframework.stereotype.Service /** - *Service for combined health (BlueprintProcessor and CDSListener) + *Service for combined health (BluePrintProcessor and CDSListener) * * @author Shaaban Ebrahim * @version 1.0 @@ -36,7 +36,7 @@ open class CombinedHealthService( private fun setupServiceEndpoint(): List { return listOf( - ServiceEndpoint("BlueprintProcessor Health Check ", healthCheckProperties.getBlueprintBaseURL() + "actuator/health"), + ServiceEndpoint("BluePrintProcessor Health Check ", healthCheckProperties.getBluePrintBaseURL() + "actuator/health"), ServiceEndpoint("CDSListener Health Check", healthCheckProperties.getCDSListenerBaseURL() + "actuator/health") ) } diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt index b4d54f65e..0a2e7ae24 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt @@ -27,7 +27,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientSer import org.springframework.stereotype.Service /** - *Service for combined Metrics for CDS Listener and BlueprintProcessor + *Service for combined Metrics for CDS Listener and BluePrintProcessor * * @author Shaaban Ebrahim * @version 1.0 @@ -41,7 +41,7 @@ open class CombinedMetricsService( private fun setupServiceEndpoint(): List { return listOf( - ServiceEndpoint("BlueprintProcessor metrics", healthCheckProperties.getBlueprintBaseURL() + "/actuator/metrics"), + ServiceEndpoint("BluePrintProcessor metrics", healthCheckProperties.getBluePrintBaseURL() + "/actuator/metrics"), ServiceEndpoint("CDS Listener metrics", healthCheckProperties.getCDSListenerBaseURL() + "/actuator/metrics") ) } diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt index 5c35fc377..1f3d256b3 100644 --- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt +++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt @@ -18,10 +18,10 @@ package org.onap.ccsdk.cds.blueprintsprocessor.healthapi /* import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentScriptExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.context.annotation.ComponentScan @@ -41,8 +41,8 @@ import org.springframework.test.web.reactive.server.WebTestClient @RunWith(SpringRunner::class) @WebFluxTest @ContextConfiguration( - classes = [BlueprintRuntimeService::class, BlueprintCoreConfiguration::class, - BlueprintCatalogService::class, ComponentScriptExecutor::class] + classes = [BluePrintRuntimeService::class, BluePrintCoreConfiguration::class, + BluePrintCatalogService::class, ComponentScriptExecutor::class] ) @ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) @TestPropertySource(locations = ["classpath:application-test.properties"]) diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt index 77471bd58..40d6f56cb 100644 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt @@ -22,7 +22,7 @@ import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolution import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionDBService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils @@ -242,7 +242,7 @@ class ResourceControllerTest { resourceAssignment.dictionaryName = "dd$prefix" resourceAssignment.dictionarySource = "source$prefix" resourceAssignment.version = 2 - resourceAssignment.status = BlueprintConstants.STATUS_SUCCESS + resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS resourceAssignment.property = property return resourceAssignment } diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt index ff9aadb19..945a30c64 100644 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt @@ -19,9 +19,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.resource.api import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest @@ -38,8 +38,8 @@ import kotlin.test.AfterTest @WebFluxTest @ContextConfiguration( classes = [ - TestDatabaseConfiguration::class, BlueprintCoreConfiguration::class, - BlueprintCatalogService::class, ErrorCatalogTestConfiguration::class + TestDatabaseConfiguration::class, BluePrintCoreConfiguration::class, + BluePrintCatalogService::class, ErrorCatalogTestConfiguration::class ] ) @ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt index 61d1595e8..6d87d2735 100644 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.resource.api -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary", diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt new file mode 100644 index 000000000..79106c24a --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt @@ -0,0 +1,111 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.grpc.Status +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toJava +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput +import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes +import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault +import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault +import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService +import org.slf4j.LoggerFactory +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.stereotype.Service +import java.util.concurrent.Phaser +import javax.annotation.PreDestroy + +@Service +open class BluePrintProcessingGRPCHandler( + private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val executionServiceHandler: ExecutionServiceHandler, + private val errorCatalogService: ErrorCatalogService +) : + BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { + + private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java) + + private val ph = Phaser(1) + + @PreAuthorize("hasRole('USER')") + override fun process( + responseObserver: StreamObserver + ): StreamObserver { + + return object : StreamObserver { + override fun onNext(executionServiceInput: ExecutionServiceInput) { + try { + ph.register() + runBlocking { + executionServiceHandler.process(executionServiceInput.toJava(), responseObserver) + } + } catch (e: Exception) { + onError(e) + } finally { + ph.arriveAndDeregister() + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + if (error is BluePrintProcessorException) onErrorCatalog(error) else onError(error) + } + + fun onError(error: Exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription(error.errorMessageOrDefault()) + .withCause(error.errorCauseOrDefault()) + .asException() + ) + } + + fun onErrorCatalog(error: BluePrintProcessorException) { + if (error.protocol == "") { + error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) + } + val errorPayload = errorCatalogService.errorPayload(error) + val grpcCode = Status.fromCodeValue(errorPayload.code) + responseObserver.onError( + grpcCode + .withDescription(errorPayload.message) + .withCause(error.errorCauseOrDefault()) + .asException() + ) + } + + override fun onCompleted() { + log.info("Completed") + } + } + } + + @PreDestroy + fun preDestroy() { + val name = "BluePrintProcessingGRPCHandler" + log.info("Starting to shutdown $name waiting for in-flight requests to finish ...") + ph.arriveAndAwaitAdvance() + log.info("Done waiting in $name") + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt new file mode 100644 index 000000000..4d735d9e7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt @@ -0,0 +1,157 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2021 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.micrometer.core.instrument.MeterRegistry +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.channels.consumeEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageMetricConstants +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService +import org.onap.ccsdk.cds.blueprintsprocessor.message.utils.BlueprintMessageUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsType +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +import org.springframework.boot.context.event.ApplicationReadyEvent +import org.springframework.context.event.EventListener +import org.springframework.stereotype.Service +import java.nio.charset.Charset +import java.util.UUID +import java.util.concurrent.Phaser +import javax.annotation.PreDestroy + +@ConditionalOnProperty( + name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"], + havingValue = "true" +) +@Service +open class BluePrintProcessingKafkaConsumer( + private val blueprintMessageLibPropertyService: BluePrintMessageLibPropertyService, + private val executionServiceHandler: ExecutionServiceHandler, + private val meterRegistry: MeterRegistry +) { + + val log = logger(BluePrintProcessingKafkaConsumer::class) + + private val ph = Phaser(1) + + private lateinit var blueprintMessageConsumerService: BlueprintMessageConsumerService + + companion object { + + const val CONSUMER_SELECTOR = "self-service-api" + const val PRODUCER_SELECTOR = "self-service-api" + } + + @EventListener(ApplicationReadyEvent::class) + fun setupMessageListener() = GlobalScope.launch { + try { + log.info( + "Setting up message consumer($CONSUMER_SELECTOR)" + + "message producer($PRODUCER_SELECTOR)..." + ) + + /** Get the Message Consumer Service **/ + blueprintMessageConsumerService = try { + blueprintMessageLibPropertyService + .blueprintMessageConsumerService(CONSUMER_SELECTOR) + } catch (e: BluePrintProcessorException) { + val errorMsg = "Failed creating Kafka consumer message service." + throw e.updateErrorMessage( + SelfServiceApiDomains.SELF_SERVICE_API, errorMsg, + "Wrong Kafka selector provided or internal error in Kafka service." + ) + } catch (e: Exception) { + throw BluePrintProcessorException("failed to create consumer service ${e.message}") + } + + /** Get the Message Producer Service **/ + val blueprintMessageProducerService = try { + blueprintMessageLibPropertyService + .blueprintMessageProducerService(PRODUCER_SELECTOR) + } catch (e: BluePrintProcessorException) { + val errorMsg = "Failed creating Kafka producer message service." + throw e.updateErrorMessage( + SelfServiceApiDomains.SELF_SERVICE_API, errorMsg, + "Wrong Kafka selector provided or internal error in Kafka service." + ) + } catch (e: Exception) { + throw BluePrintProcessorException("failed to create producer service ${e.message}") + } + + launch { + /** Subscribe to the consumer topics */ + val additionalConfig: MutableMap = hashMapOf() + val channel = blueprintMessageConsumerService.subscribe(additionalConfig) + channel.consumeEach { message -> + launch { + try { + ph.register() + val key = message.key() ?: UUID.randomUUID().toString() + val value = String(message.value(), Charset.defaultCharset()) + val executionServiceInput = value.jsonAsType() + log.info( + "Consumed Message : topic(${message.topic()}) " + + "partition(${message.partition()}) " + + "leaderEpoch(${message.leaderEpoch().get()}) " + + "offset(${message.offset()}) " + + "key(${message.key()}) " + + "CBA(${executionServiceInput.actionIdentifiers.blueprintName}/${executionServiceInput.actionIdentifiers.blueprintVersion}/${executionServiceInput.actionIdentifiers.actionName})" + ) + val executionServiceOutput = executionServiceHandler.doProcess(executionServiceInput) + blueprintMessageProducerService.sendMessage(key, executionServiceOutput) + } catch (e: Exception) { + meterRegistry.counter( + BlueprintMessageMetricConstants.KAFKA_CONSUMED_MESSAGES_ERROR_COUNTER, + BlueprintMessageUtils.kafkaMetricTag(message.topic()) + ).increment() + log.error("failed in processing the consumed message : $message", e) + } finally { + ph.arriveAndDeregister() + } + } + } + } + } catch (e: Exception) { + log.error( + "failed to start message consumer($CONSUMER_SELECTOR) " + + "message producer($PRODUCER_SELECTOR) ", + e + ) + } + } + + @PreDestroy + fun shutdownMessageListener() = runBlocking { + try { + log.info( + "Shutting down message consumer($CONSUMER_SELECTOR)" + + "message producer($PRODUCER_SELECTOR)..." + ) + blueprintMessageConsumerService.shutDown() + ph.arriveAndAwaitAdvance() + } catch (e: Exception) { + log.error("failed to shutdown message listener($CONSUMER_SELECTOR)", e) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandler.kt deleted file mode 100644 index 98577db26..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandler.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api - -import io.grpc.Status -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toJava -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput -import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes -import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault -import org.onap.ccsdk.cds.error.catalog.core.utils.errorMessageOrDefault -import org.onap.ccsdk.cds.error.catalog.services.ErrorCatalogService -import org.slf4j.LoggerFactory -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.stereotype.Service -import java.util.concurrent.Phaser -import javax.annotation.PreDestroy - -@Service -open class BlueprintProcessingGRPCHandler( - private val bluePrintCoreConfiguration: BlueprintCoreConfiguration, - private val executionServiceHandler: ExecutionServiceHandler, - private val errorCatalogService: ErrorCatalogService -) : - BlueprintProcessingServiceGrpc.BlueprintProcessingServiceImplBase() { - - private val log = LoggerFactory.getLogger(BlueprintProcessingGRPCHandler::class.java) - - private val ph = Phaser(1) - - @PreAuthorize("hasRole('USER')") - override fun process( - responseObserver: StreamObserver - ): StreamObserver { - - return object : StreamObserver { - override fun onNext(executionServiceInput: ExecutionServiceInput) { - try { - ph.register() - runBlocking { - executionServiceHandler.process(executionServiceInput.toJava(), responseObserver) - } - } catch (e: Exception) { - onError(e) - } finally { - ph.arriveAndDeregister() - } - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - if (error is BlueprintProcessorException) onErrorCatalog(error) else onError(error) - } - - fun onError(error: Exception) { - responseObserver.onError( - Status.INTERNAL - .withDescription(error.errorMessageOrDefault()) - .withCause(error.errorCauseOrDefault()) - .asException() - ) - } - - fun onErrorCatalog(error: BlueprintProcessorException) { - if (error.protocol == "") { - error.grpc(ErrorCatalogCodes.GENERIC_FAILURE) - } - val errorPayload = errorCatalogService.errorPayload(error) - val grpcCode = Status.fromCodeValue(errorPayload.code) - responseObserver.onError( - grpcCode - .withDescription(errorPayload.message) - .withCause(error.errorCauseOrDefault()) - .asException() - ) - } - - override fun onCompleted() { - log.info("Completed") - } - } - } - - @PreDestroy - fun preDestroy() { - val name = "BlueprintProcessingGRPCHandler" - log.info("Starting to shutdown $name waiting for in-flight requests to finish ...") - ph.arriveAndAwaitAdvance() - log.info("Done waiting in $name") - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumer.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumer.kt deleted file mode 100644 index 661e76b2b..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumer.kt +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2021 Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api - -import io.micrometer.core.instrument.MeterRegistry -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.channels.consumeEach -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageMetricConstants -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService -import org.onap.ccsdk.cds.blueprintsprocessor.message.utils.BlueprintMessageUtils -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsType -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.updateErrorMessage -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty -import org.springframework.boot.context.event.ApplicationReadyEvent -import org.springframework.context.event.EventListener -import org.springframework.stereotype.Service -import java.nio.charset.Charset -import java.util.UUID -import java.util.concurrent.Phaser -import javax.annotation.PreDestroy - -@ConditionalOnProperty( - name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"], - havingValue = "true" -) -@Service -open class BlueprintProcessingKafkaConsumer( - private val blueprintMessageLibPropertyService: BlueprintMessageLibPropertyService, - private val executionServiceHandler: ExecutionServiceHandler, - private val meterRegistry: MeterRegistry -) { - - val log = logger(BlueprintProcessingKafkaConsumer::class) - - private val ph = Phaser(1) - - private lateinit var blueprintMessageConsumerService: BlueprintMessageConsumerService - - companion object { - - const val CONSUMER_SELECTOR = "self-service-api" - const val PRODUCER_SELECTOR = "self-service-api" - } - - @EventListener(ApplicationReadyEvent::class) - fun setupMessageListener() = GlobalScope.launch { - try { - log.info( - "Setting up message consumer($CONSUMER_SELECTOR)" + - "message producer($PRODUCER_SELECTOR)..." - ) - - /** Get the Message Consumer Service **/ - blueprintMessageConsumerService = try { - blueprintMessageLibPropertyService - .blueprintMessageConsumerService(CONSUMER_SELECTOR) - } catch (e: BlueprintProcessorException) { - val errorMsg = "Failed creating Kafka consumer message service." - throw e.updateErrorMessage( - SelfServiceApiDomains.SELF_SERVICE_API, errorMsg, - "Wrong Kafka selector provided or internal error in Kafka service." - ) - } catch (e: Exception) { - throw BlueprintProcessorException("failed to create consumer service ${e.message}") - } - - /** Get the Message Producer Service **/ - val blueprintMessageProducerService = try { - blueprintMessageLibPropertyService - .blueprintMessageProducerService(PRODUCER_SELECTOR) - } catch (e: BlueprintProcessorException) { - val errorMsg = "Failed creating Kafka producer message service." - throw e.updateErrorMessage( - SelfServiceApiDomains.SELF_SERVICE_API, errorMsg, - "Wrong Kafka selector provided or internal error in Kafka service." - ) - } catch (e: Exception) { - throw BlueprintProcessorException("failed to create producer service ${e.message}") - } - - launch { - /** Subscribe to the consumer topics */ - val additionalConfig: MutableMap = hashMapOf() - val channel = blueprintMessageConsumerService.subscribe(additionalConfig) - channel.consumeEach { message -> - launch { - try { - ph.register() - val key = message.key() ?: UUID.randomUUID().toString() - val value = String(message.value(), Charset.defaultCharset()) - val executionServiceInput = value.jsonAsType() - log.info( - "Consumed Message : topic(${message.topic()}) " + - "partition(${message.partition()}) " + - "leaderEpoch(${message.leaderEpoch().get()}) " + - "offset(${message.offset()}) " + - "key(${message.key()}) " + - "CBA(${executionServiceInput.actionIdentifiers.blueprintName}/${executionServiceInput.actionIdentifiers.blueprintVersion}/${executionServiceInput.actionIdentifiers.actionName})" - ) - val executionServiceOutput = executionServiceHandler.doProcess(executionServiceInput) - blueprintMessageProducerService.sendMessage(key, executionServiceOutput) - } catch (e: Exception) { - meterRegistry.counter( - BlueprintMessageMetricConstants.KAFKA_CONSUMED_MESSAGES_ERROR_COUNTER, - BlueprintMessageUtils.kafkaMetricTag(message.topic()) - ).increment() - log.error("failed in processing the consumed message : $message", e) - } finally { - ph.arriveAndDeregister() - } - } - } - } - } catch (e: Exception) { - log.error( - "failed to start message consumer($CONSUMER_SELECTOR) " + - "message producer($PRODUCER_SELECTOR) ", - e - ) - } - } - - @PreDestroy - fun shutdownMessageListener() = runBlocking { - try { - log.info( - "Shutting down message consumer($CONSUMER_SELECTOR)" + - "message producer($PRODUCER_SELECTOR)..." - ) - blueprintMessageConsumerService.shutDown() - ph.arriveAndAwaitAdvance() - } catch (e: Exception) { - log.error("failed to shutdown message listener($CONSUMER_SELECTOR)", e) - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt index 6c6c26c43..bb7ecc6ad 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt @@ -27,11 +27,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutp import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.optionalClusterService import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.mdcWebCoroutineScope import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.determineHttpStatusCode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.MediaType @@ -70,8 +70,8 @@ open class ExecutionServiceController { suspend fun executionServiceControllerHealthCheck(): ResponseEntity = mdcWebCoroutineScope { var body = mutableMapOf("success" to true) var statusCode = 200 - if (BlueprintConstants.CLUSTER_ENABLED && - BlueprintDependencyService.optionalClusterService()?.clusterJoined() != true + if (BluePrintConstants.CLUSTER_ENABLED && + BluePrintDependencyService.optionalClusterService()?.clusterJoined() != true ) { statusCode = 503 body.remove("success") diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt index 8c958c4b4..e604987a7 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt @@ -34,21 +34,21 @@ import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.SelfServiceMetricC import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.cbaMetricTags import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractServiceFunction import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.config.BlueprintLoadConfiguration -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service class ExecutionServiceHandler( - private val bluePrintLoadConfiguration: BlueprintLoadConfiguration, - private val blueprintsProcessorCatalogService: BlueprintCatalogService, + private val bluePrintLoadConfiguration: BluePrintLoadConfiguration, + private val blueprintsProcessorCatalogService: BluePrintCatalogService, private val bluePrintWorkflowExecutionService: - BlueprintWorkflowExecutionService, + BluePrintWorkflowExecutionService, private val publishAuditService: PublishAuditService, private val meterRegistry: MeterRegistry ) { @@ -111,14 +111,14 @@ class ExecutionServiceHandler( val basePath = blueprintsProcessorCatalogService.getFromDatabase(blueprintName, blueprintVersion) log.info("blueprint base path $basePath") - val blueprintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime(requestId, basePath.toString()) + val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString()) - executionServiceOutput = bluePrintWorkflowExecutionService.executeBlueprintWorkflow( + executionServiceOutput = bluePrintWorkflowExecutionService.executeBluePrintWorkflow( blueprintRuntimeService, executionServiceInput, hashMapOf() ) - val errors = blueprintRuntimeService.getBlueprintError().allErrors() + val errors = blueprintRuntimeService.getBluePrintError().allErrors() if (errors.isNotEmpty()) { setErrorStatus(errors.joinToString(", "), executionServiceOutput.status) } @@ -144,7 +144,7 @@ class ExecutionServiceHandler( /** If no blueprint is needed, then get the Service function instance mapping to the action name and execute it */ suspend fun executeServiceFunction(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { val actionName = executionServiceInput.actionIdentifiers.actionName - val instance = BlueprintDependencyService.instance(actionName) + val instance = BluePrintDependencyService.instance(actionName) checkNotNull(instance) { "failed to initialize service function($actionName)" } instance.actionName = actionName return instance.applyNB(executionServiceInput) @@ -154,7 +154,7 @@ class ExecutionServiceHandler( status.errorMessage = errorMessage status.eventType = EventType.EVENT_COMPONENT_FAILURE.name status.code = 500 - status.message = BlueprintConstants.STATUS_FAILURE + status.message = BluePrintConstants.STATUS_FAILURE } private fun response( @@ -173,7 +173,7 @@ class ExecutionServiceHandler( } else { status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name status.code = 200 - status.message = BlueprintConstants.STATUS_PROCESSING + status.message = BluePrintConstants.STATUS_PROCESSING } executionServiceOutput.status = status diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/KafkaPublishAuditService.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/KafkaPublishAuditService.kt index 46befee8a..ce407bc8c 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/KafkaPublishAuditService.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/KafkaPublishAuditService.kt @@ -22,16 +22,16 @@ import com.fasterxml.jackson.databind.node.ObjectNode import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageProducerService -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.service.PropertyAssignmentService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.PropertyDefinitionUtils import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment @@ -57,8 +57,8 @@ import javax.annotation.PostConstruct ) @Service class KafkaPublishAuditService( - private val bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService, - private val blueprintsProcessorCatalogService: BlueprintCatalogService + private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService, + private val blueprintsProcessorCatalogService: BluePrintCatalogService ) : PublishAuditService { private var inputInstance: BlueprintMessageProducerService? = null @@ -166,7 +166,7 @@ class KafkaPublishAuditService( val basePath = blueprintsProcessorCatalogService.getFromDatabase(blueprintName, blueprintVersion) - val blueprintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime(requestId, basePath.toString()) + val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString()) val blueprintContext = blueprintRuntimeService.bluePrintContext() blueprintContext.workflowSteps(workflowName).forEach { step -> @@ -175,9 +175,9 @@ class KafkaPublishAuditService( val nodeTemplate = blueprintContext.nodeTemplateByName(nodeTemplateName) /** We need to check in his Node Template Dependencies is case of a Node Template DG */ - if (nodeTemplate.type == BlueprintConstants.NODE_TEMPLATE_TYPE_DG) { + if (nodeTemplate.type == BluePrintConstants.NODE_TEMPLATE_TYPE_DG) { val dependencyNodeTemplate = - nodeTemplate.properties?.get(BlueprintConstants.PROPERTY_DG_DEPENDENCY_NODE_TEMPLATE) as ArrayNode + nodeTemplate.properties?.get(BluePrintConstants.PROPERTY_DG_DEPENDENCY_NODE_TEMPLATE) as ArrayNode dependencyNodeTemplate.forEach { dependencyNodeTemplateName -> clonedExecutionServiceInput = hideSensitiveDataFromResourceResolution( blueprintRuntimeService, @@ -220,15 +220,15 @@ class KafkaPublishAuditService( * @return [executionServiceInput] with sensitive inputs replaced by a generic string */ private suspend fun hideSensitiveDataFromResourceResolution( - blueprintRuntimeService: BlueprintRuntimeService>, - blueprintContext: BlueprintContext, + blueprintRuntimeService: BluePrintRuntimeService>, + blueprintContext: BluePrintContext, executionServiceInput: ExecutionServiceInput, workflowName: String, nodeTemplateName: String ): ExecutionServiceInput { val nodeTemplate = blueprintContext.nodeTemplateByName(nodeTemplateName) - if (nodeTemplate.type == BlueprintConstants.NODE_TEMPLATE_TYPE_COMPONENT_RESOURCE_RESOLUTION) { + if (nodeTemplate.type == BluePrintConstants.NODE_TEMPLATE_TYPE_COMPONENT_RESOURCE_RESOLUTION) { val interfaceName = blueprintContext.nodeTemplateFirstInterfaceName(nodeTemplateName) val operationName = blueprintContext.nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName) @@ -242,7 +242,7 @@ class KafkaPublishAuditService( val artifactPrefixNamesNode = propertyAssignments[ResourceResolutionConstants.INPUT_ARTIFACT_PREFIX_NAMES] val propertyAssignmentService = PropertyAssignmentService(blueprintRuntimeService) val artifactPrefixNamesNodeValue = propertyAssignmentService.resolveAssignmentExpression( - BlueprintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, + BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TEMPLATE, nodeTemplateName, ResourceResolutionConstants.INPUT_ARTIFACT_PREFIX_NAMES, artifactPrefixNamesNode!! diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtils.kt index c04410a2f..17f7722c4 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtils.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtils.kt @@ -18,8 +18,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils import io.micrometer.core.instrument.Tag import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.springframework.http.HttpStatus import org.springframework.http.codec.multipart.FilePart import org.springframework.util.StringUtils @@ -30,13 +30,13 @@ import java.util.UUID const val INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE = 500 -@Throws(BlueprintException::class, IOException::class) +@Throws(BluePrintException::class, IOException::class) fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Path { val fileName = StringUtils.cleanPath(filePart.filename()) if (StringUtils.getFilenameExtension(fileName) != "zip") { - throw BlueprintException("Invalid file extension required ZIP") + throw BluePrintException("Invalid file extension required ZIP") } val changedFileName = UUID.randomUUID().toString() + ".zip" @@ -68,19 +68,19 @@ fun determineHttpStatusCode(statusCode: Int): HttpStatus { fun cbaMetricTags(executionServiceInput: ExecutionServiceInput): MutableList = executionServiceInput.actionIdentifiers.let { mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_BP_NAME, it.blueprintName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_VERSION, it.blueprintVersion), - Tag.of(BlueprintConstants.METRIC_TAG_BP_ACTION, it.actionName) + Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, it.blueprintName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, it.blueprintVersion), + Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, it.actionName) ) } fun cbaMetricTags(executionServiceOutput: ExecutionServiceOutput): MutableList = executionServiceOutput.let { mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_BP_NAME, it.actionIdentifiers.blueprintName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_VERSION, it.actionIdentifiers.blueprintVersion), - Tag.of(BlueprintConstants.METRIC_TAG_BP_ACTION, it.actionIdentifiers.actionName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_STATUS, it.status.code.toString()), - Tag.of(BlueprintConstants.METRIC_TAG_BP_OUTCOME, it.status.message) + Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, it.actionIdentifiers.blueprintName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, it.actionIdentifiers.blueprintVersion), + Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, it.actionIdentifiers.actionName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_STATUS, it.status.code.toString()), + Tag.of(BluePrintConstants.METRIC_TAG_BP_OUTCOME, it.status.message) ) } diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt new file mode 100644 index 000000000..ff615536b --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt @@ -0,0 +1,29 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.validation.BluePrintDesignTimeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator +import org.springframework.stereotype.Service + +@Service("bluePrintRuntimeValidatorService") +open class BluePrintRuntimeValidatorService( + bluePrintTypeValidatorService: BluePrintTypeValidatorService, + resourceDefinitionValidator: ResourceDefinitionValidator +) : + BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator) diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorService.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorService.kt deleted file mode 100644 index 23d4bf012..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorService.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation - -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintTypeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.validation.BlueprintDesignTimeValidatorService -import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator -import org.springframework.stereotype.Service - -@Service("bluePrintRuntimeValidatorService") -open class BlueprintRuntimeValidatorService( - bluePrintTypeValidatorService: BlueprintTypeValidatorService, - resourceDefinitionValidator: ResourceDefinitionValidator -) : - BlueprintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator) diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt new file mode 100644 index 000000000..0d79368ad --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt @@ -0,0 +1,133 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver +import io.grpc.testing.GrpcServerRule +import io.micrometer.core.instrument.MeterRegistry +import org.junit.Assert +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.annotation.DirtiesContext +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.BeforeTest + +@RunWith(SpringRunner::class) +@DirtiesContext +@ContextConfiguration( + classes = [ + SelfServiceApiTestConfiguration::class, TestDatabaseConfiguration::class, + ErrorCatalogTestConfiguration::class + ] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintProcessingGRPCHandlerTest { + + private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java) + + @MockBean + lateinit var meterRegistry: MeterRegistry + + @get:Rule + val grpcServerRule = GrpcServerRule().directExecutor() + + @Autowired + lateinit var bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler + + lateinit var requestObs: StreamObserver + + @BeforeTest + fun init() { + grpcServerRule.serviceRegistry.addService(bluePrintProcessingGRPCHandler) + + val blockingStub = BluePrintProcessingServiceGrpc.newStub(grpcServerRule.channel) + + requestObs = blockingStub.process(object : StreamObserver { + override fun onNext(executionServiceOuput: ExecutionServiceOutput) { + log.debug("onNext {}", executionServiceOuput) + if ("1234" == executionServiceOuput.commonHeader.requestId) { + Assert.assertEquals( + "Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", + executionServiceOuput.status.errorMessage + ) + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + Assert.assertEquals("INTERNAL: Could not find blueprint : from database", error.message) + } + + override fun onCompleted() { + log.info("Done") + } + }) + } + + @Test + fun testSelfServiceGRPCHandler() { + val commonHeader = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("1234") + .setSubRequestId("1234-56").build() + + val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") + val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder + JsonFormat.parser().merge(jsonContent, payloadBuilder) + + val input = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input) + + val commonHeader2 = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("2345") + .setSubRequestId("1234-56").build() + + val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build() + + val input2 = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader2) + .setActionIdentifiers(actionIdentifier) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input2) + + requestObs.onCompleted() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt new file mode 100644 index 000000000..80e953822 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt @@ -0,0 +1,100 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput +import org.springframework.test.context.ContextConfiguration + +@ContextConfiguration( + classes = [SelfServiceApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] +) +class BluePrintProcessingIntegrationTest { + + private val log = logger(BluePrintProcessingIntegrationTest::class) + + /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ + // @Test + fun integrationTestGrpcManagement() { + runBlocking { + val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { + host = "127.0.0.1" + port = 50052 + type = GRPCLibConstants.TYPE_TOKEN_AUTH + token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" + } + val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) + val channel = basicAuthGrpcClientService.channel() + + val stub = BluePrintProcessingServiceGrpc.newStub(channel) + repeat(1) { + val requestObs = stub.process(object : StreamObserver { + override fun onNext(executionServiceOuput: ExecutionServiceOutput) { + log.info("onNext Received {}", executionServiceOuput) + } + + override fun onError(error: Throwable) { + log.error("Fail to process message", error) + } + + override fun onCompleted() { + log.info("Done") + } + }) + + val commonHeader = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("1234-$it") + .setSubRequestId("1234-56").build() + + val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") + val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder + JsonFormat.parser().merge(jsonContent, payloadBuilder) + + val actionIdentifier = ActionIdentifiers.newBuilder() + .setActionName("SampleScript") + .setBlueprintName("sample-cba") + .setBlueprintVersion("1.0.0") + .build() + + val input = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader) + .setActionIdentifiers(actionIdentifier) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input) + requestObs.onCompleted() + } + delay(1000) + channel.shutdownNow() + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt new file mode 100644 index 000000000..9143d7358 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt @@ -0,0 +1,80 @@ +/* + * Copyright © 2019 IBM. + * Modifications Copyright © 2021 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.micrometer.core.instrument.MeterRegistry +import io.mockk.coEvery +import io.mockk.mockk +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.BluePrintMessageLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.Test +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintMessageLibConfiguration::class, SelfServiceApiTestConfiguration::class, + BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, ErrorCatalogTestConfiguration::class + ] +) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintProcessingKafkaConsumerTest { + + @MockBean + lateinit var meterRegistry: MeterRegistry + + @Autowired + lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService + + @Test + fun testExecutionInputMessageConsumer() { + runBlocking { + assertNotNull( + bluePrintMessageLibPropertyService, + "failed to initialise bluePrintMessageLibPropertyService" + ) + + val executionServiceHandle = mockk() + + coEvery { executionServiceHandle.doProcess(any()) } returns mockk() + + val bluePrintProcessingKafkaConsumer = BluePrintProcessingKafkaConsumer( + bluePrintMessageLibPropertyService, + executionServiceHandle, + meterRegistry + ) + + launch { + bluePrintProcessingKafkaConsumer.setupMessageListener() + } + delay(100) + bluePrintProcessingKafkaConsumer.shutdownMessageListener() + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandlerTest.kt deleted file mode 100644 index 3033103e3..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingGRPCHandlerTest.kt +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api - -import com.google.protobuf.util.JsonFormat -import io.grpc.stub.StreamObserver -import io.grpc.testing.GrpcServerRule -import io.micrometer.core.instrument.MeterRegistry -import org.junit.Assert -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.mock.mockito.MockBean -import org.springframework.test.annotation.DirtiesContext -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.BeforeTest - -@RunWith(SpringRunner::class) -@DirtiesContext -@ContextConfiguration( - classes = [ - SelfServiceApiTestConfiguration::class, TestDatabaseConfiguration::class, - ErrorCatalogTestConfiguration::class - ] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintProcessingGRPCHandlerTest { - - private val log = LoggerFactory.getLogger(BlueprintProcessingGRPCHandlerTest::class.java) - - @MockBean - lateinit var meterRegistry: MeterRegistry - - @get:Rule - val grpcServerRule = GrpcServerRule().directExecutor() - - @Autowired - lateinit var bluePrintProcessingGRPCHandler: BlueprintProcessingGRPCHandler - - lateinit var requestObs: StreamObserver - - @BeforeTest - fun init() { - grpcServerRule.serviceRegistry.addService(bluePrintProcessingGRPCHandler) - - val blockingStub = BlueprintProcessingServiceGrpc.newStub(grpcServerRule.channel) - - requestObs = blockingStub.process(object : StreamObserver { - override fun onNext(executionServiceOuput: ExecutionServiceOutput) { - log.debug("onNext {}", executionServiceOuput) - if ("1234" == executionServiceOuput.commonHeader.requestId) { - Assert.assertEquals( - "Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", - executionServiceOuput.status.errorMessage - ) - } - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - Assert.assertEquals("INTERNAL: Could not find blueprint : from database", error.message) - } - - override fun onCompleted() { - log.info("Done") - } - }) - } - - @Test - fun testSelfServiceGRPCHandler() { - val commonHeader = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId("1234") - .setSubRequestId("1234-56").build() - - val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") - val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder - JsonFormat.parser().merge(jsonContent, payloadBuilder) - - val input = ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader) - .setPayload(payloadBuilder.build()) - .build() - - requestObs.onNext(input) - - val commonHeader2 = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId("2345") - .setSubRequestId("1234-56").build() - - val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build() - - val input2 = ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader2) - .setActionIdentifiers(actionIdentifier) - .setPayload(payloadBuilder.build()) - .build() - - requestObs.onNext(input2) - - requestObs.onCompleted() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingIntegrationTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingIntegrationTest.kt deleted file mode 100644 index d6109727f..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingIntegrationTest.kt +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api - -import com.google.protobuf.util.JsonFormat -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.delay -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.TokenAuthGrpcClientService -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput -import org.springframework.test.context.ContextConfiguration - -@ContextConfiguration( - classes = [SelfServiceApiTestConfiguration::class, ErrorCatalogTestConfiguration::class] -) -class BlueprintProcessingIntegrationTest { - - private val log = logger(BlueprintProcessingIntegrationTest::class) - - /** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/ - // @Test - fun integrationTestGrpcManagement() { - runBlocking { - val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply { - host = "127.0.0.1" - port = 50052 - type = GRPCLibConstants.TYPE_TOKEN_AUTH - token = "Basic Y2NzZGthcHBzOmNjc2RrYXBwcw==" - } - val basicAuthGrpcClientService = TokenAuthGrpcClientService(tokenAuthGrpcClientProperties) - val channel = basicAuthGrpcClientService.channel() - - val stub = BlueprintProcessingServiceGrpc.newStub(channel) - repeat(1) { - val requestObs = stub.process(object : StreamObserver { - override fun onNext(executionServiceOuput: ExecutionServiceOutput) { - log.info("onNext Received {}", executionServiceOuput) - } - - override fun onError(error: Throwable) { - log.error("Fail to process message", error) - } - - override fun onCompleted() { - log.info("Done") - } - }) - - val commonHeader = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId("1234-$it") - .setSubRequestId("1234-56").build() - - val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") - val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder - JsonFormat.parser().merge(jsonContent, payloadBuilder) - - val actionIdentifier = ActionIdentifiers.newBuilder() - .setActionName("SampleScript") - .setBlueprintName("sample-cba") - .setBlueprintVersion("1.0.0") - .build() - - val input = ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader) - .setActionIdentifiers(actionIdentifier) - .setPayload(payloadBuilder.build()) - .build() - - requestObs.onNext(input) - requestObs.onCompleted() - } - delay(1000) - channel.shutdownNow() - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumerTest.kt deleted file mode 100644 index 56cc691a4..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BlueprintProcessingKafkaConsumerTest.kt +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright © 2019 IBM. - * Modifications Copyright © 2021 Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api - -import io.micrometer.core.instrument.MeterRegistry -import io.mockk.coEvery -import io.mockk.mockk -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertiesService -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.BlueprintMessageLibConfiguration -import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageLibPropertyService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.mock.mockito.MockBean -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.Test -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintMessageLibConfiguration::class, SelfServiceApiTestConfiguration::class, - BlueprintPropertyConfiguration::class, BlueprintPropertiesService::class, ErrorCatalogTestConfiguration::class - ] -) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintProcessingKafkaConsumerTest { - - @MockBean - lateinit var meterRegistry: MeterRegistry - - @Autowired - lateinit var bluePrintMessageLibPropertyService: BlueprintMessageLibPropertyService - - @Test - fun testExecutionInputMessageConsumer() { - runBlocking { - assertNotNull( - bluePrintMessageLibPropertyService, - "failed to initialise bluePrintMessageLibPropertyService" - ) - - val executionServiceHandle = mockk() - - coEvery { executionServiceHandle.doProcess(any()) } returns mockk() - - val bluePrintProcessingKafkaConsumer = BlueprintProcessingKafkaConsumer( - bluePrintMessageLibPropertyService, - executionServiceHandle, - meterRegistry - ) - - launch { - bluePrintProcessingKafkaConsumer.setupMessageListener() - } - delay(100) - bluePrintProcessingKafkaConsumer.shutdownMessageListener() - } - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt index f18471127..d7d7aaa2a 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt @@ -21,11 +21,11 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.controllerblueprints.core.compress import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired @@ -45,8 +45,8 @@ import kotlin.test.assertTrue @WebFluxTest @ContextConfiguration( classes = [ - ExecutionServiceHandler::class, BlueprintCoreConfiguration::class, - BlueprintCatalogService::class, SelfServiceApiTestConfiguration::class, + ExecutionServiceHandler::class, BluePrintCoreConfiguration::class, + BluePrintCatalogService::class, SelfServiceApiTestConfiguration::class, ErrorCatalogTestConfiguration::class, SimpleMeterRegistry::class ] ) @@ -54,7 +54,7 @@ import kotlin.test.assertTrue class ExecutionServiceControllerTest { @Autowired - lateinit var blueprintsProcessorCatalogService: BlueprintCatalogService + lateinit var blueprintsProcessorCatalogService: BluePrintCatalogService @Autowired lateinit var webTestClient: WebTestClient diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt index 526491eb5..0a89c5782 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt @@ -32,7 +32,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractServiceFunction import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.ApplicationContext @@ -62,7 +62,7 @@ class ExecutionServiceHandlerTest { @Before fun init() { - BlueprintDependencyService.inject(applicationContext) + BluePrintDependencyService.inject(applicationContext) } @Test diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt index 4401fde78..bca05f68b 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt @@ -16,7 +16,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api -import org.onap.ccsdk.cds.blueprintsprocessor.db.BlueprintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration import org.springframework.context.annotation.Bean @@ -29,7 +29,7 @@ import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration -@Import(BlueprintDBLibConfiguration::class) +@Import(BluePrintDBLibConfiguration::class) @EnableJpaRepositories( basePackages = [ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary", diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtilsTest.kt index 10db349e6..375faa152 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtilsTest.kt +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BlueprintProcessingUtilsTest.kt @@ -24,7 +24,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.springframework.http.HttpStatus import org.springframework.test.context.junit4.SpringRunner @@ -57,9 +57,9 @@ class BlueprintProcessingUtilsTest { } val expectedTags = mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_BP_NAME, executionServiceInput.actionIdentifiers.blueprintName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_VERSION, executionServiceInput.actionIdentifiers.blueprintVersion), - Tag.of(BlueprintConstants.METRIC_TAG_BP_ACTION, executionServiceInput.actionIdentifiers.actionName) + Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, executionServiceInput.actionIdentifiers.blueprintName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, executionServiceInput.actionIdentifiers.blueprintVersion), + Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, executionServiceInput.actionIdentifiers.actionName) ) val metricTag = cbaMetricTags(executionServiceInput) @@ -82,11 +82,11 @@ class BlueprintProcessingUtilsTest { } val expectedTags = mutableListOf( - Tag.of(BlueprintConstants.METRIC_TAG_BP_NAME, executionServiceOutput.actionIdentifiers.blueprintName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_VERSION, executionServiceOutput.actionIdentifiers.blueprintVersion), - Tag.of(BlueprintConstants.METRIC_TAG_BP_ACTION, executionServiceOutput.actionIdentifiers.actionName), - Tag.of(BlueprintConstants.METRIC_TAG_BP_STATUS, executionServiceOutput.status.code.toString()), - Tag.of(BlueprintConstants.METRIC_TAG_BP_OUTCOME, executionServiceOutput.status.message) + Tag.of(BluePrintConstants.METRIC_TAG_BP_NAME, executionServiceOutput.actionIdentifiers.blueprintName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_VERSION, executionServiceOutput.actionIdentifiers.blueprintVersion), + Tag.of(BluePrintConstants.METRIC_TAG_BP_ACTION, executionServiceOutput.actionIdentifiers.actionName), + Tag.of(BluePrintConstants.METRIC_TAG_BP_STATUS, executionServiceOutput.status.code.toString()), + Tag.of(BluePrintConstants.METRIC_TAG_BP_OUTCOME, executionServiceOutput.status.message) ) val metricTag = cbaMetricTags(executionServiceOutput) diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt new file mode 100644 index 000000000..84d057f55 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt @@ -0,0 +1,51 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.mock.MockResourceSource +import org.onap.ccsdk.cds.controllerblueprints.validation.BluePrintValidationConfiguration +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration( + classes = [ + BluePrintRuntimeValidatorService::class, + BluePrintValidationConfiguration::class, MockResourceSource::class + ] +) +class BluePrintRuntimeValidatorServiceTest { + + @Autowired + lateinit var bluePrintRuntimeValidatorService: BluePrintRuntimeValidatorService + + @Test + fun testBlueprintRuntimeValidation() { + runBlocking { + val blueprintBasePath = + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + assertNotNull(bluePrintRuntimeValidatorService, " failed to initilize bluePrintRuntimeValidatorService") + + bluePrintRuntimeValidatorService.validateBluePrints(blueprintBasePath) + } + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorServiceTest.kt deleted file mode 100644 index c6b90e5b7..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BlueprintRuntimeValidatorServiceTest.kt +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.mock.MockResourceSource -import org.onap.ccsdk.cds.controllerblueprints.validation.BlueprintValidationConfiguration -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration( - classes = [ - BlueprintRuntimeValidatorService::class, - BlueprintValidationConfiguration::class, MockResourceSource::class - ] -) -class BlueprintRuntimeValidatorServiceTest { - - @Autowired - lateinit var bluePrintRuntimeValidatorService: BlueprintRuntimeValidatorService - - @Test - fun testBlueprintRuntimeValidation() { - runBlocking { - val blueprintBasePath = - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - assertNotNull(bluePrintRuntimeValidatorService, " failed to initilize bluePrintRuntimeValidatorService") - - bluePrintRuntimeValidatorService.validateBlueprints(blueprintBasePath) - } - } -} diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt index f85b6424d..2186d470b 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt @@ -24,11 +24,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutp import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.core.cluster.executeWithLock -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.core.service.CDS_LOCK_GROUP import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.checkNotBlank import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty @@ -38,8 +38,8 @@ import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunction import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintVelocityTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService import org.slf4j.LoggerFactory /** @@ -53,8 +53,8 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode - lateinit var bluePrintClusterService: BlueprintClusterService + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + lateinit var bluePrintClusterService: BluePrintClusterService lateinit var implementation: Implementation lateinit var processId: String lateinit var workflowName: String @@ -88,13 +88,13 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode { diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt index 3cb46ed44..8b46ae693 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt @@ -19,9 +19,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.execution import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.slf4j.LoggerFactory abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { @@ -47,7 +47,7 @@ abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { @Deprecated("Dependencies will be resolved dynamically") open fun functionDependencyInstanceAsType(name: String): T { return functionDependencyInstances[name] as? T - ?: throw BlueprintProcessorException("couldn't get script property instance ($name)") + ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") } fun checkDynamicProperties(key: String): Boolean { @@ -60,7 +60,7 @@ abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { suspend fun executeScript(executionServiceInput: ExecutionServiceInput) { return when (scriptType) { - BlueprintConstants.SCRIPT_JYTHON -> { + BluePrintConstants.SCRIPT_JYTHON -> { executeScriptBlocking(executionServiceInput) } else -> { @@ -97,34 +97,34 @@ abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { */ final override fun apply(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - throw BlueprintException("Not Implemented, use applyNB method") + throw BluePrintException("Not Implemented, use applyNB method") } final override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } final override fun prepareResponse(): ExecutionServiceOutput { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } final override suspend fun applyNB(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } final override suspend fun prepareRequestNB(executionRequest: ExecutionServiceInput): ExecutionServiceInput { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } final override suspend fun prepareResponseNB(): ExecutionServiceOutput { - throw BlueprintException("Not Implemented required") + throw BluePrintException("Not Implemented required") } override fun process(executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented, child class will implement this") + throw BluePrintException("Not Implemented, child class will implement this") } override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - throw BlueprintException("Not Implemented, child class will implement this") + throw BluePrintException("Not Implemented, child class will implement this") } } diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt index 41e26e4ab..33f5d749f 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt @@ -21,7 +21,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse import org.onap.ccsdk.cds.controllerblueprints.core.logger @@ -79,7 +79,7 @@ abstract class AbstractServiceFunction : BlueprintFunctionNode> scriptInstance( - bluePrintContext: BlueprintContext, + bluePrintContext: BluePrintContext, scriptType: String, scriptClassReference: String ): T { var scriptComponent: T? = null when (scriptType) { - BlueprintConstants.SCRIPT_INTERNAL -> { - val bluePrintScriptsService: BlueprintScriptsService = BlueprintScriptsServiceImpl() + BluePrintConstants.SCRIPT_INTERNAL -> { + val bluePrintScriptsService: BluePrintScriptsService = BluePrintScriptsServiceImpl() scriptComponent = bluePrintScriptsService.scriptInstance(scriptClassReference) } - BlueprintConstants.SCRIPT_KOTLIN -> { - val bluePrintScriptsService: BlueprintScriptsService = BlueprintScriptsServiceImpl() + BluePrintConstants.SCRIPT_KOTLIN -> { + val bluePrintScriptsService: BluePrintScriptsService = BluePrintScriptsServiceImpl() scriptComponent = bluePrintScriptsService.scriptInstance( bluePrintContext.rootPath, bluePrintContext.name(), bluePrintContext.version(), scriptClassReference, false ) } - BlueprintConstants.SCRIPT_JYTHON -> { + BluePrintConstants.SCRIPT_JYTHON -> { scriptComponent = blueprintJythonService.jythonComponentInstance(bluePrintContext, scriptClassReference) as T } else -> { - throw BlueprintProcessorException("script type($scriptType) is not supported") + throw BluePrintProcessorException("script type($scriptType) is not supported") } } return scriptComponent diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt index 5a552e32a..2581e5628 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt @@ -22,8 +22,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createActionIdentifiersProto import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createCommonHeaderProto import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createExecutionServiceInputProto -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.springframework.beans.factory.config.ConfigurableBeanFactory import org.springframework.context.annotation.Scope @@ -70,7 +70,7 @@ open class ComponentRemoteScriptExecutor( val txId = UUID.randomUUID().toString() val commonHeader = createCommonHeaderProto( executionRequest.commonHeader.subRequestId, - txId, BlueprintConstants.APP_NAME + txId, BluePrintConstants.APP_NAME ) val actionIdentifier = createActionIdentifiersProto(blueprintName, blueprintVersion, blueprintAction) @@ -92,11 +92,11 @@ open class ComponentRemoteScriptExecutor( /** set node template attribute */ val statusMessage = executionServiceOutputProto.status.message - if (statusMessage == BlueprintConstants.STATUS_SUCCESS) { - setAttribute(ATTRIBUTE_STATUS, BlueprintConstants.STATUS_SUCCESS.asJsonPrimitive()) + if (statusMessage == BluePrintConstants.STATUS_SUCCESS) { + setAttribute(ATTRIBUTE_STATUS, BluePrintConstants.STATUS_SUCCESS.asJsonPrimitive()) } else { val errorMessage = executionServiceOutputProto.status.errorMessage ?: "failed in remote execution" - throw BlueprintProcessorException(errorMessage) + throw BluePrintProcessorException(errorMessage) } } diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt index 4263768b9..7bb071501 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.execution import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate @@ -31,24 +31,24 @@ import org.onap.ccsdk.cds.controllerblueprints.core.dsl.nodeType /** Component Extensions **/ fun ServiceTemplateBuilder.nodeTypeComponentRemoteScriptExecutor() { - val nodeType = BlueprintTypes.nodeTypeComponentRemoteScriptExecutor() + val nodeType = BluePrintTypes.nodeTypeComponentRemoteScriptExecutor() if (this.nodeTypes == null) this.nodeTypes = hashMapOf() this.nodeTypes!![nodeType.id!!] = nodeType } -fun BlueprintTypes.nodeTypeComponentRemoteScriptExecutor(): NodeType { +fun BluePrintTypes.nodeTypeComponentRemoteScriptExecutor(): NodeType { return nodeType( - id = "component-remote-script-executor", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, + id = "component-remote-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, description = "Generic Remote Script Component Executor" ) { /** Attribute definitions */ attribute( - ComponentRemoteScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BlueprintConstants.DATA_TYPE_JSON, false, + ComponentRemoteScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false, "Remote executed response data." ) attribute( - ComponentRemoteScriptExecutor.ATTRIBUTE_STATUS, BlueprintConstants.DATA_TYPE_STRING, true, + ComponentRemoteScriptExecutor.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true, "Remote execution status." ) @@ -56,35 +56,35 @@ fun BlueprintTypes.nodeTypeComponentRemoteScriptExecutor(): NodeType { operation("ComponentRemoteScriptExecutor", "ComponentRemoteScriptExecutor Operation") { inputs { property( - ComponentRemoteScriptExecutor.INPUT_SELECTOR, BlueprintConstants.DATA_TYPE_JSON, + ComponentRemoteScriptExecutor.INPUT_SELECTOR, BluePrintConstants.DATA_TYPE_JSON, true, "Remote GRPC selector or DSL reference or GRPC Json config." ) property( - ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME, BluePrintConstants.DATA_TYPE_STRING, true, "Blueprint name." ) property( - ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_VERSION, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_VERSION, BluePrintConstants.DATA_TYPE_STRING, true, "Blueprint version." ) property( - ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_ACTION, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_ACTION, BluePrintConstants.DATA_TYPE_STRING, true, "Blueprint action name." ) property( - ComponentRemoteScriptExecutor.INPUT_TIMEOUT, BlueprintConstants.DATA_TYPE_INTEGER, + ComponentRemoteScriptExecutor.INPUT_TIMEOUT, BluePrintConstants.DATA_TYPE_INTEGER, true, "Remote execution timeout in sec." ) { defaultValue(180) } property( - ComponentRemoteScriptExecutor.INPUT_REQUEST_DATA, BlueprintConstants.DATA_TYPE_JSON, + ComponentRemoteScriptExecutor.INPUT_REQUEST_DATA, BluePrintConstants.DATA_TYPE_JSON, false, "Dynamic Json Content or DSL Json reference." ) } outputs { property( - ComponentRemoteScriptExecutor.OUTPUT_STATUS, BlueprintConstants.DATA_TYPE_STRING, + ComponentRemoteScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING, true, "Status of the Component Execution ( success or failure )" ) } @@ -98,7 +98,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentRemoteScriptExecutor( description: String, block: ComponentRemoteScriptExecutorNodeTemplateBuilder.() -> Unit ) { - val nodeTemplate = BlueprintTypes.nodeTemplateComponentRemoteScriptExecutor( + val nodeTemplate = BluePrintTypes.nodeTemplateComponentRemoteScriptExecutor( id, description, block ) @@ -106,7 +106,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentRemoteScriptExecutor( nodeTemplates!![nodeTemplate.id!!] = nodeTemplate } -fun BlueprintTypes.nodeTemplateComponentRemoteScriptExecutor( +fun BluePrintTypes.nodeTemplateComponentRemoteScriptExecutor( id: String, description: String, block: ComponentRemoteScriptExecutorNodeTemplateBuilder.() -> Unit diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt index 08a964b55..8592ce62b 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt @@ -17,8 +17,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.execution import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate @@ -32,53 +32,53 @@ import kotlin.reflect.KClass /** Component Extensions **/ fun ServiceTemplateBuilder.nodeTypeComponentScriptExecutor() { - val nodeType = BlueprintTypes.nodeTypeComponentScriptExecutor() + val nodeType = BluePrintTypes.nodeTypeComponentScriptExecutor() if (this.nodeTypes == null) this.nodeTypes = hashMapOf() this.nodeTypes!![nodeType.id!!] = nodeType } -fun BlueprintTypes.nodeTypeComponentScriptExecutor(): NodeType { +fun BluePrintTypes.nodeTypeComponentScriptExecutor(): NodeType { return nodeType( - id = "component-script-executor", version = BlueprintConstants.DEFAULT_VERSION_NUMBER, - derivedFrom = BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, + id = "component-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER, + derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, description = "Generic Script Component Executor" ) { - attribute(ComponentScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BlueprintConstants.DATA_TYPE_JSON, false) - attribute(ComponentScriptExecutor.ATTRIBUTE_STATUS, BlueprintConstants.DATA_TYPE_STRING, true) + attribute(ComponentScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false) + attribute(ComponentScriptExecutor.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true) operation("ComponentScriptExecutor", "ComponentScriptExecutor Operation") { inputs { property( - ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BlueprintConstants.DATA_TYPE_STRING, + ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING, true, "Script Type" ) { - defaultValue(BlueprintConstants.SCRIPT_INTERNAL) + defaultValue(BluePrintConstants.SCRIPT_INTERNAL) constrain { validValues( listOf( - BlueprintConstants.SCRIPT_INTERNAL.asJsonPrimitive(), - BlueprintConstants.SCRIPT_JYTHON.asJsonPrimitive(), - BlueprintConstants.SCRIPT_KOTLIN.asJsonPrimitive() + BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(), + BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive(), + BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive() ) ) } } property( - ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BlueprintConstants.DATA_TYPE_STRING, + ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING, true, "Kotlin Script class name or jython script name." ) property( - ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BlueprintConstants.DATA_TYPE_JSON, + ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON, false, "Dynamic Json Content or DSL Json reference." ) } outputs { property( - ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BlueprintConstants.DATA_TYPE_JSON, + ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false, "Output Response" ) property( - ComponentScriptExecutor.OUTPUT_STATUS, BlueprintConstants.DATA_TYPE_STRING, + ComponentScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING, true, "Status of the Component Execution ( success or failure )" ) } @@ -92,7 +92,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentScriptExecutor( description: String, block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit ) { - val nodeTemplate = BlueprintTypes.nodeTemplateComponentScriptExecutor( + val nodeTemplate = BluePrintTypes.nodeTemplateComponentScriptExecutor( id, description, block ) @@ -100,7 +100,7 @@ fun TopologyTemplateBuilder.nodeTemplateComponentScriptExecutor( nodeTemplates!![nodeTemplate.id!!] = nodeTemplate } -fun BlueprintTypes.nodeTemplateComponentScriptExecutor( +fun BluePrintTypes.nodeTemplateComponentScriptExecutor( id: String, description: String, block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt index 7e3f16f39..ff6027341 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt @@ -29,8 +29,8 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutio import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptUploadBlueprintOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcClientService -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService import org.onap.ccsdk.cds.controllerblueprints.command.api.CommandExecutorServiceGrpc import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionInput import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput @@ -63,7 +63,7 @@ interface RemoteScriptExecutionService { havingValue = "true", matchIfMissing = false ) @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BlueprintGrpcLibPropertyService) : +class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) : RemoteScriptExecutionService { private val log = LoggerFactory.getLogger(GrpcRemoteScriptExecutionService::class.java)!! @@ -73,7 +73,7 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi override suspend fun init(selector: Any) { // Get the GRPC Client Service based on selector - val grpcClientService: BlueprintGrpcClientService = if (selector is JsonNode) { + val grpcClientService: BluePrintGrpcClientService = if (selector is JsonNode) { bluePrintGrpcLibPropertyService.blueprintGrpcClientService(selector) } else { bluePrintGrpcLibPropertyService.blueprintGrpcClientService(selector.toString()) diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt index dadf72e04..fc37b488f 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt @@ -29,12 +29,12 @@ import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcClientService -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty @@ -58,7 +58,7 @@ interface StreamingRemoteExecutionService { prefix = "blueprintsprocessor.streamingRemoteExecution", name = ["enabled"], havingValue = "true", matchIfMissing = false ) -class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BlueprintGrpcLibPropertyService) : +class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) : StreamingRemoteExecutionService { private val log = logger(StreamingRemoteExecutionServiceImpl::class) @@ -84,12 +84,12 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe val grpcChannel = grpcChannel(selector) /** Get Send and Receive Channel for bidirectional process method*/ - val channels = clientCallBidiStreaming(BlueprintProcessingServiceGrpc.getProcessMethod(), grpcChannel) + val channels = clientCallBidiStreaming(BluePrintProcessingServiceGrpc.getProcessMethod(), grpcChannel) commChannels[txId] = channels } val commChannel = commChannels[txId] - ?: throw BlueprintException("failed to create response subscription for transactionId($txId) channel") + ?: throw BluePrintException("failed to create response subscription for transactionId($txId) channel") log.info("created subscription for transactionId($txId)") @@ -102,7 +102,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe */ override suspend fun send(txId: String, input: ExecutionServiceInput) { val sendChannel = commChannels[txId]?.requestChannel - ?: throw BlueprintException("failed to get transactionId($txId) send channel") + ?: throw BluePrintException("failed to get transactionId($txId) send channel") coroutineScope { launch { sendChannel.send(input) @@ -127,7 +127,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe /** Send the request */ val sendChannel = commChannels[txId]?.requestChannel - ?: throw BlueprintException("failed to get transactionId($txId) send channel") + ?: throw BluePrintException("failed to get transactionId($txId) send channel") sendChannel.send(input) /** Receive the response with timeout */ @@ -186,7 +186,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe } suspend fun createGrpcChannel(grpcProperties: GrpcClientProperties): ManagedChannel { - val grpcClientService: BlueprintGrpcClientService = bluePrintGrpcLibPropertyService + val grpcClientService: BluePrintGrpcClientService = bluePrintGrpcLibPropertyService .blueprintGrpcClientService(grpcProperties) return grpcClientService.channel() } @@ -203,7 +203,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe selector } else -> { - throw BlueprintException("couldn't process selector($selector)") + throw BluePrintException("couldn't process selector($selector)") } } } diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt index 69cb0b6eb..2f1ae2fc5 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt @@ -16,9 +16,9 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext import org.springframework.stereotype.Service // TODO("After Jython depreciation, this interface will be removed") @@ -26,15 +26,15 @@ import org.springframework.stereotype.Service @Deprecated("CDS won's support Jython services") interface BlueprintJythonService { - fun jythonComponentInstance(bluePrintContext: BlueprintContext, scriptClassReference: String): + fun jythonComponentInstance(bluePrintContext: BluePrintContext, scriptClassReference: String): BlueprintFunctionNode<*, *> } @Service open class DeprecatedBlueprintJythonService : BlueprintJythonService { - override fun jythonComponentInstance(bluePrintContext: BlueprintContext, scriptClassReference: String): + override fun jythonComponentInstance(bluePrintContext: BluePrintContext, scriptClassReference: String): BlueprintFunctionNode<*, *> { - throw BlueprintProcessorException("Include python-executor module for Jython support") + throw BluePrintProcessorException("Include python-executor module for Jython support") } } diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt index 5ef62d0bc..b3a0a5892 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt @@ -32,15 +32,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createExecutionServiceOutputProto import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createStatus import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toProto -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput import kotlin.test.assertNotNull @@ -48,7 +48,7 @@ class ComponentRemoteScriptExecutorTest { @Test fun testNodeComponentRemoteScriptExecutorType() { - val nodeType = BlueprintTypes.nodeTypeComponentRemoteScriptExecutor() + val nodeType = BluePrintTypes.nodeTypeComponentRemoteScriptExecutor() assertNotNull(nodeType, "failed to generate nodeType Component Remote Script Executor") } @@ -96,7 +96,7 @@ class ComponentRemoteScriptExecutorTest { fun testComponentRemoteScriptExecutor() { runBlocking { /** Mock blueprint context */ - val blueprintContext = mockk() + val blueprintContext = mockk() every { blueprintContext.rootPath } returns normalizedPathName("target") every { blueprintContext.nodeTemplateOperationImplementation( @@ -104,7 +104,7 @@ class ComponentRemoteScriptExecutorTest { ) } returns Implementation() - val bluePrintRuntime = mockk("1234") + val bluePrintRuntime = mockk("1234") every { bluePrintRuntime.bluePrintContext() } returns blueprintContext val mockExecutionServiceInput = mockExecutionServiceInput(bluePrintRuntime) @@ -130,7 +130,7 @@ class ComponentRemoteScriptExecutorTest { } } - private fun mockExecutionServiceInput(bluePrintRuntime: DefaultBlueprintRuntimeService): ExecutionServiceInput { + private fun mockExecutionServiceInput(bluePrintRuntime: DefaultBluePrintRuntimeService): ExecutionServiceInput { val mapper = ObjectMapper() val requestNode = mapper.createObjectNode() @@ -138,10 +138,10 @@ class ComponentRemoteScriptExecutorTest { requestNode.put("type", "grpc") val operationInputs = hashMapOf() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "remote-execute".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "remote-execute".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "ComponentRemoteScriptExecutor".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = "process".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "process".asJsonPrimitive() operationInputs[ComponentRemoteScriptExecutor.INPUT_SELECTOR] = "remote-script-executor".asJsonPrimitive() operationInputs[ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME] = "sample-blueprint".asJsonPrimitive() @@ -205,7 +205,7 @@ class ComponentRemoteScriptExecutorTest { return createExecutionServiceOutputProto( executionServiceInput.commonHeader.toProto(), executionServiceInput.actionIdentifiers.toProto(), - createStatus(BlueprintConstants.STATUS_SUCCESS, 200), + createStatus(BluePrintConstants.STATUS_SUCCESS, 200), responsePayload ) } diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt new file mode 100644 index 000000000..8edea46f6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt @@ -0,0 +1,107 @@ +/* + * Copyright © 2018-2019 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts + +import io.grpc.ServerBuilder +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcServerLoggingInterceptor +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status +import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext +import org.onap.ccsdk.cds.controllerblueprints.core.logger +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput + +private val log = logger(MockBluePrintProcessingServer::class) + +class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { + + override fun process(responseObserver: StreamObserver): StreamObserver { + + return object : StreamObserver { + override fun onNext(executionServiceInput: ExecutionServiceInput) { + log.info( + "Received requestId(${executionServiceInput.commonHeader.requestId}) " + + "subRequestId(${executionServiceInput.commonHeader.subRequestId})" + ) + runBlocking { + launch(MDCContext()) { + responseObserver.onNext(buildNotification(executionServiceInput)) + responseObserver.onNext(buildResponse(executionServiceInput)) + log.info("message has sent successfully...") + } + } + responseObserver.onCompleted() + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + responseObserver.onError( + io.grpc.Status.INTERNAL + .withDescription(error.message) + .asException() + ) + } + + override fun onCompleted() { + log.info("Completed") + } + } + } + + private fun buildNotification(input: ExecutionServiceInput): ExecutionServiceOutput { + val status = Status.newBuilder() + .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION) + .build() + return ExecutionServiceOutput.newBuilder() + .setCommonHeader(input.commonHeader) + .setActionIdentifiers(input.actionIdentifiers) + .setStatus(status) + .build() + } + + private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput { + + val status = Status.newBuilder().setCode(200) + .setEventType(EventType.EVENT_COMPONENT_EXECUTED) + .build() + return ExecutionServiceOutput.newBuilder() + .setCommonHeader(input.commonHeader) + .setActionIdentifiers(input.actionIdentifiers) + .setStatus(status) + .build() + } +} + +/** For Integration testing stat this server */ +fun main() { + try { + val server = ServerBuilder + .forPort(50052) + .intercept(GrpcServerLoggingInterceptor()) + .addService(MockBluePrintProcessingServer()) + .build() + server.start() + log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...") + server.awaitTermination() + } catch (e: Exception) { + e.printStackTrace() + } +} diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBlueprintProcessingServer.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBlueprintProcessingServer.kt deleted file mode 100644 index 7ac6134d9..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBlueprintProcessingServer.kt +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright © 2018-2019 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts - -import io.grpc.ServerBuilder -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcServerLoggingInterceptor -import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status -import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext -import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.processing.api.BlueprintProcessingServiceGrpc -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput - -private val log = logger(MockBlueprintProcessingServer::class) - -class MockBlueprintProcessingServer : BlueprintProcessingServiceGrpc.BlueprintProcessingServiceImplBase() { - - override fun process(responseObserver: StreamObserver): StreamObserver { - - return object : StreamObserver { - override fun onNext(executionServiceInput: ExecutionServiceInput) { - log.info( - "Received requestId(${executionServiceInput.commonHeader.requestId}) " + - "subRequestId(${executionServiceInput.commonHeader.subRequestId})" - ) - runBlocking { - launch(MDCContext()) { - responseObserver.onNext(buildNotification(executionServiceInput)) - responseObserver.onNext(buildResponse(executionServiceInput)) - log.info("message has sent successfully...") - } - } - responseObserver.onCompleted() - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - responseObserver.onError( - io.grpc.Status.INTERNAL - .withDescription(error.message) - .asException() - ) - } - - override fun onCompleted() { - log.info("Completed") - } - } - } - - private fun buildNotification(input: ExecutionServiceInput): ExecutionServiceOutput { - val status = Status.newBuilder() - .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION) - .build() - return ExecutionServiceOutput.newBuilder() - .setCommonHeader(input.commonHeader) - .setActionIdentifiers(input.actionIdentifiers) - .setStatus(status) - .build() - } - - private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput { - - val status = Status.newBuilder().setCode(200) - .setEventType(EventType.EVENT_COMPONENT_EXECUTED) - .build() - return ExecutionServiceOutput.newBuilder() - .setCommonHeader(input.commonHeader) - .setActionIdentifiers(input.actionIdentifiers) - .setStatus(status) - .build() - } -} - -/** For Integration testing stat this server */ -fun main() { - try { - val server = ServerBuilder - .forPort(50052) - .intercept(GrpcServerLoggingInterceptor()) - .addService(MockBlueprintProcessingServer()) - .build() - server.start() - log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...") - server.awaitTermination() - } catch (e: Exception) { - e.printStackTrace() - } -} diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt index 0d3e42a5e..28e2b11b2 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt @@ -35,8 +35,8 @@ import org.junit.Test import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties -import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BlueprintGrpcLibPropertyService -import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.MockBlueprintProcessingServer +import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.MockBluePrintProcessingServer import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType @@ -67,11 +67,11 @@ class StreamingRemoteExecutionServiceTest { @ExperimentalCoroutinesApi @FlowPreview fun testStreamingChannel() { - grpcCleanup.register(serverBuilder.addService(MockBlueprintProcessingServer()).build().start()) + grpcCleanup.register(serverBuilder.addService(MockBluePrintProcessingServer()).build().start()) val channel = grpcCleanup.register(channelBuilder.maxInboundMessageSize(1024).build()) runBlocking { - val bluePrintGrpcLibPropertyService = BlueprintGrpcLibPropertyService(mockk()) + val bluePrintGrpcLibPropertyService = BluePrintGrpcLibPropertyService(mockk()) val streamingRemoteExecutionService = StreamingRemoteExecutionServiceImpl(bluePrintGrpcLibPropertyService) diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt index 3438821c7..b5757812c 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt @@ -34,23 +34,23 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.core.service.CDS_LOCK_GROUP import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.nodeTypeComponentScriptExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation import org.onap.ccsdk.cds.controllerblueprints.core.data.LockAssignment import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BlueprintScriptsServiceImpl -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration @@ -66,14 +66,14 @@ import kotlin.test.assertNotNull @ContextConfiguration( classes = [ ComponentFunctionScriptingService::class, - BlueprintScriptsServiceImpl::class, DeprecatedBlueprintJythonService::class + BluePrintScriptsServiceImpl::class, DeprecatedBlueprintJythonService::class ] ) class AbstractComponentFunctionTest { - lateinit var bluePrintRuntimeService: DefaultBlueprintRuntimeService - lateinit var blueprintContext: BlueprintContext - lateinit var blueprintClusterService: BlueprintClusterService + lateinit var bluePrintRuntimeService: DefaultBluePrintRuntimeService + lateinit var blueprintContext: BluePrintContext + lateinit var blueprintClusterService: BluePrintClusterService @Autowired lateinit var compSvc: ComponentFunctionScriptingService @@ -92,7 +92,7 @@ class AbstractComponentFunctionTest { ) } returns Implementation() - every { bluePrintRuntimeService.getBlueprintError() } returns BlueprintError() + every { bluePrintRuntimeService.getBluePrintError() } returns BluePrintError() } @Test @@ -152,7 +152,7 @@ class AbstractComponentFunctionTest { @Test fun testComponentScriptExecutorNodeType() { - val componentScriptExecutor = BlueprintTypes.nodeTypeComponentScriptExecutor() + val componentScriptExecutor = BluePrintTypes.nodeTypeComponentScriptExecutor() assertNotNull(componentScriptExecutor.interfaces, "failed to get interface operations") } @@ -277,7 +277,7 @@ class AbstractComponentFunctionTest { /** * Mocked input for abstract function test. */ - private fun getMockedInput(bluePrintRuntime: DefaultBlueprintRuntimeService): + private fun getMockedInput(bluePrintRuntime: DefaultBluePrintRuntimeService): ExecutionServiceInput { val mapper = ObjectMapper() @@ -286,11 +286,11 @@ class AbstractComponentFunctionTest { rootNode.put("type", "rest") val operationInputs = hashMapOf() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-restconf".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() - operationInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() operationInputs["dynamic-properties"] = rootNode diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt new file mode 100644 index 000000000..0f8007658 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt @@ -0,0 +1,111 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asObjectNode +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service + +@Service("bluePrintWorkflowExecutionService") +open class BluePrintWorkflowExecutionServiceImpl( + private val componentWorkflowExecutionService: ComponentWorkflowExecutionService, + private val dgWorkflowExecutionService: DGWorkflowExecutionService, + private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService +) : BluePrintWorkflowExecutionService { + + private val log = LoggerFactory.getLogger(BluePrintWorkflowExecutionServiceImpl::class.java)!! + + override suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: ExecutionServiceInput, + properties: MutableMap + ): ExecutionServiceOutput { + + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val workflowName = executionServiceInput.actionIdentifiers.actionName + + // Assign Workflow inputs + // check if request structure exists + if (!executionServiceInput.payload.has("$workflowName-request")) { + throw BluePrintProcessorException("Input request missing the expected '$workflowName-request' block!") + } + val input = executionServiceInput.payload.get("$workflowName-request") + bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) + + val workflow = bluePrintContext.workflowByName(workflowName) + + val steps = workflow.steps ?: throw BluePrintProcessorException("could't get steps for workflow($workflowName)") + + /** If workflow has multiple steps, then it is imperative workflow */ + val executionServiceOutput: ExecutionServiceOutput = if (steps.size > 1) { + imperativeWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) + } else { + // Get the DG Node Template + val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) + + val derivedFrom = bluePrintContext.nodeTemplateNodeType(nodeTemplateName).derivedFrom + + log.info("Executing workflow($workflowName) NodeTemplate($nodeTemplateName), derived from($derivedFrom)") + /** Return ExecutionServiceOutput based on DG node or Component Node */ + when { + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { + componentWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) + } + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { + dgWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) + } + else -> { + throw BluePrintProcessorException( + "couldn't execute workflow($workflowName) step mapped " + + "to node template($nodeTemplateName) derived from($derivedFrom)" + ) + } + } + } + executionServiceOutput.commonHeader = executionServiceInput.commonHeader + executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + + // Resolve Workflow Outputs + var workflowOutputs: MutableMap? = null + try { + workflowOutputs = bluePrintRuntimeService.resolveWorkflowOutputs(workflowName) + } catch (e: RuntimeException) { + log.error("Failed to resolve outputs for workflow: $workflowName", e) + e.message?.let { bluePrintRuntimeService.getBluePrintError().addError(it, "workflow") } + } + + // Set the Response Payload + executionServiceOutput.payload = JacksonUtils.objectMapper.createObjectNode() + executionServiceOutput.payload.set( + "$workflowName-response", + workflowOutputs?.asObjectNode() ?: JacksonUtils.objectMapper.createObjectNode() + ) + return executionServiceOutput + } +} diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt index 64bb70e63..044e8cf53 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt @@ -16,20 +16,20 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.sli.core.sli.SvcLogicContext class BlueprintSvcLogicContext : SvcLogicContext() { - private var bluePrintRuntimeService: BlueprintRuntimeService<*>? = null + private var bluePrintRuntimeService: BluePrintRuntimeService<*>? = null private var request: Any? = null private var response: Any? = null - fun getBlueprintService(): BlueprintRuntimeService<*> { + fun getBluePrintService(): BluePrintRuntimeService<*> { return this.bluePrintRuntimeService!! } - fun setBlueprintRuntimeService(bluePrintRuntimeService: BlueprintRuntimeService<*>) { + fun setBluePrintRuntimeService(bluePrintRuntimeService: BluePrintRuntimeService<*>) { this.bluePrintRuntimeService = bluePrintRuntimeService } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt index ebad1501b..4efe9f12d 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt @@ -17,7 +17,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.sli.core.sli.ExitNodeException import org.onap.ccsdk.sli.core.sli.SvcLogicContext import org.onap.ccsdk.sli.core.sli.SvcLogicException @@ -47,7 +47,7 @@ interface BlueprintSvcLogicService : SvcLogicServiceBase { fun unRegisterExecutors(name: String) - suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BlueprintRuntimeService<*>, input: Any): Any + suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: Any): Any override fun execute(module: String, rpc: String, version: String, mode: String, ctx: SvcLogicContext): SvcLogicContext { TODO("not implemented") @@ -104,12 +104,12 @@ class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService { override suspend fun execute( graph: SvcLogicGraph, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, input: Any ): Any { // Initialise BlueprintSvcLogic Context with Blueprint Runtime Service and Input Request val blueprintSvcLogicContext = BlueprintSvcLogicContext() - blueprintSvcLogicContext.setBlueprintRuntimeService(bluePrintRuntimeService) + blueprintSvcLogicContext.setBluePrintRuntimeService(bluePrintRuntimeService) blueprintSvcLogicContext.setRequest(input) // Execute the Graph execute(graph, blueprintSvcLogicContext) diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImpl.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImpl.kt deleted file mode 100644 index 5a175b056..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImpl.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asObjectNode -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service - -@Service("bluePrintWorkflowExecutionService") -open class BlueprintWorkflowExecutionServiceImpl( - private val componentWorkflowExecutionService: ComponentWorkflowExecutionService, - private val dgWorkflowExecutionService: DGWorkflowExecutionService, - private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService -) : BlueprintWorkflowExecutionService { - - private val log = LoggerFactory.getLogger(BlueprintWorkflowExecutionServiceImpl::class.java)!! - - override suspend fun executeBlueprintWorkflow( - bluePrintRuntimeService: BlueprintRuntimeService<*>, - executionServiceInput: ExecutionServiceInput, - properties: MutableMap - ): ExecutionServiceOutput { - - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val workflowName = executionServiceInput.actionIdentifiers.actionName - - // Assign Workflow inputs - // check if request structure exists - if (!executionServiceInput.payload.has("$workflowName-request")) { - throw BlueprintProcessorException("Input request missing the expected '$workflowName-request' block!") - } - val input = executionServiceInput.payload.get("$workflowName-request") - bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) - - val workflow = bluePrintContext.workflowByName(workflowName) - - val steps = workflow.steps ?: throw BlueprintProcessorException("could't get steps for workflow($workflowName)") - - /** If workflow has multiple steps, then it is imperative workflow */ - val executionServiceOutput: ExecutionServiceOutput = if (steps.size > 1) { - imperativeWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) - } else { - // Get the DG Node Template - val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) - - val derivedFrom = bluePrintContext.nodeTemplateNodeType(nodeTemplateName).derivedFrom - - log.info("Executing workflow($workflowName) NodeTemplate($nodeTemplateName), derived from($derivedFrom)") - /** Return ExecutionServiceOutput based on DG node or Component Node */ - when { - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { - componentWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) - } - derivedFrom.startsWith(BlueprintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> { - dgWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) - } - else -> { - throw BlueprintProcessorException( - "couldn't execute workflow($workflowName) step mapped " + - "to node template($nodeTemplateName) derived from($derivedFrom)" - ) - } - } - } - executionServiceOutput.commonHeader = executionServiceInput.commonHeader - executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers - - // Resolve Workflow Outputs - var workflowOutputs: MutableMap? = null - try { - workflowOutputs = bluePrintRuntimeService.resolveWorkflowOutputs(workflowName) - } catch (e: RuntimeException) { - log.error("Failed to resolve outputs for workflow: $workflowName", e) - e.message?.let { bluePrintRuntimeService.getBlueprintError().addError(it, "workflow") } - } - - // Set the Response Payload - executionServiceOutput.payload = JacksonUtils.objectMapper.createObjectNode() - executionServiceOutput.payload.set( - "$workflowName-response", - workflowOutputs?.asObjectNode() ?: JacksonUtils.objectMapper.createObjectNode() - ) - return executionServiceOutput - } -} diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt index 322180893..397dd3ffd 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt @@ -18,16 +18,16 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.springframework.stereotype.Service @Service("componentWorkflowExecutionService") open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) : - BlueprintWorkflowExecutionService { + BluePrintWorkflowExecutionService { - override suspend fun executeBlueprintWorkflow( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + override suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, executionServiceInput: ExecutionServiceInput, properties: MutableMap ): ExecutionServiceOutput { diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt index efcae4aee..d40b8f144 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt @@ -21,20 +21,20 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.utils.SvcGraphUtils -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service("dgWorkflowExecutionService") open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService) : - BlueprintWorkflowExecutionService { + BluePrintWorkflowExecutionService { private val log = LoggerFactory.getLogger(DGWorkflowExecutionService::class.java) - override suspend fun executeBlueprintWorkflow( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + override suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, executionServiceInput: ExecutionServiceInput, properties: MutableMap ): ExecutionServiceOutput { diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt index 29019b7cc..b8350f4f1 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt @@ -22,19 +22,19 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintException -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext import org.onap.ccsdk.cds.controllerblueprints.core.asGraph import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService import org.onap.ccsdk.cds.controllerblueprints.core.isAcyclic import org.onap.ccsdk.cds.controllerblueprints.core.logger -import org.onap.ccsdk.cds.controllerblueprints.core.service.AbstractBlueprintWorkFlowService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.AbstractBluePrintWorkFlowService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeExecuteMessage import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeSkipMessage import org.onap.ccsdk.cds.controllerblueprints.core.service.WorkflowExecuteMessage @@ -45,10 +45,10 @@ import kotlin.coroutines.CoroutineContext class ImperativeWorkflowExecutionService( private val nodeTemplateExecutionService: NodeTemplateExecutionService ) : - BlueprintWorkflowExecutionService { + BluePrintWorkflowExecutionService { - override suspend fun executeBlueprintWorkflow( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + override suspend fun executeBluePrintWorkflow( + bluePrintRuntimeService: BluePrintRuntimeService<*>, executionServiceInput: ExecutionServiceInput, properties: MutableMap ): ExecutionServiceOutput { @@ -60,11 +60,11 @@ class ImperativeWorkflowExecutionService( val graph = bluePrintContext.workflowByName(workflowName).asGraph() if (!graph.isAcyclic()) { - throw BlueprintException("Imperative workflow must be acyclic. Check on_success/on_failure for circular references") + throw BluePrintException("Imperative workflow must be acyclic. Check on_success/on_failure for circular references") } return coroutineScope { - ImperativeBlueprintWorkflowService( + ImperativeBluePrintWorkflowService( nodeTemplateExecutionService, this.coroutineContext[MDCContext] ) @@ -72,21 +72,21 @@ class ImperativeWorkflowExecutionService( } } -open class ImperativeBlueprintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService, private val mdcContext: CoroutineContext?) : - AbstractBlueprintWorkFlowService() { +open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService, private val mdcContext: CoroutineContext?) : + AbstractBluePrintWorkFlowService() { final override val coroutineContext: CoroutineContext get() = mdcContext?.let { super.coroutineContext + it } ?: super.coroutineContext - val log = logger(ImperativeBlueprintWorkflowService::class) + val log = logger(ImperativeBluePrintWorkflowService::class) - lateinit var bluePrintRuntimeService: BlueprintRuntimeService<*> + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> lateinit var executionServiceInput: ExecutionServiceInput lateinit var workflowName: String override suspend fun executeWorkflow( graph: Graph, - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, input: ExecutionServiceInput ): ExecutionServiceOutput { this.graph = graph @@ -100,7 +100,7 @@ open class ImperativeBlueprintWorkflowService(private val nodeTemplateExecutionS if (!workflowActor.isClosedForSend) { workflowActor.send(startMessage) } else { - throw BlueprintProcessorException("workflow($workflowActor) actor is closed") + throw BluePrintProcessorException("workflow($workflowActor) actor is closed") } return output.await() } @@ -114,12 +114,12 @@ open class ImperativeBlueprintWorkflowService(private val nodeTemplateExecutionS if (exceptions.isNotEmpty()) { exceptions.forEach { val errorMessage = it.message ?: "" - bluePrintRuntimeService.getBlueprintError().addError(errorMessage, "workflow") + bluePrintRuntimeService.getBluePrintError().addError(errorMessage, "workflow") log.error("workflow($workflowId) exception :", it) } - message = BlueprintConstants.STATUS_FAILURE + message = BluePrintConstants.STATUS_FAILURE } else { - message = BlueprintConstants.STATUS_SUCCESS + message = BluePrintConstants.STATUS_SUCCESS } eventType = EventType.EVENT_COMPONENT_EXECUTED.name } @@ -162,9 +162,9 @@ open class ImperativeBlueprintWorkflowService(private val nodeTemplateExecutionS val executionServiceOutput = nodeTemplateExecutionService .executeNodeTemplate(bluePrintRuntimeService, node.id, nodeTemplateName, nodeInput) - if (executionServiceOutput.status.message == BlueprintConstants.STATUS_FAILURE) { + if (executionServiceOutput.status.message == BluePrintConstants.STATUS_FAILURE) { // Clear step errors so that the workflow does not fail - bluePrintRuntimeService.getBlueprintError().stepErrors(node.id)?.clear() + bluePrintRuntimeService.getBluePrintError().stepErrors(node.id)?.clear() return EdgeLabel.FAILURE } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt index ff8f5b8cf..88799d102 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt @@ -20,23 +20,23 @@ import com.fasterxml.jackson.databind.JsonNode import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService import org.slf4j.LoggerFactory import org.springframework.stereotype.Service @Service -open class NodeTemplateExecutionService(private val bluePrintClusterService: BlueprintClusterService) { +open class NodeTemplateExecutionService(private val bluePrintClusterService: BluePrintClusterService) { private val log = LoggerFactory.getLogger(NodeTemplateExecutionService::class.java)!! suspend fun executeNodeTemplate( - bluePrintRuntimeService: BlueprintRuntimeService<*>, + bluePrintRuntimeService: BluePrintRuntimeService<*>, stepName: String, nodeTemplateName: String, executionServiceInput: ExecutionServiceInput @@ -63,7 +63,7 @@ open class NodeTemplateExecutionService(private val bluePrintClusterService: Blu ) // Get the Component Instance - val plugin = BlueprintDependencyService.instance(componentName) + val plugin = BluePrintDependencyService.instance(componentName) // Set the Blueprint Services plugin.bluePrintRuntimeService = bluePrintRuntimeService plugin.bluePrintClusterService = bluePrintClusterService @@ -79,9 +79,9 @@ open class NodeTemplateExecutionService(private val bluePrintClusterService: Blu // Populate Step Meta Data val stepInputs: MutableMap = hashMapOf() - stepInputs[BlueprintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = nodeTemplateName.asJsonPrimitive() - stepInputs[BlueprintConstants.PROPERTY_CURRENT_INTERFACE] = interfaceName.asJsonPrimitive() - stepInputs[BlueprintConstants.PROPERTY_CURRENT_OPERATION] = operationName.asJsonPrimitive() + stepInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = nodeTemplateName.asJsonPrimitive() + stepInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = interfaceName.asJsonPrimitive() + stepInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = operationName.asJsonPrimitive() val stepInputData = StepData().apply { name = stepName properties = stepInputs diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt index 2e3f78a69..8ef74152c 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt @@ -52,7 +52,7 @@ open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService try { // Get the Request from the Context and Set to the Function Input and Invoke the function val executionOutput = nodeTemplateExecutionService.executeNodeTemplate( - ctx.getBlueprintService(), stepName, nodeTemplateName, executionInput + ctx.getBluePrintService(), stepName, nodeTemplateName, executionInput ) ctx.setResponse(executionOutput) diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt new file mode 100644 index 000000000..c28e36acc --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt @@ -0,0 +1,185 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ObjectNode +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkAll +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.MockComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintError +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType +import org.onap.ccsdk.cds.controllerblueprints.core.data.Step +import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.test.mock.mockito.MockBean +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [WorkflowServiceConfiguration::class]) +class BluePrintWorkflowExecutionServiceImplTest { + + @Autowired + lateinit var bluePrintWorkflowExecutionService: BluePrintWorkflowExecutionService + + @MockBean + lateinit var bluePrintClusterService: BluePrintClusterService + + @Before + fun init() { + mockkObject(BluePrintDependencyService) + every { BluePrintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() + } + + @After + fun afterTests() { + unmockkAll() + } + + @Test + fun testBluePrintWorkflowExecutionService() { + runBlocking { + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( + "1234", + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + ) + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile( + "execution-input/resource-assignment-input.json", + ExecutionServiceInput::class.java + )!! + + val executionServiceOutput = bluePrintWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) + + assertNotNull(executionServiceOutput, "failed to get response") + assertEquals( + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + "failed to get successful response" + ) + } + } + + @Test + fun testImperativeBluePrintWorkflowExecutionService() { + runBlocking { + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( + "1234", + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + ) + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile( + "execution-input/imperative-test-input.json", + ExecutionServiceInput::class.java + )!! + + val executionServiceOutput = bluePrintWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) + + assertNotNull(executionServiceOutput, "failed to get response") + assertEquals( + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + "failed to get successful response" + ) + } + } + + @Test + fun `Blueprint fails on missing workflowName-parameters with a useful message`() { + assertFailsWith(exceptionClass = BluePrintProcessorException::class) { + runBlocking { + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( + "1234", + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" + ) + // service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message + val executionServiceInput = + JacksonUtils.readValueFromClassPathFile( + "execution-input/resource-assignment-input-missing-resource_assignment_request.json", + ExecutionServiceInput::class.java + )!! + + val executionServiceOutput = bluePrintWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) + } + } + } + + @Test + fun `Should handle errors from resolve workflow output`() { + val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService = mockk() + val bluePrintWorkflowExecutionServiceImpl = BluePrintWorkflowExecutionServiceImpl( + mockk(), mockk(), imperativeWorkflowExecutionService + ) + val bluePrintRuntimeService: BluePrintRuntimeService> = mockk() + val bluePrintContext: BluePrintContext = mockk() + val executionServiceInput = ExecutionServiceInput().apply { + this.actionIdentifiers = ActionIdentifiers().apply { this.actionName = "config-assign" } + this.commonHeader = CommonHeader() + this.payload = """{"config-assign-request": {}}""".asJsonType() as ObjectNode + } + val workflow = Workflow().apply { + this.steps = mutableMapOf("one" to Step(), "two" to Step()) + } + val blueprintError = BluePrintError() + + every { bluePrintRuntimeService.bluePrintContext() } returns bluePrintContext + every { bluePrintRuntimeService.assignWorkflowInputs(any(), any()) } returns Unit + every { bluePrintContext.workflowByName(any()) } returns workflow + every { + bluePrintRuntimeService.resolveWorkflowOutputs(any()) + } throws RuntimeException("failed to resolve property...") + every { + runBlocking { + imperativeWorkflowExecutionService.executeBluePrintWorkflow(any(), any(), any()) + } + } returns ExecutionServiceOutput() + every { bluePrintRuntimeService.getBluePrintError() } returns blueprintError + + runBlocking { + val output = bluePrintWorkflowExecutionServiceImpl.executeBluePrintWorkflow( + bluePrintRuntimeService, executionServiceInput, mutableMapOf() + ) + assertEquals("failed to resolve property...", blueprintError.allErrors()[0]) + assertEquals("""{"config-assign-response":{}}""".asJsonType(), output.payload) + } + } +} diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt index e7dd9dedb..d391050a6 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt @@ -22,13 +22,13 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.PrototypeComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.SingletonComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean @@ -49,17 +49,17 @@ class BlueprintServiceLogicTest { lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService @MockBean - lateinit var bluePrintClusterService: BlueprintClusterService + lateinit var bluePrintClusterService: BluePrintClusterService @Before fun init() { - BlueprintDependencyService.inject(applicationContext) + BluePrintDependencyService.inject(applicationContext) } @Test fun testExecuteGraphWithSingleComponent() { runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -72,10 +72,10 @@ class BlueprintServiceLogicTest { bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input) val executionServiceOutput = dgWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) assertNotNull(executionServiceOutput, "failed to get response") assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, "failed to get successful response" ) } @@ -84,7 +84,7 @@ class BlueprintServiceLogicTest { @Test fun testExecuteGraphWithMultipleComponents() { runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -97,10 +97,10 @@ class BlueprintServiceLogicTest { bluePrintRuntimeService.assignWorkflowInputs("assign-activate", input) val executionServiceOutput = dgWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) assertNotNull(executionServiceOutput, "failed to get response") assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, "failed to get successful response" ) } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImplTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImplTest.kt deleted file mode 100644 index b7087b338..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintWorkflowExecutionServiceImplTest.kt +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ObjectNode -import io.mockk.every -import io.mockk.mockk -import io.mockk.mockkObject -import io.mockk.unmockkAll -import kotlinx.coroutines.runBlocking -import org.junit.After -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService -import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.MockComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintError -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException -import org.onap.ccsdk.cds.controllerblueprints.core.asJsonType -import org.onap.ccsdk.cds.controllerblueprints.core.data.Step -import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow -import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintWorkflowExecutionService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintRuntimeService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils -import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.mock.mockito.MockBean -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [WorkflowServiceConfiguration::class]) -class BlueprintWorkflowExecutionServiceImplTest { - - @Autowired - lateinit var bluePrintWorkflowExecutionService: BlueprintWorkflowExecutionService - - @MockBean - lateinit var bluePrintClusterService: BlueprintClusterService - - @Before - fun init() { - mockkObject(BlueprintDependencyService) - every { BlueprintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() - } - - @After - fun afterTests() { - unmockkAll() - } - - @Test - fun testBlueprintWorkflowExecutionService() { - runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( - "1234", - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - ) - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile( - "execution-input/resource-assignment-input.json", - ExecutionServiceInput::class.java - )!! - - val executionServiceOutput = bluePrintWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) - - assertNotNull(executionServiceOutput, "failed to get response") - assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, - "failed to get successful response" - ) - } - } - - @Test - fun testImperativeBlueprintWorkflowExecutionService() { - runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( - "1234", - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - ) - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile( - "execution-input/imperative-test-input.json", - ExecutionServiceInput::class.java - )!! - - val executionServiceOutput = bluePrintWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) - - assertNotNull(executionServiceOutput, "failed to get response") - assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, - "failed to get successful response" - ) - } - } - - @Test - fun `Blueprint fails on missing workflowName-parameters with a useful message`() { - assertFailsWith(exceptionClass = BlueprintProcessorException::class) { - runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( - "1234", - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" - ) - // service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message - val executionServiceInput = - JacksonUtils.readValueFromClassPathFile( - "execution-input/resource-assignment-input-missing-resource_assignment_request.json", - ExecutionServiceInput::class.java - )!! - - val executionServiceOutput = bluePrintWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) - } - } - } - - @Test - fun `Should handle errors from resolve workflow output`() { - val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService = mockk() - val bluePrintWorkflowExecutionServiceImpl = BlueprintWorkflowExecutionServiceImpl( - mockk(), mockk(), imperativeWorkflowExecutionService - ) - val bluePrintRuntimeService: BlueprintRuntimeService> = mockk() - val bluePrintContext: BlueprintContext = mockk() - val executionServiceInput = ExecutionServiceInput().apply { - this.actionIdentifiers = ActionIdentifiers().apply { this.actionName = "config-assign" } - this.commonHeader = CommonHeader() - this.payload = """{"config-assign-request": {}}""".asJsonType() as ObjectNode - } - val workflow = Workflow().apply { - this.steps = mutableMapOf("one" to Step(), "two" to Step()) - } - val blueprintError = BlueprintError() - - every { bluePrintRuntimeService.bluePrintContext() } returns bluePrintContext - every { bluePrintRuntimeService.assignWorkflowInputs(any(), any()) } returns Unit - every { bluePrintContext.workflowByName(any()) } returns workflow - every { - bluePrintRuntimeService.resolveWorkflowOutputs(any()) - } throws RuntimeException("failed to resolve property...") - every { - runBlocking { - imperativeWorkflowExecutionService.executeBlueprintWorkflow(any(), any(), any()) - } - } returns ExecutionServiceOutput() - every { bluePrintRuntimeService.getBlueprintError() } returns blueprintError - - runBlocking { - val output = bluePrintWorkflowExecutionServiceImpl.executeBlueprintWorkflow( - bluePrintRuntimeService, executionServiceInput, mutableMapOf() - ) - assertEquals("failed to resolve property...", blueprintError.allErrors()[0]) - assertEquals("""{"config-assign-response":{}}""".asJsonType(), output.payload) - } - } -} diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt index 355939cdd..cc1bfee7f 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt @@ -22,11 +22,11 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonReactorUtils import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.mock.mockito.MockBean @@ -47,18 +47,18 @@ class DGWorkflowExecutionServiceTest { lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService @MockBean - lateinit var bluePrintClusterService: BlueprintClusterService + lateinit var bluePrintClusterService: BluePrintClusterService @Before fun init() { - BlueprintDependencyService.inject(applicationContext) + BluePrintDependencyService.inject(applicationContext) } @Test fun testExecuteDirectedGraph() { runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -70,14 +70,14 @@ class DGWorkflowExecutionServiceTest { val input = executionServiceInput.payload.get("resource-assignment-request") bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input) - val executionServiceOutput = dgWorkflowExecutionService.executeBlueprintWorkflow( + val executionServiceOutput = dgWorkflowExecutionService.executeBluePrintWorkflow( bluePrintRuntimeService, executionServiceInput, mutableMapOf() ) assertNotNull(executionServiceOutput, "failed to get response") assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, "failed to get successful response" ) } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt index 9ba607cd4..2367422a7 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt @@ -28,15 +28,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.nodeTypeCompone import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.MockComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.mockNodeTemplateComponentScriptExecutor import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate import org.onap.ccsdk.cds.controllerblueprints.core.dsl.serviceTemplate import org.onap.ccsdk.cds.controllerblueprints.core.logger import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintContext -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import kotlin.test.Test import kotlin.test.assertEquals @@ -48,8 +48,8 @@ class ImperativeWorkflowExecutionServiceTest { @Before fun init() { - mockkObject(BlueprintDependencyService) - every { BlueprintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() + mockkObject(BluePrintDependencyService) + every { BluePrintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() } @After @@ -101,7 +101,7 @@ class ImperativeWorkflowExecutionServiceTest { step("activate-licence", "activate-licence", "") } } - nodeType(BlueprintTypes.nodeTypeComponentScriptExecutor()) + nodeType(BluePrintTypes.nodeTypeComponentScriptExecutor()) } } @@ -109,10 +109,10 @@ class ImperativeWorkflowExecutionServiceTest { fun testImperativeExecutionService() { runBlocking { val serviceTemplate = mockServiceTemplate() - val bluePrintContext = BlueprintContext(serviceTemplate) + val bluePrintContext = BluePrintContext(serviceTemplate) bluePrintContext.rootPath = normalizedPathName(".") bluePrintContext.entryDefinition = "cba.imperative.test.ImperativeTestDefinitions.kt" - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime("12345", bluePrintContext) + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("12345", bluePrintContext) val executionServiceInput = JacksonUtils .readValueFromClassPathFile( @@ -122,10 +122,10 @@ class ImperativeWorkflowExecutionServiceTest { val imperativeWorkflowExecutionService = ImperativeWorkflowExecutionService(NodeTemplateExecutionService(mockk())) val output = imperativeWorkflowExecutionService - .executeBlueprintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf()) assertNotNull(output, "failed to get imperative workflow output") assertNotNull(output.status, "failed to get imperative workflow output status") - assertEquals(output.status.message, BlueprintConstants.STATUS_SUCCESS) + assertEquals(output.status.message, BluePrintConstants.STATUS_SUCCESS) assertEquals(output.status.eventType, EventType.EVENT_COMPONENT_EXECUTED.name) } } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt index b113987e5..783939880 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt @@ -24,11 +24,11 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BlueprintClusterService +import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.MockComponentFunction -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintConstants -import org.onap.ccsdk.cds.controllerblueprints.core.service.BlueprintDependencyService -import org.onap.ccsdk.cds.controllerblueprints.core.utils.BlueprintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.ContextConfiguration @@ -42,12 +42,12 @@ import kotlin.test.assertNotNull class NodeTemplateExecutionServiceTest { @MockBean - lateinit var bluePrintClusterService: BlueprintClusterService + lateinit var bluePrintClusterService: BluePrintClusterService @Before fun init() { - mockkObject(BlueprintDependencyService) - every { BlueprintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() + mockkObject(BluePrintDependencyService) + every { BluePrintDependencyService.applicationContext.getBean(any()) } returns MockComponentFunction() } @After @@ -58,7 +58,7 @@ class NodeTemplateExecutionServiceTest { @Test fun testExecuteNodeTemplate() { runBlocking { - val bluePrintRuntimeService = BlueprintMetadataUtils.getBlueprintRuntime( + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime( "1234", "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration" ) @@ -81,7 +81,7 @@ class NodeTemplateExecutionServiceTest { assertNotNull(executionServiceOutput, "failed to get response") assertEquals( - BlueprintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, + BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message, "failed to get successful response" ) } diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt index e2bc0f131..9c3727288 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt @@ -20,7 +20,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.nodeTemplateComponentScriptExecutor -import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive import org.slf4j.LoggerFactory import org.springframework.beans.factory.config.ConfigurableBeanFactory @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component -fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BlueprintTypes.nodeTemplateComponentScriptExecutor( +fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BluePrintTypes.nodeTemplateComponentScriptExecutor( id, "mock($id) component function" ) { diff --git a/ms/py-executor/blueprints_grpc/__init__.py b/ms/py-executor/blueprints_grpc/__init__.py index 991ddeb0a..8a2db9e1e 100644 --- a/ms/py-executor/blueprints_grpc/__init__.py +++ b/ms/py-executor/blueprints_grpc/__init__.py @@ -12,8 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -from proto.BlueprintCommon_pb2 import * -from proto.BlueprintProcessing_pb2 import * +from proto.BluePrintCommon_pb2 import * +from proto.BluePrintProcessing_pb2 import * from .script_executor_configuration import * from .executor_utils import * from .blueprint_processing_server import * \ No newline at end of file diff --git a/ms/py-executor/blueprints_grpc/blueprint_processing_server.py b/ms/py-executor/blueprints_grpc/blueprint_processing_server.py index 1d2eab732..322d34b0b 100644 --- a/ms/py-executor/blueprints_grpc/blueprint_processing_server.py +++ b/ms/py-executor/blueprints_grpc/blueprint_processing_server.py @@ -16,7 +16,7 @@ import logging from google.protobuf.json_format import MessageToJson -from proto import BlueprintProcessing_pb2_grpc as BlueprintProcessing_pb2_grpc +from proto import BluePrintProcessing_pb2_grpc as BluePrintProcessing_pb2_grpc from .script_executor_configuration import ScriptExecutorConfiguration from .executor_utils import instance_for_input @@ -33,7 +33,7 @@ class AbstractScriptFunction: pass -class BlueprintProcessingServer(BlueprintProcessing_pb2_grpc.BlueprintProcessingServiceServicer): +class BluePrintProcessingServer(BluePrintProcessing_pb2_grpc.BluePrintProcessingServiceServicer): def __init__(self, configuration: ScriptExecutorConfiguration): self.logger = logging.getLogger(self.__class__.__name__) diff --git a/ms/py-executor/blueprints_grpc/executor_utils.py b/ms/py-executor/blueprints_grpc/executor_utils.py index 93197112e..701958fff 100644 --- a/ms/py-executor/blueprints_grpc/executor_utils.py +++ b/ms/py-executor/blueprints_grpc/executor_utils.py @@ -24,14 +24,14 @@ import time from google.protobuf import json_format, struct_pb2 from google.protobuf.timestamp_pb2 import Timestamp -from proto.BlueprintCommon_pb2 import ( +from proto.BluePrintCommon_pb2 import ( EVENT_COMPONENT_EXECUTED, EVENT_COMPONENT_NOTIFICATION, EVENT_COMPONENT_PROCESSING, EVENT_COMPONENT_TRACE, Status ) -from proto.BlueprintProcessing_pb2 import ( +from proto.BluePrintProcessing_pb2 import ( ExecutionServiceInput, ExecutionServiceOutput, ) diff --git a/ms/py-executor/client.py b/ms/py-executor/client.py index bf636a8be..482bcbdd3 100644 --- a/ms/py-executor/client.py +++ b/ms/py-executor/client.py @@ -25,9 +25,9 @@ # limitations under the License. import grpc -from proto.BlueprintCommon_pb2 import ActionIdentifiers, CommonHeader -from proto.BlueprintProcessing_pb2 import ExecutionServiceInput -from proto.BlueprintProcessing_pb2_grpc import BlueprintProcessingServiceStub +from proto.BluePrintCommon_pb2 import ActionIdentifiers, CommonHeader +from proto.BluePrintProcessing_pb2 import ExecutionServiceInput +from proto.BluePrintProcessing_pb2_grpc import BluePrintProcessingServiceStub def generate_messages(): @@ -59,7 +59,7 @@ if __name__ == '__main__': with open('py-executor-chain.pem', 'rb') as f: creds = grpc.ssl_channel_credentials(f.read()) channel = grpc.secure_channel('localhost:50052', creds) - stub = BlueprintProcessingServiceStub(channel) + stub = BluePrintProcessingServiceStub(channel) messages = generate_messages() responses = stub.process(messages) diff --git a/ms/py-executor/resource_resolution/README.md b/ms/py-executor/resource_resolution/README.md index a2edebf98..3920338ae 100644 --- a/ms/py-executor/resource_resolution/README.md +++ b/ms/py-executor/resource_resolution/README.md @@ -5,8 +5,8 @@ ### Insecure channel ``` -from proto.BlueprintCommon_pb2_grpc import ActionIdentifiers, CommonHeader -from proto.BlueprintProcessing_pb2_grpc import ExecutionServiceInput +from proto.BluePrintCommon_pb2_grpc import ActionIdentifiers, CommonHeader +from proto.BluePrintProcessing_pb2_grpc import ExecutionServiceInput from resource_resolution.grpc.client import Client as ResourceResolutionClient @@ -43,8 +43,8 @@ if __name__ == "__main__": ### Secure channel ``` -from proto.BlueprintCommon_pb2_grpc import ActionIdentifiers, CommonHeader -from proto.BlueprintProcessing_pb2_grpc import ExecutionServiceInput +from proto.BluePrintCommon_pb2_grpc import ActionIdentifiers, CommonHeader +from proto.BluePrintProcessing_pb2_grpc import ExecutionServiceInput from resource_resolution.grpc.client import Client as ResourceResolutionClient @@ -82,8 +82,8 @@ if __name__ == "__main__": ### Authorizarion header ``` -from proto.BlueprintCommon_pb2 import ActionIdentifiers, CommonHeader -from proto.BlueprintProcessing_pb2 import ExecutionServiceInput +from proto.BluePrintCommon_pb2 import ActionIdentifiers, CommonHeader +from proto.BluePrintProcessing_pb2 import ExecutionServiceInput from resource_resolution.grpc.client import Client as ResourceResolutionClient diff --git a/ms/py-executor/resource_resolution/grpc/client.py b/ms/py-executor/resource_resolution/grpc/client.py index 95f59b532..fee168628 100644 --- a/ms/py-executor/resource_resolution/grpc/client.py +++ b/ms/py-executor/resource_resolution/grpc/client.py @@ -23,8 +23,8 @@ from grpc import ( secure_channel, ssl_channel_credentials, ) -from proto.BlueprintProcessing_pb2 import ExecutionServiceInput, ExecutionServiceOutput -from proto.BlueprintProcessing_pb2_grpc import BlueprintProcessingServiceStub +from proto.BluePrintProcessing_pb2 import ExecutionServiceInput, ExecutionServiceOutput +from proto.BluePrintProcessing_pb2_grpc import BluePrintProcessingServiceStub from .authorization import AuthTokenInterceptor @@ -69,7 +69,7 @@ class Client: self.logger.debug(f"Create insecure channel to connect to {server_address}") if use_header_auth: self.channel: Channel = intercept_channel(self.channel, AuthTokenInterceptor(header_auth_token)) - self.stub: BlueprintProcessingServiceStub = BlueprintProcessingServiceStub(self.channel) + self.stub: BluePrintProcessingServiceStub = BluePrintProcessingServiceStub(self.channel) def close(self) -> None: """Close client session. diff --git a/ms/py-executor/resource_resolution/resource_resolution.py b/ms/py-executor/resource_resolution/resource_resolution.py index c5f758563..3b8c19b74 100644 --- a/ms/py-executor/resource_resolution/resource_resolution.py +++ b/ms/py-executor/resource_resolution/resource_resolution.py @@ -23,7 +23,7 @@ from typing import Any, Dict, Generator, Optional, Type from google.protobuf import json_format -from proto.BlueprintProcessing_pb2 import ExecutionServiceInput, ExecutionServiceOutput +from proto.BluePrintProcessing_pb2 import ExecutionServiceInput, ExecutionServiceOutput from .grpc import Client as GrpcClient from .http import Client as HttpClient @@ -361,12 +361,12 @@ class ResourceResolution: It's possible to store/retrieve templates using pair of artifact name and resolution key OR resource type and resource id. This method checks if valid combination of parameters were used. - + Args: resolution_key (str, optional): resolutionKey HTTP request parameter value. Defaults to None. resource_type (str, optional): resourceType HTTP request parameter value. Defaults to None. resource_id (str, optional): resourceId HTTP request parameter value. Defaults to None. - + Raises: AttributeError: Invalid combination of parametes used """ diff --git a/ms/py-executor/server.py b/ms/py-executor/server.py index 5df6f9350..7f6537011 100644 --- a/ms/py-executor/server.py +++ b/ms/py-executor/server.py @@ -24,10 +24,10 @@ from pathlib import Path, PurePath import grpc from manager.servicer import ArtifactManagerServicer -from proto.BlueprintManagement_pb2_grpc import add_BlueprintManagementServiceServicer_to_server +from proto.BluePrintManagement_pb2_grpc import add_BluePrintManagementServiceServicer_to_server -from blueprints_grpc import BlueprintProcessing_pb2_grpc, ScriptExecutorConfiguration -from blueprints_grpc.blueprint_processing_server import BlueprintProcessingServer +from blueprints_grpc import BluePrintProcessing_pb2_grpc, ScriptExecutorConfiguration +from blueprints_grpc.blueprint_processing_server import BluePrintProcessingServer from blueprints_grpc.request_header_validator_interceptor import RequestHeaderValidatorInterceptor logger = logging.getLogger("Server") @@ -56,10 +56,10 @@ def serve(configuration: ScriptExecutorConfiguration): # create server server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers))) - BlueprintProcessing_pb2_grpc.add_BlueprintProcessingServiceServicer_to_server( - BlueprintProcessingServer(configuration), server + BluePrintProcessing_pb2_grpc.add_BluePrintProcessingServiceServicer_to_server( + BluePrintProcessingServer(configuration), server ) - add_BlueprintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) + add_BluePrintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) # add secure port using credentials server.add_secure_port('[::]:' + port, server_credentials) @@ -73,10 +73,10 @@ def serve(configuration: ScriptExecutorConfiguration): # create server with token authentication interceptors server = grpc.server(futures.ThreadPoolExecutor(max_workers=int(maxWorkers)), interceptors=(header_validator,)) - BlueprintProcessing_pb2_grpc.add_BlueprintProcessingServiceServicer_to_server( - BlueprintProcessingServer(configuration), server + BluePrintProcessing_pb2_grpc.add_BluePrintProcessingServiceServicer_to_server( + BluePrintProcessingServer(configuration), server ) - add_BlueprintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) + add_BluePrintManagementServiceServicer_to_server(ArtifactManagerServicer(), server) server.add_insecure_port('[::]:' + port) server.start() diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java index 45fb36736..b8868325a 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/SdcListenerNotificationCallback.java @@ -122,13 +122,13 @@ public class SdcListenerNotificationCallback implements INotificationCallback { final String archivePath = cbaArchivePath.toString(); // Extract CBA archive from CSAR package and store it into local disk - csarFiles.forEach(file -> listenerService.extractBlueprint(file.getAbsolutePath(), archivePath)); + csarFiles.forEach(file -> listenerService.extractBluePrint(file.getAbsolutePath(), archivePath)); csarFiles.forEach(file -> FileUtil.deleteFile(file, csarArchivePath.toString())); } else { LOGGER.error("Could not able to read CSAR files from this location {}", csarArchivePath); } - listenerService.saveBlueprintToCdsDatabase(cbaArchivePath, sdcListenerDto.getManagedChannelForGrpc()); + listenerService.saveBluePrintToCdsDatabase(cbaArchivePath, sdcListenerDto.getManagedChannelForGrpc()); } } diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcesssorHandler.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcesssorHandler.java new file mode 100644 index 000000000..b80dd260d --- /dev/null +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcesssorHandler.java @@ -0,0 +1,67 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.sdclistener.handler; + +import io.grpc.ManagedChannel; +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc.BluePrintManagementServiceBlockingStub; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@ConfigurationProperties("listenerservice") +@Component +public class BluePrintProcesssorHandler implements AutoCloseable { + + private static final Logger LOGGER = LoggerFactory.getLogger(BluePrintProcesssorHandler.class); + + private ManagedChannel channel; + + /** + * Sending CBA archive to CDS backend to store into its Database. + * + * @param request BluePrintManagementInput object holds CBA archive, its version and blueprints. + * @param managedChannel - ManagedChannel object helps to access the server or application end point. + * + * @return A response object + */ + public Status sendRequest(BluePrintUploadInput request, ManagedChannel managedChannel) { + LOGGER.info("Sending request to blueprint processor"); + + this.channel = managedChannel; + + final BluePrintManagementServiceBlockingStub syncStub = BluePrintManagementServiceGrpc.newBlockingStub(channel); + + // Send the request to CDS backend. + final BluePrintManagementOutput response = syncStub.uploadBlueprint(request); + + return response.getStatus(); + } + + @Override + public void close() { + if (channel != null) { + channel.shutdown(); + } + LOGGER.info("Stopping GRPC connection to CDS backend"); + } + +} diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcesssorHandler.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcesssorHandler.java deleted file mode 100644 index 41475cd6b..000000000 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcesssorHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.sdclistener.handler; - -import io.grpc.ManagedChannel; -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementOutput; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc.BlueprintManagementServiceBlockingStub; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@ConfigurationProperties("listenerservice") -@Component -public class BlueprintProcesssorHandler implements AutoCloseable { - - private static final Logger LOGGER = LoggerFactory.getLogger(BlueprintProcesssorHandler.class); - - private ManagedChannel channel; - - /** - * Sending CBA archive to CDS backend to store into its Database. - * - * @param request BlueprintManagementInput object holds CBA archive, its version and blueprints. - * @param managedChannel - ManagedChannel object helps to access the server or application end point. - * - * @return A response object - */ - public Status sendRequest(BlueprintUploadInput request, ManagedChannel managedChannel) { - LOGGER.info("Sending request to blueprint processor"); - - this.channel = managedChannel; - - final BlueprintManagementServiceBlockingStub syncStub = BlueprintManagementServiceGrpc.newBlockingStub(channel); - - // Send the request to CDS backend. - final BlueprintManagementOutput response = syncStub.uploadBlueprint(request); - - return response.getStatus(); - } - - @Override - public void close() { - if (channel != null) { - channel.shutdown(); - } - LOGGER.info("Stopping GRPC connection to CDS backend"); - } - -} diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java index 231054f06..5fa3fb327 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerService.java @@ -29,7 +29,7 @@ public interface ListenerService { * @param csarArchivePath The path where CSAR archive is stored. * @param cbaArchivePath The destination path where CBA will be stored. */ - void extractBlueprint(String csarArchivePath, String cbaArchivePath); + void extractBluePrint(String csarArchivePath, String cbaArchivePath); /** * Store the Zip file into CDS database. @@ -37,7 +37,7 @@ public interface ListenerService { * @param path path where zip file exists. * @param managedChannel To access the blueprint processor application end point */ - void saveBlueprintToCdsDatabase(Path path, ManagedChannel managedChannel); + void saveBluePrintToCdsDatabase(Path path, ManagedChannel managedChannel); /** * Extract and store the csar package to local disk. diff --git a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java index 1aebd74b8..ee27a9475 100644 --- a/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java +++ b/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java @@ -23,12 +23,12 @@ import org.apache.commons.io.IOUtils; import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput; import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk; import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction; import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto; -import org.onap.ccsdk.cds.sdclistener.handler.BlueprintProcesssorHandler; +import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler; import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus; import org.onap.ccsdk.cds.sdclistener.util.FileUtil; import org.onap.sdc.api.results.IDistributionClientDownloadResult; @@ -64,7 +64,7 @@ import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK; public class ListenerServiceImpl implements ListenerService { @Autowired - private BlueprintProcesssorHandler bluePrintProcesssorHandler; + private BluePrintProcesssorHandler bluePrintProcesssorHandler; @Autowired private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor; @@ -87,7 +87,7 @@ public class ListenerServiceImpl implements ListenerService { private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class); @Override - public void extractBlueprint(String csarArchivePath, String cbaArchivePath) { + public void extractBluePrint(String csarArchivePath, String cbaArchivePath) { int validPathCount = 0; final String distributionId = getDistributionId(); final String artifactUrl = getArtifactUrl(); @@ -101,7 +101,7 @@ public class ListenerServiceImpl implements ListenerService { validPathCount++; final String cbaArchiveName = Paths.get(fileName).getFileName().toString(); LOGGER.info("Storing the CBA archive {}", cbaArchiveName); - storeBlueprint(zipFile, cbaArchiveName, cbaStorageDir, entry); + storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry); } } @@ -121,7 +121,7 @@ public class ListenerServiceImpl implements ListenerService { } } - private void storeBlueprint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) { + private void storeBluePrint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) { Path targetLocation = cbaArchivePath.resolve(fileName); LOGGER.info("The target location for zip file is {}", targetLocation); File targetZipFile = new File(targetLocation.toString()); @@ -144,7 +144,7 @@ public class ListenerServiceImpl implements ListenerService { } @Override - public void saveBlueprintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) { + public void saveBluePrintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) { List zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath); if (!zipFiles.isEmpty()) { prepareRequestForCdsBackend(zipFiles, channel, cbaArchivePath.toString()); @@ -193,7 +193,7 @@ public class ListenerServiceImpl implements ListenerService { files.forEach(zipFile -> { try { - final BlueprintUploadInput request = generateBlueprintUploadInputBuilder(zipFile, path); + final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile, path); // Send request to CDS Backend. final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel); @@ -219,11 +219,11 @@ public class ListenerServiceImpl implements ListenerService { }); } - private BlueprintUploadInput generateBlueprintUploadInputBuilder(File file, String path) throws IOException { + private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file, String path) throws IOException { byte[] bytes = FileUtils.readFileToByteArray(file); FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build(); FileUtil.deleteFile(file, path); - return BlueprintUploadInput.newBuilder() + return BluePrintUploadInput.newBuilder() .setCommonHeader(CommonHeader.newBuilder().setRequestId(UUID.randomUUID().toString()) .setSubRequestId(UUID.randomUUID().toString()).setOriginatorId("SDC-LISTENER").build()) .setActionIdentifiers( diff --git a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcessorHandlerTest.java b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcessorHandlerTest.java new file mode 100644 index 000000000..7cde45d9e --- /dev/null +++ b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BluePrintProcessorHandlerTest.java @@ -0,0 +1,124 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.sdclistener.handler; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase; +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput; +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk; +import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction; +import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@EnableConfigurationProperties({BluePrintProcesssorHandler.class, SdcListenerAuthClientInterceptor.class}) +@SpringBootTest(classes = {BluePrintProcessorHandlerTest.class}) +public class BluePrintProcessorHandlerTest { + + @Autowired + private BluePrintProcesssorHandler bluePrintProcesssorHandler; + + @Autowired + private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor; + + @Rule + public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + private static final String CBA_ARCHIVE = "src/test/resources/testcba.zip"; + private static final String SUCCESS_MSG = "Successfully uploaded CBA"; + private static final int SUCCESS_CODE = 200; + private ManagedChannel channel; + + @Before + public void setUp() throws IOException { + final BluePrintManagementServiceImplBase serviceImplBase = new BluePrintManagementServiceImplBase() { + @Override + public void uploadBlueprint(BluePrintUploadInput request, + StreamObserver responseObserver) { + responseObserver.onNext(getBluePrintManagementOutput()); + responseObserver.onCompleted(); + } + }; + + // Generate server name. + String serverName = InProcessServerBuilder.generateName(); + + // Create a server, add service, start, and register. + grpcCleanup.register(InProcessServerBuilder.forName(serverName).addService(serviceImplBase).directExecutor() + .build().start()); + + // Create a client channel. + channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); + } + + @Test + public void testApplicationEndPointSucess() throws IOException { + // Arrange + BluePrintUploadInput request = generateRequest(); + + // Act + Status output = bluePrintProcesssorHandler.sendRequest(request, channel); + + // Verify + assertEquals(SUCCESS_CODE, output.getCode()); + assertTrue(output.getMessage().contains(SUCCESS_MSG)); + } + + private BluePrintUploadInput generateRequest() throws IOException { + File file = Paths.get(CBA_ARCHIVE).toFile(); + byte[] bytes = FileUtils.readFileToByteArray(file); + FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build(); + + return BluePrintUploadInput.newBuilder() + .setCommonHeader(CommonHeader.newBuilder().setRequestId(UUID.randomUUID().toString()) + .setSubRequestId(UUID.randomUUID().toString()).setOriginatorId("SDC-LISTENER").build()) + .setActionIdentifiers( + ActionIdentifiers.newBuilder().setActionName(UploadAction.PUBLISH.toString()).build()) + .setFileChunk(fileChunk).build(); + } + + private BluePrintManagementOutput getBluePrintManagementOutput() { + return BluePrintManagementOutput.newBuilder() + .setStatus(Status.newBuilder().setMessage(SUCCESS_MSG).setCode(200).build()).build(); + } + +} diff --git a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcessorHandlerTest.java b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcessorHandlerTest.java deleted file mode 100644 index b48a98e15..000000000 --- a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/handler/BlueprintProcessorHandlerTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.cds.sdclistener.handler; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; -import io.grpc.testing.GrpcCleanupRule; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; -import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; -import org.onap.ccsdk.cds.controllerblueprints.common.api.Status; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementOutput; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintManagementServiceGrpc.BlueprintManagementServiceImplBase; -import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput; -import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk; -import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction; -import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Paths; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -@RunWith(SpringRunner.class) -@EnableConfigurationProperties({BlueprintProcesssorHandler.class, SdcListenerAuthClientInterceptor.class}) -@SpringBootTest(classes = {BlueprintProcessorHandlerTest.class}) -public class BlueprintProcessorHandlerTest { - - @Autowired - private BlueprintProcesssorHandler bluePrintProcesssorHandler; - - @Autowired - private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor; - - @Rule - public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); - - private static final String CBA_ARCHIVE = "src/test/resources/testcba.zip"; - private static final String SUCCESS_MSG = "Successfully uploaded CBA"; - private static final int SUCCESS_CODE = 200; - private ManagedChannel channel; - - @Before - public void setUp() throws IOException { - final BlueprintManagementServiceImplBase serviceImplBase = new BlueprintManagementServiceImplBase() { - @Override - public void uploadBlueprint(BlueprintUploadInput request, - StreamObserver responseObserver) { - responseObserver.onNext(getBlueprintManagementOutput()); - responseObserver.onCompleted(); - } - }; - - // Generate server name. - String serverName = InProcessServerBuilder.generateName(); - - // Create a server, add service, start, and register. - grpcCleanup.register(InProcessServerBuilder.forName(serverName).addService(serviceImplBase).directExecutor() - .build().start()); - - // Create a client channel. - channel = grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()); - } - - @Test - public void testApplicationEndPointSucess() throws IOException { - // Arrange - BlueprintUploadInput request = generateRequest(); - - // Act - Status output = bluePrintProcesssorHandler.sendRequest(request, channel); - - // Verify - assertEquals(SUCCESS_CODE, output.getCode()); - assertTrue(output.getMessage().contains(SUCCESS_MSG)); - } - - private BlueprintUploadInput generateRequest() throws IOException { - File file = Paths.get(CBA_ARCHIVE).toFile(); - byte[] bytes = FileUtils.readFileToByteArray(file); - FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build(); - - return BlueprintUploadInput.newBuilder() - .setCommonHeader(CommonHeader.newBuilder().setRequestId(UUID.randomUUID().toString()) - .setSubRequestId(UUID.randomUUID().toString()).setOriginatorId("SDC-LISTENER").build()) - .setActionIdentifiers( - ActionIdentifiers.newBuilder().setActionName(UploadAction.PUBLISH.toString()).build()) - .setFileChunk(fileChunk).build(); - } - - private BlueprintManagementOutput getBlueprintManagementOutput() { - return BlueprintManagementOutput.newBuilder() - .setStatus(Status.newBuilder().setMessage(SUCCESS_MSG).setCode(200).build()).build(); - } - -} diff --git a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java index 2e55c8e25..4179ccab0 100644 --- a/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java +++ b/ms/sdclistener/application/src/test/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImplTest.java @@ -29,7 +29,7 @@ import org.mockito.junit.MockitoRule; import org.onap.ccsdk.cds.sdclistener.SdcListenerConfiguration; import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor; import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto; -import org.onap.ccsdk.cds.sdclistener.handler.BlueprintProcesssorHandler; +import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler; import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus; import org.onap.sdc.api.results.IDistributionClientDownloadResult; import org.onap.sdc.impl.mock.DistributionClientResultStubImpl; @@ -50,7 +50,7 @@ import static org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus.Notificati import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK; @RunWith(SpringRunner.class) -@EnableConfigurationProperties({SdcListenerAuthClientInterceptor.class, BlueprintProcesssorHandler.class, +@EnableConfigurationProperties({SdcListenerAuthClientInterceptor.class, BluePrintProcesssorHandler.class, SdcListenerDto.class, ListenerServiceImpl.class, SdcListenerStatus.class, SdcListenerConfiguration.class}) @SpringBootTest(classes = {ListenerServiceImplTest.class}) public class ListenerServiceImplTest { @@ -90,9 +90,9 @@ public class ListenerServiceImplTest { } @Test - public void extractBlueprintSuccessfully() throws IOException { + public void extractBluePrintSuccessfully() throws IOException { // Act - listenerService.extractBlueprint(CSAR_SAMPLE, tempDirectoryPath.toString()); + listenerService.extractBluePrint(CSAR_SAMPLE, tempDirectoryPath.toString()); // Verify. String result = checkFileExists(tempDirectoryPath); @@ -100,7 +100,7 @@ public class ListenerServiceImplTest { } @Test - public void extractBlueprintFailure() { + public void extractBluePrintFailure() { // Arrange Mockito.when(listenerDto.getDistributionId()).thenReturn(DISTRIBUTION_ID); Mockito.when(listenerDto.getArtifactUrl()).thenReturn(URL); @@ -108,7 +108,7 @@ public class ListenerServiceImplTest { SDC_LISTENER_COMPONENT); // Act - listenerService.extractBlueprint(WRONG_CSAR_SAMPLE, tempDirectoryPath.toString()); + listenerService.extractBluePrint(WRONG_CSAR_SAMPLE, tempDirectoryPath.toString()); // Verify Mockito.verify(status).sendResponseBackToSdc(DISTRIBUTION_ID, COMPONENT_DONE_OK, null, URL, -- cgit 1.2.3-korg