From adcd4f2bc695840e9ecbc05003bc52c675f22fec Mon Sep 17 00:00:00 2001 From: KAPIL SINGAL Date: Fri, 22 Jan 2021 11:49:51 -0500 Subject: Renaming Files having BluePrint to have Blueprint Replacing BluePrint with Blueprint throughout Issue-ID: CCSDK-3098 Signed-off-by: KAPIL SINGAL Change-Id: Ibee8bad07ae7d9287073db2d4f2f2cd730fa8b96 --- .../core/BluePrintConstants.kt | 251 ------- .../controllerblueprints/core/BluePrintError.kt | 30 - .../core/BluePrintException.kt | 34 - .../core/BluePrintExtensionFunctions.kt | 148 ---- .../core/BluePrintProcessorException.kt | 175 ----- .../controllerblueprints/core/BluePrintTypes.kt | 170 ----- .../core/BlueprintConstants.kt | 251 +++++++ .../controllerblueprints/core/BlueprintError.kt | 30 + .../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 | 184 ----- .../core/data/BluePrintModel.kt | 736 ------------------- .../core/data/BlueprintExpressionData.kt | 77 ++ .../core/data/BlueprintGraph.kt | 184 +++++ .../core/data/BlueprintModel.kt | 736 +++++++++++++++++++ .../controllerblueprints/core/dsl/BluePrintDSL.kt | 408 ----------- .../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 | 408 +++++++++++ .../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 | 350 --------- .../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 | 350 +++++++++ .../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 | 317 -------- .../core/dsl/BlueprintDSLTest.kt | 317 ++++++++ .../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 | 84 --- .../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 | 109 --- .../BlueprintArtifactDefinitionValidatorImpl.kt | 99 +++ .../BlueprintArtifactTypeValidatorImpl.kt | 36 + .../BlueprintAttributeDefinitionValidatorImpl.kt | 92 +++ .../validation/BlueprintDataTypeValidatorImpl.kt | 35 + .../BlueprintDesignTimeValidatorService.kt | 84 +++ .../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 | 109 +++ .../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 +- 173 files changed, 13175 insertions(+), 13175 deletions(-) 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/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/annotations/BluePrintsAnnotations.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/config/BluePrintLoadConfiguration.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/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/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/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 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 100755 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/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/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/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/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 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 100755 ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt delete mode 100755 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/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt create mode 100644 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/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript 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/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/BlueprintErrorTest.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/annotations/BlueprintsAnnotationsTest.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/dsl/BlueprintDSLTest.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/scripts/BlueprintScriptsServiceImplTest.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/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/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-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-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/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/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/BlueprintDesignTimeValidatorServiceTest.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/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBlueprintTypeValidatorService.kt (limited to 'ms/blueprintsprocessor/modules/blueprints') 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 9439c2d98..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt +++ /dev/null @@ -1,251 +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 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" -} 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 71a107171..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt +++ /dev/null @@ -1,30 +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 { - - var errors: MutableList = arrayListOf() - - fun addError(type: String, name: String, error: String) { - this.errors.add("$type : $name : $error") - } - - fun addError(error: String) { - this.errors.add(error) - } -} 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 74e6bb6bd..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 daf833494..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 c818b0a44..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 1c769932f..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/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..fdd1d5d83 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintConstants.kt @@ -0,0 +1,251 @@ +/* + * 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 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" +} 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..b4d95ca3b --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BlueprintError.kt @@ -0,0 +1,30 @@ +/* + * 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 { + + var errors: MutableList = arrayListOf() + + fun addError(type: String, name: String, error: String) { + this.errors.add("$type : $name : $error") + } + + fun addError(error: String) { + this.errors.add(error) + } +} 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..10e6f5959 --- /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..0a1b0954a --- /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..10a299bd0 --- /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..cb78ea19f --- /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/CustomFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt index ebe682611..25abcd30b 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 518e9b236..ca3d815f3 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 deleted file mode 100644 index c39442976..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/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..a72860ae2 --- /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/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 adfbf2905..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/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..5176ffefd --- /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/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 b833db755..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt +++ /dev/null @@ -1,184 +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 { edge -> edge.target(this) } - - fun neighbors(label: EdgeLabel): List = edges.filter { it.label == label } - .map { edge -> edge.target(this) } - - 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 target(node: Node): Node = target - - 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 9f32d8830..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/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..b833db755 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BlueprintGraph.kt @@ -0,0 +1,184 @@ +/* + * 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 { edge -> edge.target(this) } + + fun neighbors(label: EdgeLabel): List = edges.filter { it.label == label } + .map { edge -> edge.target(this) } + + 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 target(node: Node): Node = target + + 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..49736c18b --- /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/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 88f852d41..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt +++ /dev/null @@ -1,408 +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" - ) { - } -} - -@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 b469ded74..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 370531d2a..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 d07fc9c71..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 3a3503403..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 3dfdbac57..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 8a1a9d63c..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/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..503e07048 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSL.kt @@ -0,0 +1,408 @@ +/* + * 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" + ) { + } +} + +@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..f92a955a5 --- /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..8f1a8d145 --- /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..21bc8c7d8 --- /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..f8f6080ad --- /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..3b3b4b41f --- /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..0de1a510c --- /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/ServiceTemplateBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/ServiceTemplateBuilder.kt index 254e644b3..4391e89e0 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 deleted file mode 100755 index bd45bed06..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 fcc9bf2d7..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 2080cd161..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/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 8d04e5489..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 aa61b0c4d..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/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 70c797326..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/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 100644 index 000000000..87ee0e4f9 --- /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..109bc7b85 --- /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..318fd2b91 --- /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/BlueprintFunctionNode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt index b56fac541..4f6689022 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 new file mode 100644 index 000000000..631236a40 --- /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..b7a06e264 --- /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/BlueprintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt index 1958e23ac..799011568 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 0d9876b81..5f36e8ede 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 new file mode 100644 index 000000000..4f20a1a33 --- /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/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 230097f3c..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 a0efc619c..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 f3eb1a2b9..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/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..5cf0a93af --- /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..a6d4571a2 --- /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..c89d74dfb --- /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/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 1a43c3066..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 7b11f71a2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt +++ /dev/null @@ -1,350 +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 workflowStepByName(workFlowName: String, stepName: String): Step { - return workflowByName(workFlowName).steps?.get(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 = workflowByName(workFlowName).steps?.keys?.first() - ?: throw BluePrintException("could't get first step for workflow($workFlowName)") - 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 e8457283e..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 193ff7888..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 80b742705..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 fdc348bf7..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 1f71495a3..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 873e3a082..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 d7f7b9a60..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 8a8ded752..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 43e27d047..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 f3e4e59aa..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/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..e0a0f170b --- /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..b79b86747 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BlueprintContext.kt @@ -0,0 +1,350 @@ +/* + * 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 workflowStepByName(workFlowName: String, stepName: String): Step { + return workflowByName(workFlowName).steps?.get(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 = workflowByName(workFlowName).steps?.keys?.first() + ?: throw BlueprintException("could't get first step for workflow($workFlowName)") + 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..8f3308568 --- /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..ac90705a1 --- /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..6dbacd199 --- /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..ac85cb3e8 --- /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..dd07bade2 --- /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..c05b94260 --- /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..d953bd54f --- /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..888c5c0c6 --- /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..1c4847900 --- /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..b5121caac --- /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/PropertyAssignmentService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt index b246054e2..7a5a2d58f 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 deleted file mode 100755 index 1a7c23cf1..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 100755 index 292eca92e..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 d29fed0d9..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 43f3a0b53..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 f4c51d455..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/BlueprintArchiveUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BlueprintArchiveUtils.kt new file mode 100644 index 000000000..a16f58042 --- /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 100644 index 000000000..583709f08 --- /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..c2e0ec39c --- /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..ffaa9e72f --- /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..1df185cf6 --- /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/ClusterUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ClusterUtils.kt index 7fe955b03..cacfc2cd2 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 02dd2027d..14b308bc9 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 ace66cf7a..1110f6f34 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 48319325c..1a082d353 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 c0204af8d..1b8af5897 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 fea637f61..6ebe7c11a 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 deleted file mode 100644 index e69de29bb..000000000 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/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 6a028d36f..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.errors.isEmpty()) - } - - @Test - fun testAddErrorWith3Params() { - val bluePrintError = BluePrintError() - - bluePrintError.addError("type", "name", "error") - - assertEquals("type : name : error", bluePrintError.errors[0]) - } - - @Test - fun testAddErrorWith1Params() { - val bluePrintError = BluePrintError() - - bluePrintError.addError("error") - - assertEquals("error", bluePrintError.errors[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 new file mode 100644 index 000000000..482d21abd --- /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.errors.isEmpty()) + } + + @Test + fun testAddErrorWith3Params() { + val bluePrintError = BlueprintError() + + bluePrintError.addError("type", "name", "error") + + assertEquals("type : name : error", bluePrintError.errors[0]) + } + + @Test + fun testAddErrorWith1Params() { + val bluePrintError = BlueprintError() + + bluePrintError.addError("error") + + assertEquals("error", bluePrintError.errors[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 7ac9b8649..8c1e9f65f 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 643549be0..0fe2fbf7f 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 deleted file mode 100644 index a75262f96..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/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..b19c3502a --- /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/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 9aea47a9e..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt +++ /dev/null @@ -1,317 +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() - - 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 new file mode 100644 index 000000000..5143c9dc7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BlueprintDSLTest.kt @@ -0,0 +1,317 @@ +/* + * 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() + + 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 deleted file mode 100644 index 0803d921b..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/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..7dd980dc7 --- /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/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 38f6ea2ec..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 4f645270d..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 265175165..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 4fcbb2d98..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 0e93ccf6b..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 eb6246989..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/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..4ad4ab403 --- /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..552f7b6f8 --- /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..5ef28cce2 --- /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..268811091 --- /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..6ebb6b7ff --- /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..291a81f28 --- /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/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 6e19656ec..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 62bb0afcb..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 6ccfe1e95..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/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..ac74f7ab1 --- /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..d0c32cc39 --- /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..b03fb9fc1 --- /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/JacksonUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt index d78e62f28..ec12639fb 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 83764c517..f2d63531d 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 5dd1937f8..4ba7694ee 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 deleted file mode 100644 index 73504314b..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 b31211e2d..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 9a4650104..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 dab6a78bc..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 67bdd0396..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt +++ /dev/null @@ -1,84 +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.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) - - if (bluePrintRuntimeService.getBluePrintError().errors.size > 0) { - throw BluePrintException("failed in blueprint validation : ${bluePrintRuntimeService.getBluePrintError().errors.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 6fa83119e..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 04a3fd046..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 5683c0170..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 d71e78c43..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!!) - } - } - - 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 a7fb3d57e..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 db7d91a22..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 a1a9eb913..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 25b5af0b2..000000000 --- a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt +++ /dev/null @@ -1,109 +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!! - ) - } - } - } - 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 new file mode 100644 index 000000000..d9f4db728 --- /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..ebcdf9f52 --- /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..ef02e84c3 --- /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..35680c2ac --- /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..fe3aeb1ed --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintDesignTimeValidatorService.kt @@ -0,0 +1,84 @@ +/* + * 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.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) + + if (bluePrintRuntimeService.getBlueprintError().errors.size > 0) { + throw BlueprintException("failed in blueprint validation : ${bluePrintRuntimeService.getBlueprintError().errors.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..0374424e8 --- /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..b7ec2d150 --- /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..4d69d3acd --- /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..b9450e66d --- /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!!) + } + } + + 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..d9bd51619 --- /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..4e5f0da16 --- /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..b4d2372d0 --- /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..8f9cb01c5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BlueprintWorkflowValidatorImpl.kt @@ -0,0 +1,109 @@ +/* + * 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!! + ) + } + } + } + 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 78a5d379e..d7dcd9713 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 dc5da2669..044c5296b 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 63aa7e537..91d01c6a0 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 deleted file mode 100644 index dcf352927..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().errors.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().errors[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().errors.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().errors[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 new file mode 100644 index 000000000..49c12b95f --- /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().errors.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().errors[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().errors.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().errors[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 deleted file mode 100644 index 11c6c037c..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/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..69f57a0b9 --- /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/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 f8dea9871..e6a0ab6e4 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 b97492dc8..e5d9f5f8b 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 5117c4388..7da46f582 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 c09474a2b..3833cbe93 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 66df5078c..af0607763 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 862f1892d..79f21cfdf 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)); -- cgit 1.2.3-korg