aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/modules
diff options
context:
space:
mode:
Diffstat (limited to 'ms/blueprintsprocessor/modules')
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/pom.xml105
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt213
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt29
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt49
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt148
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.kt57
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt164
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt30
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt333
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt108
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt115
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt51
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt100
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt23
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt28
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt77
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt180
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt652
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt103
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt41
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt313
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt477
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt80
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt232
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt211
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.kt408
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt581
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt121
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt57
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt60
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt154
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt50
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt39
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt28
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt72
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt65
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt175
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt178
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt76
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt82
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt125
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt296
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt53
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt230
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt94
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt115
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt76
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt649
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateService.kt65
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt706
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt99
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowService.kt353
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt259
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt158
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt292
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt41
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt213
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintRuntimeUtils.kt64
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt47
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt92
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt327
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt62
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt62
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt108
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt132
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt46
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript0
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory17
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintErrorTest.kt33
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt238
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctionTest.kt33
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctionsTest.kt37
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt58
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/TestConstants.kt24
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt119
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt292
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt87
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt583
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt140
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt58
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt207
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintTemplateServiceTest.kt82
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt271
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt57
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt41
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt80
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtilsTest.kt42
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt74
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtilsTest.kt58
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtilsTest.kt38
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtilsTest.kt42
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt57
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/SampleBlueprintFunctionNode.kt66
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/TOSCA-Metadata/TOSCA.meta7
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/componentnode/default.json100
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/alltype-data.json10
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/default-context.json7
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/dictionary/dictionary_schema.json299
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment1.properties2
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment2.properties2
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/logback-test.xml31
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/convert.json36
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/default.json16
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-jinja.json3
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-velocity.json36
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-velocity-template.vtl61
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-data.json3
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-velocity-template.vtl2
-rwxr-xr-xms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/interface.jinja3
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/isis.jinja3
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/master.jinja7
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-proto/krotoPlusConfig.asciipb6
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-proto/pom.xml114
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/pom.xml64
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt99
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt36
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt92
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt35
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt84
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTemplateValidatorImpl.kt274
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintNodeTypeValidatorImpl.kt179
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt89
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt115
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt76
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt114
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt24
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt108
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt50
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt46
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt115
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt108
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt86
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/pom.xml39
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/pom.xml43
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinition.kt108
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDictionaryConstants.kt38
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt46
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt142
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt119
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.kt99
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinitionTest.java61
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactoryTest.java43
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt66
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtilsTest.java40
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java100
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryTestUtils.kt31
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/data/resource-assignment-input.json10
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/cyclic.json111
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/duplicate.json110
-rw-r--r--ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/success.json110
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/pom.xml8
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt35
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt7
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/PrimaryDBLibGenericService.kt (renamed from ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt)11
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt12
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt40
-rwxr-xr-xms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModel.kt16
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelContent.kt19
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelSearch.kt10
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelContentRepository.kt18
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelRepository.kt5
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelSearchRepository.kt25
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt22
-rwxr-xr-xms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt50
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt30
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt54
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt16
-rw-r--r--ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties1
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt15
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt13
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt3
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt48
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt12
-rw-r--r--ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt86
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt4
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt4
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcClientLoggingInterceptor.kt31
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt34
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt17
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt29
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt33
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt34
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt18
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt37
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt132
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt39
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt35
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-chain.pem60
-rw-r--r--ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-key.pem100
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt3
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt1
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt25
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt24
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerService.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageConsumerService.kt13
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageProducerService.kt20
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerService.kt8
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt28
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt81
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt27
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerServiceTest.kt65
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt5
-rw-r--r--ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt7
-rwxr-xr-xms/blueprintsprocessor/modules/commons/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/ApiDataExtensions.kt31
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt7
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt41
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt49
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt3
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/ApiDataUtils.kt (renamed from ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappings.kt)102
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt62
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt (renamed from ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingTests.kt)13
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt5
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt6
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt29
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt59
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt100
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt36
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt27
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt13
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt134
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt4
-rw-r--r--ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt221
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt11
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt20
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt12
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientService.kt2
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt27
-rw-r--r--ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt27
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/configs-api/pom.xml5
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt82
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotExceptionHandler.kt17
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt48
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt62
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt179
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt76
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt8
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt13
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt11
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaJsonNodeConverter.kt3
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaResourceDefinitionConverter.kt2
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ModelType.kt14
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ResourceDictionary.kt14
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt19
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt14
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt25
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt17
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt40
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt13
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt18
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt9
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt10
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt13
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt39
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt42
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt52
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt145
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt11
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt15
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt5
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt12
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt10
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt9
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepository.kt (renamed from ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/BluePrintsReactRepository.kt)16
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeRepository.kt11
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepository.kt4
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt36
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt86
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintSortByOption.kt (renamed from ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/SortByOptionsEnum.kt)2
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt17
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt147
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt138
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiTestConfiguration.kt7
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt25
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryControllerTest.kt11
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt60
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt18
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt31
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/mock/MockFilePart.kt8
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt28
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryReactRepositoryTest.kt (renamed from ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepositoryTest.kt)14
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt11
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/pom.xml3
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/BasicAuthRestClientServiceConfiguration.kt1
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt24
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/SecurityEncryptionConfiguration.kt4
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ApplicationHealth.kt2
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/HealthApiResponse.kt7
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/Metrics.kt1
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/MetricsResponse.kt4
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceEndpoint.kt1
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceName.kt2
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServicesCheckResponse.kt3
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/WebClientEnpointResponse.kt3
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/EndPointExecution.kt13
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt13
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt8
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/SDCListenerHealthCheck.kt16
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt99
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/SecurityConfigurationTest.kt1
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedHealth.kt16
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt16
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt23
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt28
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt18
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/pom.xml1
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceController.kt85
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceExceptionHandler.kt17
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateController.kt76
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt62
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt24
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt60
-rwxr-xr-xms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml8
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt23
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt41
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt40
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt44
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt6
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt8
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt51
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt28
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt21
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt48
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt4
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/SelfServiceApiTestConfiguration.kt29
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt60
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt19
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/UtilsTest.kt (renamed from ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt)3
-rw-r--r--ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt12
-rw-r--r--ms/blueprintsprocessor/modules/pom.xml1
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/pom.xml8
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt40
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt4
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt2
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt47
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt106
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt148
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutor.kt15
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt70
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ExecutionServiceConfiguration.kt3
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt77
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt31
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt48
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt6
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt5
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt11
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt196
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt50
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt64
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt36
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt33
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHostTest.kt13
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleComponent.kt24
-rw-r--r--ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleTest.kt3
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/pom.xml4
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt29
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt3
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt29
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt22
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt29
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt84
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt24
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt3
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt20
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt2
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt59
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt39
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt24
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt48
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt23
-rw-r--r--ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt14
391 files changed, 21888 insertions, 2517 deletions
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/pom.xml b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/pom.xml
new file mode 100644
index 000000000..4700c6337
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/pom.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprints</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>blueprint-core</artifactId>
+
+ <name>Controller Blueprints Core</name>
+
+ <dependencies>
+ <!-- Compiler Service -->
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-compiler-embeddable</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-scripting-jvm-host</artifactId>
+ <exclusions>
+ <exclusion>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-compiler</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-script-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-script-runtime</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-xml</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.dataformat</groupId>
+ <artifactId>jackson-dataformat-yaml</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.module</groupId>
+ <artifactId>jackson-module-jsonSchema</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.projectreactor</groupId>
+ <artifactId>reactor-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.yaml</groupId>
+ <artifactId>snakeyaml</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.hubspot.jinjava</groupId>
+ <artifactId>jinjava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-logging</artifactId>
+ </dependency>
+ <!--Testing dependencies-->
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-test-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>io.mockk</groupId>
+ <artifactId>mockk</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlinx</groupId>
+ <artifactId>kotlinx-coroutines-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
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..9520f679c
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintConstants.kt
@@ -0,0 +1,213 @@
+/*
+ * 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
+
+/**
+ * BluePrintConstants
+ *
+ * @author Brinda Santh
+ */
+object BluePrintConstants {
+
+ val APP_NAME = System.getProperty("APPLICATION_NAME")
+ ?: System.getProperty("APP_NAME")
+ ?: System.getProperty("APPNAME")
+ ?: "cds-controller-default"
+
+ 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_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 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_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_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"
+
+ 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_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_AUTHOR = "template_author"
+ const val METADATA_TEMPLATE_TAGS = "template_tags"
+ 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 DEFAULT_VERSION_NUMBER = "1.0.0"
+ const val DEFAULT_STEP_OPERATION = "process"
+ const val DEFAULT_STEP_INTERFACE = "ComponentInterface"
+
+ const val ARTIFACT_VELOCITY_TYPE_NAME = "artifact-template-velocity"
+ const val ARTIFACT_JINJA_TYPE_NAME = "artifact-template-jinja"
+
+ 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"
+}
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..66d54f52e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintError.kt
@@ -0,0 +1,29 @@
+/*
+ * 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<String> = 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..a2435da13
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintException.kt
@@ -0,0 +1,49 @@
+/*
+ * 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
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintException : Exception {
+
+ var code: Int = 100
+
+ 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(String.format(message, *args), cause)
+
+ constructor(code: Int, cause: Throwable) : super(cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String) : super(message) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String, cause: Throwable) : super(message, cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) :
+ super(String.format(message, *args), cause) {
+ this.code = code
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt
new file mode 100644
index 000000000..daf833494
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintExtensionFunctions.kt
@@ -0,0 +1,148 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core
+
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.ArtifactExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.AttributeExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsConstrain
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsDataType
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.BluePrintsProperty
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.DSLExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.InputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.OperationOutputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyDefaultValue
+import org.onap.ccsdk.cds.controllerblueprints.core.annotations.PropertyExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ConstraintClause
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EntrySchema
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.dslExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getInput
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateArtifact
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateAttribute
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateOperationOutput
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.getNodeTemplateProperty
+import kotlin.reflect.KClass
+import kotlin.reflect.KProperty1
+import kotlin.reflect.KType
+import kotlin.reflect.full.declaredMemberProperties
+
+fun <T : KClass<*>> 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 : KClass<*>> T.asPropertyDefinitionMap(): MutableMap<String, PropertyDefinition> {
+ val properties: MutableMap<String, PropertyDefinition> = hashMapOf()
+ this.declaredMemberProperties.forEach { member ->
+ properties[member.name] = member.asPropertyDefinition()
+ }
+ return properties
+}
+
+fun <T> KProperty1<T, *>.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 : KType> 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 : KType> 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..b0b217051
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintProcessorException.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
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintProcessorException : RuntimeException {
+
+ var code: Int = 100
+
+ 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)
+
+ constructor(code: Int, cause: Throwable) : super(cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String) : super(message) {
+ this.code = code
+ }
+
+ constructor(code: Int, message: String, cause: Throwable) : super(message, cause) {
+ this.code = code
+ }
+
+ constructor(code: Int, cause: Throwable, message: String, vararg args: Any?) :
+ super(String.format(message, *args), cause) {
+ this.code = code
+ }
+}
+
+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)
+}
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..0e4279a3a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/BluePrintTypes.kt
@@ -0,0 +1,164 @@
+/*
+ * 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<String> = 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<String> = arrayListOf(
+ BluePrintConstants.MODEL_TYPE_ARTIFACTS_ROOT,
+ BluePrintConstants.MODEL_TYPE_ARTIFACT_TYPE_IMPLEMENTATION
+ )
+
+ @JvmStatic
+ val validDataTypeDerivedFroms: MutableList<String> = arrayListOf(
+ BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT,
+ BluePrintConstants.MODEL_TYPE_DATA_TYPE_DYNAMIC
+ )
+
+ @JvmStatic
+ val validRelationShipDerivedFroms: MutableList<String> = 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<String> = 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_SSH,
+ BluePrintConstants.MODEL_TYPE_CAPABILITY_TYPE_SFTP
+ )
+
+ @JvmStatic
+ fun validModelTypes(): List<String> {
+ val validTypes: MutableList<String> = 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<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.addAll(validPrimitiveTypes())
+ validTypes.addAll(validComplexTypes())
+ validTypes.addAll(validCollectionTypes())
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validPrimitiveTypes(): List<String> {
+ val validTypes: MutableList<String> = 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<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.DATA_TYPE_JSON)
+ return validTypes
+ }
+
+ @JvmStatic
+ fun validCollectionTypes(): List<String> {
+ val validTypes: MutableList<String> = arrayListOf()
+ validTypes.add(BluePrintConstants.DATA_TYPE_LIST)
+ validTypes.add(BluePrintConstants.DATA_TYPE_MAP)
+ 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<String> {
+ 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<String> {
+ return listOf(BluePrintConstants.MODEL_TYPE_NODES_ROOT)
+ }
+
+ @JvmStatic
+ fun rootDataTypes(): List<String> {
+ 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/ConfigModelConstant.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt
new file mode 100644
index 000000000..e8e13f2b0
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/ConfigModelConstant.kt
@@ -0,0 +1,30 @@
+/*
+ * 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
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ConfigModelConstant {
+
+ const val MODEL_CONTENT_TYPE_TOSCA_JSON = "TOSCA_JSON"
+ const val MODEL_CONTENT_TYPE_TEMPLATE = "TEMPLATE"
+ const val CAPABILITY_PROPERTY_MAPPING = "mapping"
+}
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
new file mode 100644
index 000000000..5189d0758
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctions.kt
@@ -0,0 +1,333 @@
+/*
+ * 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
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.DoubleNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
+import org.apache.commons.lang3.ObjectUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JsonParserUtils
+import org.slf4j.LoggerFactory
+import org.slf4j.helpers.MessageFormatter
+import java.util.UUID
+import kotlin.reflect.KClass
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+
+fun <T : Any> logger(clazz: T) = LoggerFactory.getLogger(clazz.javaClass)!!
+
+fun <T : KClass<*>> logger(clazz: T) = LoggerFactory.getLogger(clazz.java)!!
+
+fun <T : Any> T?.defaultToEmpty(): String {
+ return this?.toString() ?: ""
+}
+
+fun <T : Any> T?.defaultToUUID(): String {
+ return this?.toString() ?: UUID.randomUUID().toString()
+}
+
+fun <T : Any> T.bpClone(): T {
+ return ObjectUtils.clone(this)
+}
+
+fun String.isJson(): Boolean {
+ return ((this.trim().startsWith("{") && this.trim().endsWith("}")) ||
+ (this.trim().startsWith("[") && this.trim().endsWith("]")))
+}
+
+fun Any.asJsonString(intend: Boolean? = false): String {
+ return JacksonUtils.getJson(this, intend!!)
+}
+
+fun String.asJsonPrimitive(): TextNode {
+ return TextNode(this)
+}
+
+inline fun <reified T : Any> String.jsonAsType(): T {
+ return JacksonUtils.readValue<T>(this.trim())
+}
+
+// If you know the string is json content, then use the function directly
+fun String.jsonAsJsonType(): JsonNode {
+ return JacksonUtils.jsonNode(this.trim())
+}
+
+fun Boolean.asJsonPrimitive(): BooleanNode {
+ return BooleanNode.valueOf(this)
+}
+
+fun Int.asJsonPrimitive(): IntNode {
+ return IntNode.valueOf(this)
+}
+
+fun Double.asJsonPrimitive(): DoubleNode {
+ return DoubleNode.valueOf(this)
+}
+
+/**
+ * Utility to convert Primitive object to Json Type Primitive.
+ */
+fun <T : Any?> T.asJsonPrimitive(): JsonNode {
+ return if (this == null || this is MissingNode || this is NullNode) {
+ NullNode.instance
+ } else {
+ when (this) {
+ is String ->
+ this.asJsonPrimitive()
+ is Boolean ->
+ this.asJsonPrimitive()
+ is Int ->
+ this.asJsonPrimitive()
+ is Double ->
+ this.asJsonPrimitive()
+ else ->
+ throw BluePrintException("$this type is not supported")
+ }
+ }
+}
+
+/** 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()
+ // For List, Map and Complex Types.
+ else -> this.jsonAsJsonType()
+ }
+}
+
+/**
+ * Utility to convert Complex or Primitive object to Json Type.
+ */
+fun <T : Any?> T.asJsonType(): JsonNode {
+ return if (this == null || this is MissingNode || this is NullNode) {
+ NullNode.instance
+ } else {
+ when (this) {
+ is JsonNode ->
+ this
+ is String -> {
+ if (this.isJson())
+ this.jsonAsJsonType()
+ else
+ TextNode(this)
+ }
+ is Boolean ->
+ BooleanNode.valueOf(this)
+ is Int ->
+ IntNode.valueOf(this.toInt())
+ is Double ->
+ DoubleNode.valueOf(this.toDouble())
+ else ->
+ JacksonUtils.jsonNodeFromObject(this)
+ }
+ }
+}
+
+fun Map<String, *>.asJsonNode(): JsonNode {
+ return JacksonUtils.jsonNodeFromObject(this)
+}
+
+fun Map<String, *>.asObjectNode(): ObjectNode {
+ return JacksonUtils.objectNodeFromObject(this)
+}
+
+fun format(message: String, vararg args: Any?): String {
+ if (args != null && args.isNotEmpty()) {
+ return MessageFormatter.arrayFormat(message, args).message
+ }
+ return message
+}
+
+fun <T : Any> Map<String, *>.castOptionalValue(key: String, valueType: KClass<T>): T? {
+ return if (containsKey(key)) {
+ get(key) as? T
+ } else {
+ null
+ }
+}
+
+fun <T : Any> Map<String, *>.castValue(key: String, valueType: KClass<T>): T {
+ if (containsKey(key)) {
+ return get(key) as T
+ } else {
+ throw BluePrintException("couldn't find the key $key")
+ }
+}
+
+fun ArrayNode.asListOfString(): List<String> {
+ return JacksonUtils.getListFromJsonNode(this, String::class.java)
+}
+
+fun <T> JsonNode.asType(clazzType: Class<T>): T {
+ return JacksonUtils.readValue(this, clazzType)
+ ?: throw BluePrintException("couldn't convert JsonNode of type $clazzType")
+}
+
+fun JsonNode.asListOfString(): List<String> {
+ check(this is ArrayNode) { "JsonNode is not of type ArrayNode" }
+ return this.asListOfString()
+}
+
+fun <T : JsonNode> T?.returnNullIfMissing(): JsonNode? {
+ return if (this == null || this is NullNode || this is MissingNode) {
+ null
+ } else this
+}
+
+fun <T : JsonNode> T?.isNullOrMissing(): Boolean {
+ return this == null || this is NullNode || this is MissingNode
+}
+
+/**
+ * Convert Json to map of json node, the root fields will be map keys
+ */
+fun JsonNode.rootFieldsToMap(): MutableMap<String, JsonNode> {
+ if (this is ObjectNode) {
+ val propertyMap: MutableMap<String, JsonNode> = linkedMapOf()
+ this.fields().forEach {
+ propertyMap[it.key] = it.value
+ }
+ return propertyMap
+ } else {
+ throw BluePrintException("json node should be Object Node Type")
+ }
+}
+
+fun JsonNode.removeNullNode() {
+ val it = this.iterator()
+ while (it.hasNext()) {
+ val child = it.next()
+ if (child.isNull) {
+ it.remove()
+ } else {
+ child.removeNullNode()
+ }
+ }
+}
+
+fun MutableMap<String, JsonNode>.putJsonElement(key: String, value: Any) {
+ val convertedValue = value.asJsonType()
+ this[key] = convertedValue
+}
+
+fun Map<String, JsonNode>.getAsString(key: String): String {
+ return this[key]?.asText() ?: throw BluePrintException("couldn't find value for key($key)")
+}
+
+fun Map<String, JsonNode>.getAsBoolean(key: String): Boolean {
+ return this[key]?.asBoolean() ?: throw BluePrintException("couldn't find value for key($key)")
+}
+
+fun Map<String, JsonNode>.getAsInt(key: String): Int {
+ return this[key]?.asInt() ?: throw BluePrintException("couldn't find value for key($key)")
+}
+
+fun Map<String, JsonNode>.getAsDouble(key: String): Double {
+ return this[key]?.asDouble() ?: throw BluePrintException("couldn't find value for key($key)")
+}
+
+fun Map<String, JsonNode>.getOptionalAsString(key: String): String? {
+ return if (this.containsKey(key)) this[key]!!.asText() else null
+}
+
+fun Map<String, JsonNode>.getOptionalAsBoolean(key: String): Boolean? {
+ return if (this.containsKey(key)) this[key]!!.asBoolean() else null
+}
+
+fun Map<String, JsonNode>.getOptionalAsInt(key: String): Int? {
+ return if (this.containsKey(key)) this[key]!!.asInt() else null
+}
+
+fun Map<String, JsonNode>.getOptionalAsDouble(key: String): Double? {
+ return if (this.containsKey(key)) this[key]!!.asDouble() else null
+}
+
+// Checks
+
+inline fun checkEquals(value1: String?, value2: String?, lazyMessage: () -> Any): Boolean {
+ if (value1.equals(value2, ignoreCase = true)) {
+ return true
+ } else {
+ throw BluePrintException(lazyMessage().toString())
+ }
+}
+
+inline fun checkNotEmpty(value: String?, lazyMessage: () -> Any): String {
+ if (value == null || value.isEmpty()) {
+ val message = lazyMessage()
+ throw IllegalStateException(message.toString())
+ } else {
+ return value
+ }
+}
+
+inline fun checkNotBlank(value: String?, lazyMessage: () -> Any): String {
+ if (value == null || value.isBlank()) {
+ val message = lazyMessage()
+ throw IllegalStateException(message.toString())
+ } else {
+ return value
+ }
+}
+
+fun isNotEmpty(value: String?): Boolean {
+ return value != null && value.isNotEmpty()
+}
+
+fun isNotBlank(value: String?): Boolean {
+ return value != null && value.isNotBlank()
+}
+
+fun <T : String> T?.emptyTONull(): String? {
+ return if (this == null || this.isEmpty()) null else this
+}
+
+fun nullToEmpty(value: String?): String {
+ return if (isNotEmpty(value)) value!! else ""
+}
+
+inline fun <reified T : JsonNode> T.isComplexType(): Boolean {
+ return this is ObjectNode || this is ArrayNode
+}
+
+// Json Parsing Extensions
+fun JsonNode.jsonPathParse(expression: String): JsonNode {
+ check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
+ return JsonParserUtils.parse(this, expression)
+}
+
+// Json Path Extensions
+fun JsonNode.jsonPaths(expression: String): List<String> {
+ check(this.isComplexType()) { "$this is not complex or array node to apply expression" }
+ return JsonParserUtils.paths(this, expression)
+}
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
new file mode 100644
index 000000000..518e9b236
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctions.kt
@@ -0,0 +1,108 @@
+/*
+ * 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 kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.apache.commons.io.FileUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
+import java.io.File
+import java.io.InputStream
+import java.nio.charset.Charset
+import java.nio.file.Path
+import java.nio.file.Paths
+
+fun InputStream.toFile(path: String): File {
+ val file = File(path)
+ file.outputStream().use { this.copyTo(it) }
+ return file
+}
+
+fun File.reCreateDirs(): File {
+ if (this.exists()) {
+ this.deleteRecursively()
+ }
+ // this.mkdirs()
+ FileUtils.forceMkdir(this)
+ check(this.exists()) {
+ throw BluePrintException("failed to re create dir(${this.absolutePath})")
+ }
+ return this
+}
+
+fun File.compress(targetZipFileName: String): File {
+ return this.compress(Paths.get(targetZipFileName).toFile())
+}
+
+/**
+ * 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)
+ return targetZipFile
+}
+
+fun File.deCompress(targetFileName: String): File {
+ return this.deCompress(Paths.get(targetFileName).toFile())
+}
+
+/**
+ * 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)
+ return targetFile
+}
+
+fun deleteDir(path: String, vararg more: String?) {
+ normalizedFile(path, *more).deleteRecursively()
+}
+
+fun checkFileExists(file: File, lazyMessage: () -> Any) {
+ if (!file.exists()) {
+ val message = lazyMessage()
+ throw IllegalStateException(message.toString())
+ }
+}
+
+fun normalizedFile(path: String, vararg more: String?): File {
+ return Paths.get(path, *more).toFile().normalize()
+}
+
+fun normalizedPath(path: String, vararg more: String?): Path {
+ return Paths.get(path, *more).toAbsolutePath().normalize()
+}
+
+fun normalizedPathName(path: String, vararg more: String?): String {
+ return normalizedPath(path, *more).toString()
+}
+
+suspend fun File.reCreateNBDirs(): File = withContext(Dispatchers.IO) {
+ reCreateDirs()
+}
+
+suspend fun deleteNBDir(path: String, vararg more: String?): Boolean = withContext(Dispatchers.IO) {
+ normalizedFile(path, *more).deleteRecursively()
+}
+
+suspend fun File.readNBText(): String = withContext(Dispatchers.IO) {
+ readText(Charset.defaultCharset())
+}
+
+suspend fun File.readNBLines(): List<String> = withContext(Dispatchers.IO) {
+ readLines(Charset.defaultCharset())
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt
new file mode 100644
index 000000000..5995a8a9e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctions.kt
@@ -0,0 +1,115 @@
+/*
+ * 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.data.EdgeLabel
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.WorkflowGraphUtils
+import java.util.regex.Pattern
+
+private val graphTokenSeparators = Pattern.compile("[->/]")
+
+/** Convert Blueprint workflow to graph data structure */
+fun Workflow.asGraph(): Graph {
+ return WorkflowGraphUtils.workFlowToGraph(this)
+}
+
+fun String.toGraph(): Graph {
+ if (!startsWith('[') || !endsWith(']')) {
+ throw IllegalArgumentException("Expected string starting '[' and ending with ']' but it was '$")
+ }
+ val tokens = substring(1, length - 1).split(", ").map { it.split(graphTokenSeparators) }
+ val nodes = tokens.flatMap { it.take(2) }.toCollection(LinkedHashSet())
+ val edges = tokens.filter { it.size == 3 }.map { Graph.TermForm.Term(it[0], it[1], EdgeLabel.valueOf(it[2])) }
+ return Graph.labeledDirectedTerms(Graph.TermForm(nodes, edges))
+}
+
+fun Graph.toAdjacencyList(): Graph.AdjacencyList<String, EdgeLabel> {
+ val entries = nodes.values.map { node ->
+ val links = node.edges.map { Graph.AdjacencyList.Link(it.target(node).id, it.label) }
+ Graph.AdjacencyList.Entry(node = node.id, links = links)
+ }
+ return Graph.AdjacencyList(entries)
+}
+
+fun Graph.findAllPaths(from: String, to: String, path: List<String> = emptyList()): List<List<String>> {
+ if (from == to) return listOf(path + to)
+ return nodes[from]!!.neighbors()
+ .filter { !path.contains(it.id) }
+ .flatMap { findAllPaths(it.id, to, path + from) }
+}
+
+fun Graph.findCycles(node: String): List<List<String>> {
+ fun findCycles(path: List<String>): List<List<String>> {
+ if (path.size > 3 && path.first() == path.last()) return listOf(path)
+ return nodes[path.last()]!!.neighbors()
+ .filterNot { path.tail().contains(it.id) }
+ .flatMap { findCycles(path + it.id) }
+ }
+ return findCycles(listOf(node))
+}
+
+fun Graph.startNodes() = this.nodes.values.filter {
+ val incomingEdges = incomingEdges(it.id)
+ incomingEdges.isEmpty()
+}
+
+fun Graph.endNodes(): Set<Graph.Node> = this.nodes.values.filter {
+ outgoingEdges(it.id).isEmpty()
+}.toSet()
+
+fun Graph.node(node: String) = this.nodes[node]
+
+fun Graph.edge(label: EdgeLabel) =
+ this.edges.filter { it.label == label }
+
+fun Graph.incomingEdges(node: String) =
+ this.edges.filter { it.target.id == node }
+
+fun Graph.incomingNodes(node: String) =
+ this.incomingEdges(node).map { it.source }
+
+fun Graph.outgoingEdges(node: String) =
+ this.edges.filter { it.source.id == node }
+
+fun Graph.outgoingNodes(node: String) =
+ this.outgoingEdges(node).map { it.target }
+
+fun Graph.outgoingEdges(node: String, label: EdgeLabel) =
+ this.edges.filter { it.source.id == node && it.label == label }
+
+fun Graph.outgoingNodes(node: String, label: EdgeLabel) =
+ this.outgoingEdges(node, label).map { it.target }
+
+fun Graph.outgoingNodesNotInEdgeLabels(node: String, labels: List<EdgeLabel>) =
+ this.outgoingEdgesNotInLabels(node, labels).map { it.target }
+
+fun Graph.outgoingEdges(node: String, labels: List<EdgeLabel>) =
+ this.edges.filter { it.source.id == node && labels.contains(it.label) }
+
+fun Graph.outgoingEdgesNotInLabels(node: String, labels: List<EdgeLabel>) =
+ this.edges.filter { it.source.id == node && !labels.contains(it.label) }
+
+fun Graph.outgoingNodes(node: String, labels: List<EdgeLabel>) =
+ this.outgoingEdges(node, labels).map { it.target }
+
+fun Graph.isEndNode(node: Graph.Node): Boolean {
+ return this.endNodes().contains(node)
+}
+
+fun <T> List<T>.tail(): List<T> = drop(1)
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt
new file mode 100644
index 000000000..9d81f13e3
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContext.kt
@@ -0,0 +1,51 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core
+
+import kotlinx.coroutines.ThreadContextElement
+import org.slf4j.MDC
+import kotlin.coroutines.AbstractCoroutineContextElement
+import kotlin.coroutines.CoroutineContext
+
+typealias MDCContextMap = Map<String, String>?
+
+class MDCContext(private val contextMap: MDCContextMap = MDC.getCopyOfContextMap()) :
+ ThreadContextElement<MDCContextMap>, AbstractCoroutineContextElement(Key) {
+
+ /**
+ * Key of [MDCContext] in [CoroutineContext].
+ */
+ companion object Key : CoroutineContext.Key<MDCContext>
+
+ override fun updateThreadContext(context: CoroutineContext): MDCContextMap {
+ val oldState = MDC.getCopyOfContextMap()
+ setCurrent(contextMap)
+ return oldState
+ }
+
+ override fun restoreThreadContext(context: CoroutineContext, oldState: MDCContextMap) {
+ setCurrent(oldState)
+ }
+
+ private fun setCurrent(contextMap: MDCContextMap) {
+ if (contextMap == null) {
+ MDC.clear()
+ } else {
+ MDC.setContextMap(contextMap)
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt
new file mode 100644
index 000000000..c39442976
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotations.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.annotations
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import kotlin.reflect.KClass
+
+@Target(AnnotationTarget.CLASS)
+annotation class BluePrintsDataType(
+ val name: String,
+ val version: String = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ val description: String,
+ val derivedFrom: String = "tosca.datatypes.root"
+)
+
+@Target(AnnotationTarget.CLASS)
+annotation class BluePrintsWorkflowInput
+
+@Target(AnnotationTarget.CLASS)
+annotation class BluePrintsWorkflowOutput
+
+@Target(AnnotationTarget.CLASS)
+annotation class BluePrintsNodeType(
+ val propertiesType: KClass<*>,
+ val attributesType: KClass<*>,
+ val inputsType: KClass<*>,
+ val outputsType: KClass<*>
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class BluePrintsProperty(
+ val name: String = "",
+ val description: String = ""
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+@Repeatable
+annotation class BluePrintsConstrain()
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class PropertyDefaultValue(val value: String)
+
+annotation class PropertyValidValue(val value: String)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class InputExpression(
+ val propertyName: String
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class PropertyExpression(
+ val modelableEntityName: String = "SELF",
+ val reqOrCapEntityName: String = "",
+ val propertyName: String,
+ val subPropertyName: String = ""
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class AttributeExpression(
+ val modelableEntityName: String = "SELF",
+ val reqOrCapEntityName: String = "",
+ val attributeName: String,
+ val subAttributeName: String = ""
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class ArtifactExpression(
+ val modelableEntityName: String = "SELF",
+ val artifactName: String,
+ val location: String = "LOCAL_FILE",
+ val remove: Boolean = false
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class OperationOutputExpression(
+ val modelableEntityName: String = "SELF",
+ val interfaceName: String,
+ val operationName: String,
+ val propertyName: String,
+ val subPropertyName: String = ""
+)
+
+@Target(AnnotationTarget.FIELD, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.PROPERTY)
+annotation class DSLExpression(
+ val propertyName: String
+)
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt
new file mode 100644
index 000000000..66bc3b3cb
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/common/ApplicationConstants.kt
@@ -0,0 +1,23 @@
+/*
+ * Copyright © 2019 Bell Canada
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.common
+
+object ApplicationConstants {
+ const val ACTIVE_Y = "Y"
+ const val ACTIVE_N = "N"
+ const val ASDC_ARTIFACT_TYPE_SDNC_MODEL = "SDNC_MODEL"
+}
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..0128f64a5
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/config/BluePrintLoadConfiguration.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.config
+
+open class BluePrintLoadConfiguration {
+ lateinit var blueprintDeployPath: String
+ lateinit var blueprintArchivePath: String
+ lateinit var blueprintWorkingPath: String
+
+ var loadBluePrintPaths: String? = null
+ var loadModeTypePaths: String? = null
+ var loadResourceDictionaryPaths: String? = null
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt
new file mode 100644
index 000000000..37c128714
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintExpressionData.kt
@@ -0,0 +1,77 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 - 2019 IBM, Bell Canada.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+@file:Suppress("unused")
+
+package org.onap.ccsdk.cds.controllerblueprints.core.data
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+data class ExpressionData(
+ var isExpression: Boolean = false,
+ var valueNode: JsonNode,
+ var expressionNode: ObjectNode? = null,
+ var dslExpression: DSLExpression? = null,
+ var inputExpression: InputExpression? = null,
+ var propertyExpression: PropertyExpression? = null,
+ var attributeExpression: AttributeExpression? = null,
+ var artifactExpression: ArtifactExpression? = null,
+ var operationOutputExpression: OperationOutputExpression? = null,
+ var command: String? = null
+)
+
+data class InputExpression(
+ var propertyName: String
+)
+
+data class PropertyExpression(
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var propertyName: String,
+ var subPropertyName: String? = null
+)
+
+data class AttributeExpression(
+ var modelableEntityName: String = "SELF",
+ var reqOrCapEntityName: String? = null,
+ var attributeName: String,
+ var subAttributeName: String? = null
+)
+
+data class ArtifactExpression(
+ val modelableEntityName: String = "SELF",
+ val artifactName: String,
+ val location: String? = "LOCAL_FILE",
+ val remove: Boolean? = false
+)
+
+data class OperationOutputExpression(
+ val modelableEntityName: String = "SELF",
+ val interfaceName: String,
+ val operationName: String,
+ val propertyName: String,
+ var subPropertyName: String? = null
+)
+
+data class DSLExpression(
+ val propertyName: String
+)
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt
new file mode 100644
index 000000000..9c9b1f9bf
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintGraph.kt
@@ -0,0 +1,180 @@
+/*
+ * 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<String, Node> = hashMapOf()
+ val edges: MutableSet<Edge> = 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<Edge> = ArrayList()
+
+ fun neighbors(): List<Node> = edges.map { edge -> edge.target(this) }
+
+ fun neighbors(label: EdgeLabel): List<Node> = edges.filter { it.label == label }
+ .map { edge -> edge.target(this) }
+
+ fun labelEdges(label: EdgeLabel): List<Edge> = 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<String>, val edges: List<Term>) {
+
+ data class Term(val source: String, val target: String, val label: EdgeLabel) {
+ override fun toString() = "Term($source, $target, $label)"
+ }
+ }
+
+ data class AdjacencyList<String, out EdgeLabel>(val entries: List<Entry<String, EdgeLabel>>) {
+ constructor(vararg entries: Entry<String, EdgeLabel>) : this(entries.asList())
+
+ override fun toString() = "AdjacencyList(${entries.joinToString()})"
+
+ data class Entry<out String, out EdgeLabel>(val node: String, val links: List<Link<String, EdgeLabel>> = emptyList<Nothing>()) {
+ constructor(node: String, vararg links: Link<String, EdgeLabel>) : this(node, links.asList())
+
+ override fun toString() = "Entry($node, links[${links.joinToString()}])"
+ }
+
+ data class Link<out String, out EdgeLabel>(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<String, EdgeLabel>): 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<String, EdgeLabel>,
+ 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..71a31dcca
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/BluePrintModel.kt
@@ -0,0 +1,652 @@
+/*
+ * 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
+
+/**
+ *
+ *
+ * @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<String, String>? = null
+ @get:JsonProperty("derived_from")
+ lateinit var derivedFrom: String
+ var attributes: MutableMap<String, AttributeDefinition>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = 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<String, String>? = 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<JsonNode>? = null
+ @get:JsonProperty("valid_values")
+ var validValues: MutableList<JsonNode>? = 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<String, PropertyDefinition>? = null
+ var capabilities: MutableList<String>? = 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<String, JsonNode>? = 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("default")
+ var defaultValue: JsonNode? = null
+ var status: String? = null
+ var constraints: MutableList<ConstraintClause>? = null
+ @get:JsonProperty("entry_schema")
+ var entrySchema: EntrySchema? = null
+ @get:JsonProperty("external-schema")
+ var externalSchema: String? = null
+ var metadata: MutableMap<String, String>? = 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<ConstraintClause>? = 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<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = null
+}
+
+class Implementation {
+ var primary: String? = null
+ var dependencies: MutableList<String>? = null
+ @get:JsonProperty("operation_host")
+ var operationHost: String = BluePrintConstants.PROPERTY_SELF
+ // Timeout value in seconds
+ var timeout: Int = 180
+}
+
+/*
+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<String, OperationDefinition>? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = 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<String>? = 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<ConditionClause>
+}
+
+/*
+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<Activity>? = null
+ @get:JsonProperty("on_success")
+ var onSuccess: ArrayList<String>? = null
+ @get:JsonProperty("on_failure")
+ var onFailure: ArrayList<String>? = 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<String, PropertyDefinition>? = null
+ @get:JsonProperty("valid_source_types")
+ var validSourceTypes: MutableList<String>? = null
+ var occurrences: MutableList<Any>? = 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<Any>? = 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<String>? = 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<ConstraintClause>? = 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<String, CapabilityDefinition>? = null
+ var requirements: MutableMap<String, RequirementDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = 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<String, RequirementDefinition>? = null
+ var capabilities: MutableMap<String, CapabilityDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = 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<String, InterfaceDefinition>? = null
+ @get:JsonProperty("valid_target_types")
+ var validTargetTypes: MutableList<String>? = 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<String>? = null
+ var requirements: ArrayList<RequirementDefinition>? = null
+ var capabilities: MutableMap<String, CapabilityDefinition>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = 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<String>
+}
+
+/*
+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<String, JsonNode>? = null
+ var properties: MutableMap<String, JsonNode>? = 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<String, String>? = null
+ var properties: MutableMap<String, JsonNode>? = null
+ var members = ArrayList<String>()
+ var interfaces: MutableMap<String, InterfaceDefinition>? = 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<String, String>? = null
+ var properties: MutableMap<String, JsonNode>? = null
+ var targets: MutableList<String>? = 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<String, PropertyDefinition>? = null
+ @get:JsonProperty("node_templates")
+ var nodeTemplates: MutableMap<String, NodeTemplate>? = null
+ @get:JsonProperty("relationship_templates")
+ var relationshipTemplates: MutableMap<String, RelationshipTemplate>? = null
+ var policies: MutableMap<String, PolicyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = null
+ @get:JsonProperty("substitution_mappings")
+ var substitutionMappings: Any? = null
+ var workflows: MutableMap<String, Workflow>? = null
+}
+
+class SubstitutionMapping {
+ @get:JsonProperty("node_type")
+ lateinit var nodeType: String
+ lateinit var capabilities: ArrayList<String>
+ lateinit var requirements: ArrayList<String>
+}
+
+class EntrySchema {
+ lateinit var type: String
+ var constraints: MutableList<ConstraintClause>? = null
+}
+
+class InterfaceAssignment {
+ @get:JsonIgnore
+ var id: String? = null
+ var operations: MutableMap<String, OperationAssignment>? = null
+ var inputs: MutableMap<String, JsonNode>? = 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<String, String>? = null
+ var directives: MutableList<String>? = null
+ // @get:JsonSerialize(using = PropertyDefinitionValueSerializer::class)
+ var properties: MutableMap<String, JsonNode>? = null
+ var attributes: MutableMap<String, JsonNode>? = null
+ var capabilities: MutableMap<String, CapabilityAssignment>? = null
+ var requirements: MutableMap<String, RequirementAssignment>? = null
+ var interfaces: MutableMap<String, InterfaceAssignment>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = 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<String, JsonNode>? = null
+ var outputs: MutableMap<String, JsonNode>? = 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 {
+ var type: String? = null
+ var description: String? = null
+ var metadata: MutableMap<String, String>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ var attributes: MutableMap<String, JsonNode>? = null
+ var interfaces: MutableMap<String, InterfaceDefinition>? = 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<String, Step>? = null
+ var preconditions: ArrayList<PreConditionDefinition>? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = null
+}
+
+class ConditionClause {
+ var and: ArrayList<MutableMap<String, Any>>? = null
+ var or: ArrayList<MutableMap<String, Any>>? = null
+ @get:JsonProperty("assert")
+ var assertConditions: ArrayList<MutableMap<String, Any>>? = 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<String, String>? = null
+ var description: String? = null
+ @get:JsonProperty("dsl_definitions")
+ var dslDefinitions: MutableMap<String, JsonNode>? = null
+ var repositories: MutableMap<String, RepositoryDefinition>? = null
+ var imports: MutableList<ImportDefinition>? = null
+ @get:JsonProperty("artifact_types")
+ var artifactTypes: MutableMap<String, ArtifactType>? = null
+ @get:JsonProperty("data_types")
+ var dataTypes: MutableMap<String, DataType>? = null
+ @get:JsonProperty("relationship_types")
+ var relationshipTypes: MutableMap<String, RelationshipType>? = null
+ @get:JsonProperty("node_types")
+ var nodeTypes: MutableMap<String, NodeType>? = null
+ @get:JsonProperty("policy_types")
+ var policyTypes: MutableMap<String, PolicyType>? = 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
+ var templateName: String? = null
+ var templateVersion: String? = null
+ var templateTags: String? = null
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt
new file mode 100644
index 000000000..8bdedd429
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/data/ErrorCode.kt
@@ -0,0 +1,103 @@
+/*
+ * Copyright © 2018-2019 Bell Canada Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onap.ccsdk.cds.controllerblueprints.core.data
+
+import java.util.HashMap
+
+/**
+ * ErrorCode.java Purpose: Maintain a list of HTTP status codes
+ *
+ * @author Steve Siani
+ * @version 1.0
+ */
+enum class ErrorCode(val value: Int, val httpCode: Int) {
+
+ // / TODO: Add more attribute for each needed application protocol
+ // TODO: Example: INVALID_FILE_EXTENSION(2, 415, 25)
+ GENERIC_FAILURE(1, 500) {
+
+ override fun message(detailMsg: String): String {
+ return "Generic failure. Details : {$detailMsg}"
+ }
+ },
+ INVALID_FILE_EXTENSION(2, 415) {
+ override fun message(detailMsg: String): String {
+ return "Unexpected file extension. Details : {$detailMsg}"
+ }
+ },
+ BLUEPRINT_PATH_MISSING(3, 503) {
+ override fun message(detailMsg: String): String {
+ return "Blueprint path missing or wrong. Details : {$detailMsg}"
+ }
+ },
+ BLUEPRINT_WRITING_FAIL(4, 503) {
+ override fun message(detailMsg: String): String {
+ return "Fail to write blueprint files. Details : {$detailMsg}"
+ }
+ },
+ IO_FILE_INTERRUPT(5, 503) {
+ override fun message(detailMsg: String): String {
+ return "IO file system interruption. Details : {$detailMsg}"
+ }
+ },
+ INVALID_REQUEST_FORMAT(6, 400) {
+ override fun message(detailMsg: String): String {
+ return "Bad request. Details : {$detailMsg}"
+ }
+ },
+ UNAUTHORIZED_REQUEST(7, 401) {
+ override fun message(detailMsg: String): String {
+ return "The request requires user authentication. Details : {$detailMsg}"
+ }
+ },
+ REQUEST_NOT_FOUND(8, 404) {
+ override fun message(detailMsg: String): String {
+ return "Request mapping doesn't exist. Details : {$detailMsg}"
+ }
+ },
+ RESOURCE_NOT_FOUND(9, 404) {
+ override fun message(detailMsg: String): String {
+ return "No response was found for this request in the server. Details : {$detailMsg}"
+ }
+ },
+ CONFLICT_ADDING_RESOURCE(10, 409) {
+ override fun message(detailMsg: String): String {
+ return "Duplicated entry while saving Blueprint. Details : {$detailMsg}"
+ }
+ },
+ DUPLICATE_DATA(11, 409) {
+ override fun message(detailMsg: String): String {
+ return "Duplicated data - was expecting one result, got more than one. Details : {$detailMsg}"
+ }
+ };
+
+ abstract fun message(detailMsg: String): String
+
+ companion object {
+
+ private val map = HashMap<Int, ErrorCode>()
+
+ init {
+ for (errorCode in ErrorCode.values()) {
+ map[errorCode.value] = errorCode
+ }
+ }
+
+ fun valueOf(value: Int): ErrorCode? {
+ return if (map.containsKey(value)) map[value] else map[1]
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.kt
new file mode 100644
index 000000000..13e9f0e5a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/AbstractNodeTemplateOperationImplBuilder.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.dsl
+
+abstract class AbstractNodeTemplateOperationImplBuilder<Prop : PropertiesAssignmentBuilder,
+ In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>(
+ id: String,
+ type: String,
+ private val interfaceName: String,
+ description: String
+ ) : AbstractNodeTemplatePropertyImplBuilder<Prop>(id, type, description) {
+
+ open fun definedOperation(description: String, block: OperationAssignmentBuilder<In, Out>.() -> Unit) {
+ typedOperation<In, Out>(interfaceName, description, block)
+ }
+}
+
+abstract class AbstractNodeTemplatePropertyImplBuilder<Prop : PropertiesAssignmentBuilder>(
+ id: String,
+ type: String,
+ description: String
+) : NodeTemplateBuilder(id, type, description) {
+
+ open fun definedProperties(block: Prop.() -> Unit) {
+ typedProperties<Prop>(block)
+ }
+}
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..9964687a6
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSL.kt
@@ -0,0 +1,313 @@
+/*
+ * 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: BluePrintServiceDSLBuilder.() -> Unit
+): ServiceTemplate {
+ return BluePrintServiceDSLBuilder(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 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"
+ ) {
+ }
+}
+
+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 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 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 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 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 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")
+ }
+}
+
+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 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 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 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 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"
+ ) {
+ }
+}
+
+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"
+ ) {
+ }
+}
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..f2e964a1d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLBuilder.kt
@@ -0,0 +1,477 @@
+/*
+ * 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<String, String> = hashMapOf()
+ var properties: MutableMap<String, JsonNode>? = null
+ var dataTypes: MutableMap<String, DataType> = hashMapOf()
+ var artifactTypes: MutableMap<String, ArtifactType> = hashMapOf()
+ var components: MutableMap<String, DSLComponent> = hashMapOf()
+ private var registryComponents: MutableMap<String, DSLRegistryComponent> = hashMapOf()
+ var workflows: MutableMap<String, DSLWorkflow> = 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<String, PropertyDefinition>? = null
+ var attributes: MutableMap<String, AttributeDefinition>? = null
+
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ var implementation: Implementation? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = 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<String, JsonNode>? = null
+
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ var implementation: Implementation? = null
+ var inputs: MutableMap<String, JsonNode>? = null
+ var outputs: MutableMap<String, JsonNode>? = 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<String, Step>? = null
+ private var inputs: MutableMap<String, PropertyDefinition>? = null
+ private var outputs: MutableMap<String, PropertyDefinition>? = 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..8b5c4151a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLData.kt
@@ -0,0 +1,80 @@
+/*
+ * 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<String, String> = hashMapOf()
+ var properties: MutableMap<String, JsonNode>? = null
+ var dataTypes: MutableMap<String, DataType> = hashMapOf()
+ var artifactTypes: MutableMap<String, ArtifactType> = hashMapOf()
+ var components: MutableMap<String, DSLComponent> = hashMapOf()
+ var registryComponents: MutableMap<String, DSLRegistryComponent> = hashMapOf()
+ var workflows: MutableMap<String, DSLWorkflow> = hashMapOf()
+}
+
+class DSLWorkflow {
+ @get:JsonIgnore
+ var id: String? = null
+ lateinit var description: String
+ lateinit var actionName: String
+ lateinit var steps: MutableMap<String, Step>
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = 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<String, AttributeDefinition>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ var inputs: MutableMap<String, PropertyDefinition>? = null
+ var outputs: MutableMap<String, PropertyDefinition>? = 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<String, JsonNode>? = null
+ var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ var inputs: MutableMap<String, JsonNode>? = null
+ var outputs: MutableMap<String, JsonNode>? = null
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt
new file mode 100644
index 000000000..ca4d56338
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceDSLBuilder.kt
@@ -0,0 +1,232 @@
+/*
+ * 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.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
+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.ImportDefinition
+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.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import kotlin.reflect.KClass
+
+class BluePrintServiceDSLBuilder(
+ private val name: String,
+ private val version: String,
+ private val author: String,
+ private val tags: String
+) {
+
+ private var serviceTemplate = ServiceTemplate()
+ private var topologyTemplate: TopologyTemplate? = null
+ private var metadata: MutableMap<String, String> = hashMapOf()
+ private var dslDefinitions: MutableMap<String, JsonNode>? = null
+ private var imports: MutableList<ImportDefinition> = mutableListOf()
+ private var nodeTypes: MutableMap<String, NodeType>? = null
+ private var artifactTypes: MutableMap<String, ArtifactType>? = null
+ private var dataTypes: MutableMap<String, DataType>? = null
+ private var relationshipTypes: MutableMap<String, RelationshipType>? = null
+ private var policyTypes: MutableMap<String, PolicyType>? = 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
+ }
+
+ fun metadata(id: String, value: String) {
+ metadata[id] = value
+ }
+
+ fun import(file: String) {
+ val importDefinition = ImportDefinition().apply {
+ this.file = file
+ }
+ imports.add(importDefinition)
+ }
+
+ fun dsl(id: String, kclass: KClass<*>) {
+ dsl(id, kclass.asPropertyDefinitionMap().asJsonNode())
+ }
+
+ fun dataType(dataType: KClass<*>) {
+ dataType(dataType.asBluePrintsDataTypes())
+ }
+
+ fun dsl(id: String, content: Any) {
+ dsl(id, content.asJsonType())
+ }
+
+ fun dsl(id: String, json: JsonNode) {
+ if (dslDefinitions == null)
+ dslDefinitions = hashMapOf()
+ dslDefinitions!![id] = json
+ }
+
+ fun dataTypes(dataTypes: MutableMap<String, DataType>) {
+ if (this.dataTypes == null)
+ this.dataTypes = hashMapOf()
+
+ this.dataTypes!!.putAll(dataTypes)
+ }
+
+ fun artifactTypes(artifactTypes: MutableMap<String, ArtifactType>) {
+ if (this.artifactTypes == null)
+ this.artifactTypes = hashMapOf()
+
+ this.artifactTypes!!.putAll(artifactTypes)
+ }
+
+ fun relationshipTypes(relationshipTypes: MutableMap<String, RelationshipType>) {
+ if (this.relationshipTypes == null)
+ this.relationshipTypes = hashMapOf()
+
+ this.relationshipTypes!!.putAll(relationshipTypes)
+ }
+
+ fun policyTypes(policyTypes: MutableMap<String, PolicyType>) {
+ if (this.policyTypes == null)
+ this.policyTypes = hashMapOf()
+
+ this.policyTypes!!.putAll(policyTypes)
+ }
+
+ fun nodeType(nodeTypes: MutableMap<String, NodeType>) {
+ if (this.nodeTypes == null)
+ this.nodeTypes = hashMapOf()
+
+ this.nodeTypes!!.putAll(nodeTypes)
+ }
+
+ fun dataType(dataType: DataType) {
+ if (dataTypes == null)
+ dataTypes = hashMapOf()
+ dataTypes!![dataType.id!!] = dataType
+ }
+
+ fun artifactType(artifactType: ArtifactType) {
+ if (artifactTypes == null)
+ artifactTypes = hashMapOf()
+ artifactTypes!![artifactType.id!!] = artifactType
+ }
+
+ fun relationshipType(relationshipType: RelationshipType) {
+ if (relationshipTypes == null)
+ relationshipTypes = hashMapOf()
+ relationshipTypes!![relationshipType.id!!] = relationshipType
+ }
+
+ fun policyType(policyType: PolicyType) {
+ if (policyTypes == null)
+ policyTypes = hashMapOf()
+
+ policyTypes!![policyType.id!!] = policyType
+ }
+
+ fun nodeType(nodeType: NodeType) {
+ if (nodeTypes == null)
+ nodeTypes = hashMapOf()
+ nodeTypes!![nodeType.id!!] = nodeType
+ }
+
+ fun dataType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: DataTypeBuilder.() -> Unit
+ ) {
+ if (dataTypes == null)
+ dataTypes = hashMapOf()
+ dataTypes!![id] = DataTypeBuilder(id, version, derivedFrom, description).apply(block).build()
+ }
+
+ fun artifactType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: ArtifactTypeBuilder.() -> Unit
+ ) {
+ if (artifactTypes == null)
+ artifactTypes = hashMapOf()
+ artifactTypes!![id] = ArtifactTypeBuilder(id, version, derivedFrom, description).apply(block).build()
+ }
+
+ fun relationshipType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: RelationshipTypeBuilder.() -> Unit
+ ) {
+ if (relationshipTypes == null)
+ relationshipTypes = hashMapOf()
+ relationshipTypes!![id] = RelationshipTypeBuilder(id, version, derivedFrom, description).apply(block).build()
+ }
+
+ fun policyType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: PolicyTypeBuilder.() -> Unit
+ ) {
+ if (policyTypes == null)
+ policyTypes = hashMapOf()
+ policyTypes!![id] = PolicyTypeBuilder(id, version, derivedFrom, description).apply(block).build()
+ }
+
+ fun nodeType(
+ id: String,
+ version: String,
+ derivedFrom: String,
+ description: String,
+ block: NodeTypeBuilder.() -> Unit
+ ) {
+ if (nodeTypes == null)
+ nodeTypes = hashMapOf()
+ nodeTypes!![id] = NodeTypeBuilder(id, version, derivedFrom, description).apply(block).build()
+ }
+
+ fun topologyTemplate(block: TopologyTemplateBuilder.() -> Unit) {
+ topologyTemplate = TopologyTemplateBuilder().apply(block).build()
+ }
+
+ fun build(): ServiceTemplate {
+ initMetaData()
+ serviceTemplate.metadata = metadata
+ serviceTemplate.imports = imports
+ serviceTemplate.dslDefinitions = dslDefinitions
+ serviceTemplate.nodeTypes = nodeTypes
+ serviceTemplate.artifactTypes = artifactTypes
+ serviceTemplate.dataTypes = dataTypes
+ serviceTemplate.relationshipTypes = relationshipTypes
+ serviceTemplate.policyTypes = policyTypes
+ serviceTemplate.topologyTemplate = topologyTemplate
+ return serviceTemplate
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt
new file mode 100644
index 000000000..d07fc9c71
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintServiceTemplateGenerator.kt
@@ -0,0 +1,211 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.dsl
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.node.NullNode
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.bpClone
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.InterfaceDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
+
+/**
+ * Generate Service Template for the simplified DSL.
+ * @author Brinda Santh
+ */
+class BluePrintServiceTemplateGenerator(private val dslBluePrint: DSLBluePrint) {
+
+ private var serviceTemplate = ServiceTemplate()
+
+ private val nodeTypes: MutableMap<String, NodeType> = hashMapOf()
+ private val artifactTypes: MutableMap<String, ArtifactType> = hashMapOf()
+ private val dataTypes: MutableMap<String, DataType> = 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<String, NodeTemplate> {
+
+ val nodeTemplates: MutableMap<String, NodeTemplate> = 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<String, Workflow>? {
+ var workflows: MutableMap<String, Workflow>? = 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<String, InterfaceDefinition> {
+
+ // 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<String, OperationDefinition> = hashMapOf()
+ operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationDefinition
+
+ val interfaceDefinition = InterfaceDefinition()
+ interfaceDefinition.operations = operations
+
+ val interfaces: MutableMap<String, InterfaceDefinition> = hashMapOf()
+ interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceDefinition
+ return interfaces
+ }
+
+ private fun populateInterfaceAssignments(dslComponent: DSLRegistryComponent): MutableMap<String, InterfaceAssignment> {
+ val operationAssignment = OperationAssignment()
+ operationAssignment.implementation = dslComponent.implementation
+ operationAssignment.inputs = dslComponent.inputs
+ operationAssignment.outputs = dslComponent.outputs
+
+ val operations: MutableMap<String, OperationAssignment> = hashMapOf()
+ operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment
+
+ val interfaceAssignment = InterfaceAssignment()
+ interfaceAssignment.operations = operations
+
+ val interfaces: MutableMap<String, InterfaceAssignment> = hashMapOf()
+ interfaces[dslComponent.interfaceName] = interfaceAssignment
+ return interfaces
+ }
+
+ private fun populateInterfaceAssignments(dslComponent: DSLComponent): MutableMap<String, InterfaceAssignment> {
+ val operationAssignment = OperationAssignment()
+ operationAssignment.implementation = dslComponent.implementation
+ operationAssignment.inputs = propertyAssignments(dslComponent.inputs)
+ operationAssignment.outputs = propertyAssignments(dslComponent.outputs)
+
+ val operations: MutableMap<String, OperationAssignment> = hashMapOf()
+ operations[BluePrintConstants.DEFAULT_STEP_OPERATION] = operationAssignment
+
+ val interfaceAssignment = InterfaceAssignment()
+ interfaceAssignment.operations = operations
+
+ val interfaces: MutableMap<String, InterfaceAssignment> = hashMapOf()
+ interfaces[BluePrintConstants.DEFAULT_STEP_INTERFACE] = interfaceAssignment
+ return interfaces
+ }
+
+ private fun propertyDefinitions(propertyDefinitions: Map<String, PropertyDefinition>?): MutableMap<String, PropertyDefinition>? {
+ val definitions: MutableMap<String, PropertyDefinition>? = propertyDefinitions?.bpClone()?.toMutableMap()
+
+ definitions?.forEach { (_, prop) ->
+ prop.value = null
+ }
+ return definitions
+ }
+
+ private fun attributeDefinitions(attributeDefinitions: Map<String, AttributeDefinition>?): MutableMap<String, AttributeDefinition>? {
+ val definitions: MutableMap<String, AttributeDefinition>? = attributeDefinitions?.bpClone()?.toMutableMap()
+
+ definitions?.forEach { (_, prop) ->
+ prop.value = null
+ }
+ return definitions
+ }
+
+ private fun propertyAssignments(propertyDefinitions: Map<String, PropertyDefinition>?): MutableMap<String, JsonNode>? {
+ var assignments: MutableMap<String, JsonNode>? = 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..df4d2d849
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTemplateDSLBuilder.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.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.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.full.createInstance
+import kotlin.reflect.jvm.reflect
+
+class TopologyTemplateBuilder {
+ private var topologyTemplate = TopologyTemplate()
+ private var nodeTemplates: MutableMap<String, NodeTemplate>? = null
+ private var workflows: MutableMap<String, Workflow>? = 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 nodeTemplateOperation(
+ nodeTemplateName: String,
+ type: String,
+ interfaceName: String,
+ description: String,
+ operationBlock: OperationAssignmentBuilder<PropertiesAssignmentBuilder,
+ PropertiesAssignmentBuilder>.() -> 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.workflows = workflows
+ return topologyTemplate
+ }
+}
+
+open class NodeTemplateBuilder(
+ private val id: String,
+ private val type: String,
+ private val description: String? = ""
+) {
+
+ private var nodeTemplate: NodeTemplate = NodeTemplate()
+ private var properties: MutableMap<String, JsonNode>? = null
+ private var interfaces: MutableMap<String, InterfaceAssignment>? = null
+ private var artifacts: MutableMap<String, ArtifactDefinition>? = null
+ private var capabilities: MutableMap<String, CapabilityAssignment>? = null
+ private var requirements: MutableMap<String, RequirementAssignment>? = null
+
+ fun properties(properties: MutableMap<String, JsonNode>?) {
+ this.properties = properties
+ }
+
+ fun properties(block: PropertiesAssignmentBuilder.() -> Unit) {
+ if (properties == null)
+ properties = hashMapOf()
+ properties = PropertiesAssignmentBuilder().apply(block).build()
+ }
+
+ open fun <Prop : PropertiesAssignmentBuilder> typedProperties(block: Prop.() -> Unit) {
+ if (properties == null)
+ properties = hashMapOf()
+ val instance: Prop = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<Prop>).createInstance()
+ properties = instance.apply(block).build()
+ }
+
+ open fun <In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder> typedOperation(
+ interfaceName: String,
+ description: String = "",
+ block: OperationAssignmentBuilder<In, Out>.() -> Unit
+ ) {
+ if (interfaces == null)
+ interfaces = hashMapOf()
+
+ val interfaceAssignment = InterfaceAssignment()
+ val defaultOperationName = BluePrintConstants.DEFAULT_STEP_OPERATION
+ interfaceAssignment.operations = hashMapOf()
+ interfaceAssignment.operations!![defaultOperationName] =
+ OperationAssignmentBuilder<In, Out>(defaultOperationName, description).apply(block).build()
+ interfaces!![interfaceName] = interfaceAssignment
+ }
+
+ fun operation(
+ interfaceName: String,
+ description: String,
+ block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit
+ ) {
+ typedOperation<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>(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<String, ArtifactDefinition>?) {
+ 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<String, CapabilityAssignment>?) {
+ this.capabilities = 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<String, RequirementAssignment>?) {
+ this.requirements = requirements
+ }
+
+ 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
+ }
+}
+
+class ArtifactDefinitionBuilder(private val id: String, private val type: String, private val file: String) {
+
+ private var artifactDefinition: ArtifactDefinition = ArtifactDefinition()
+ private var properties: MutableMap<String, JsonNode>? = 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<String, JsonNode>? = null
+ var properties: MutableMap<String, JsonNode>? = 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 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<String, OperationAssignment>? = null
+
+ fun operation(
+ id: String,
+ description: String? = "",
+ block: OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>.() -> Unit
+ ) {
+ if (operations == null)
+ operations = hashMapOf()
+ operations!![id] = OperationAssignmentBuilder<PropertiesAssignmentBuilder, PropertiesAssignmentBuilder>(
+ id, description
+ ).apply(block).build()
+ }
+
+ fun build(): InterfaceAssignment {
+ interfaceAssignment.id = id
+ interfaceAssignment.operations = operations
+ return interfaceAssignment
+ }
+}
+
+class OperationAssignmentBuilder<In : PropertiesAssignmentBuilder, Out : PropertiesAssignmentBuilder>(
+ 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<String, JsonNode>?) {
+ operationAssignment.inputs = inputs
+ }
+
+ fun inputs(block: In.() -> Unit) {
+ val instance: In = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<In>).createInstance()
+ operationAssignment.inputs = instance.apply(block).build()
+ }
+
+ fun outputs(outputs: MutableMap<String, JsonNode>?) {
+ operationAssignment.outputs = outputs
+ }
+
+ fun outputs(block: Out.() -> Unit) {
+ val instance: Out = (block.reflect()?.parameters?.get(0)?.type?.classifier as KClass<Out>).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<String, JsonNode> = hashMapOf()
+
+ fun property(id: String, value: Any) {
+ property(id, value.asJsonType())
+ }
+
+ fun property(id: String, value: JsonNode) {
+ properties[id] = value
+ }
+
+ open fun build(): MutableMap<String, JsonNode> {
+ return properties
+ }
+}
+
+open class AttributesAssignmentBuilder {
+ var attributes: MutableMap<String, JsonNode> = hashMapOf()
+
+ fun attribute(id: String, value: String) {
+ attribute(id, value.asJsonType())
+ }
+
+ fun attribute(id: String, value: JsonNode) {
+ attributes[id] = value
+ }
+
+ fun build(): MutableMap<String, JsonNode> {
+ 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..e183b8090
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintTypeDSLBuilder.kt
@@ -0,0 +1,581 @@
+/*
+ * 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<String, String>? = null
+ var properties: MutableMap<String, PropertyDefinition>? = null
+ var attributes: MutableMap<String, AttributeDefinition>? = 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<String, CapabilityDefinition>? = null
+ private var requirements: MutableMap<String, RequirementDefinition>? = null
+ private var interfaces: MutableMap<String, InterfaceDefinition>? = null
+ private var artifacts: MutableMap<String, ArtifactDefinition>? = 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<String>? = 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<String>) {
+ 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<String>) {
+ 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<String, PropertyDefinition> = 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<String, OperationDefinition>? = 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<String, PropertyDefinition> = 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<String, PropertyDefinition> {
+ 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<ConstraintClause> = mutableListOf()
+
+ fun constrain(block: ConstraintClauseBuilder.() -> Unit) {
+ val constraintClause = ConstraintClauseBuilder().apply(block).build()
+ constraints.add(constraintClause)
+ }
+
+ fun build(): MutableList<ConstraintClause> {
+ 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<JsonNode>) {
+ constraintClause.validValues = validValues.toMutableList()
+ }
+
+ fun length(length: Any) {
+ constraintClause.length = length.asJsonPrimitive()
+ }
+
+ fun minLength(minLength: Any) {
+ constraintClause.minLength = minLength.asJsonPrimitive()
+ }
+
+ fun maxLength(maxLength: Any) {
+ constraintClause.maxLength = maxLength.asJsonPrimitive()
+ }
+
+ fun pattern(pattern: String) {
+ constraintClause.pattern = pattern
+ }
+
+ fun schema(schema: String) {
+ constraintClause.schema = schema
+ }
+
+ fun build(): ConstraintClause {
+ return constraintClause
+ }
+}
+
+class EntrySchemaBuilder(private val type: String) {
+ private var entrySchema: EntrySchema = EntrySchema()
+
+ fun constrain(block: ConstraintClauseBuilder.() -> Unit) {
+ if (entrySchema.constraints == null) {
+ entrySchema.constraints = mutableListOf()
+ }
+ val constraintClause = ConstraintClauseBuilder().apply(block).build()
+ entrySchema.constraints!!.add(constraintClause)
+ }
+
+ fun build(): EntrySchema {
+ entrySchema.type = type
+ return entrySchema
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt
new file mode 100644
index 000000000..8a1a9d63c
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintWorkflowDSLBuilder.kt
@@ -0,0 +1,121 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.dsl
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Activity
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Step
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
+import kotlin.reflect.KClass
+
+class WorkflowBuilder(private val id: String, private val description: String) {
+
+ private var workflow = Workflow()
+ private var steps: MutableMap<String, Step>? = null
+ private var inputs: MutableMap<String, PropertyDefinition>? = null
+ private var outputs: MutableMap<String, PropertyDefinition>? = 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<Activity> = arrayListOf()
+ private var onSuccess: ArrayList<String>? = null
+ private var onFailure: ArrayList<String>? = 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/interfaces/BluePrintCatalogService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt
new file mode 100755
index 000000000..bd45bed06
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintCatalogService.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import java.io.File
+import java.nio.file.Path
+
+interface BluePrintCatalogService {
+
+ /**
+ * Save the CBA to database.
+ * @param processingId Processing Id
+ * @param blueprintFile Either a directory, or an archive
+ * @param validate whether to validate blueprint content. Default true.
+ * @return The unique blueprint identifier
+ * @throws BluePrintException if process failed
+ */
+ @Throws(BluePrintException::class)
+ suspend fun saveToDatabase(processingId: String, blueprintFile: File, validate: Boolean = true): String
+
+ /**
+ * Retrieve the CBA from database either archived or extracted.
+ * @param name Name of the blueprint
+ * @param version Version of the blueprint
+ * @param extract true to extract the content, false for archived content. Default to true
+ * @return Path where CBA is located
+ * @throws BluePrintException if process failed
+ */
+
+ @Throws(BluePrintException::class)
+ suspend fun getFromDatabase(name: String, version: String, extract: Boolean = true): Path
+
+ /**
+ * Delete the CBA from database.
+ * @param name Name of the blueprint
+ * @param version Version of the blueprint
+ * @throws BluePrintException if process failed
+ */
+
+ @Throws(BluePrintException::class)
+ suspend fun deleteFromDatabase(name: String, version: String)
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt
new file mode 100644
index 000000000..fcc9bf2d7
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintDefinitions.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
+
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+
+interface BluePrintDefinitions {
+
+ /** Define the service Template Model */
+ fun serviceTemplate(): ServiceTemplate
+
+ /** Load Custom Definitions that may used during runtime **/
+ fun loadOtherDefinitions()
+
+ /** Utility Method to add the definition */
+ fun addOtherDefinition(key: String, definition: Any)
+
+ /** Utility method to get the definition */
+ fun <T : Any> otherDefinition(key: String): T
+
+ fun otherDefinitions(): MutableMap<String, Any>
+}
+
+abstract class AbstractBluePrintDefinitions : BluePrintDefinitions {
+
+ private val otherDefinitionMap: MutableMap<String, Any> = hashMapOf()
+
+ constructor() {
+ loadOtherDefinitions()
+ }
+
+ override fun loadOtherDefinitions() {
+ }
+
+ override fun <T : Any> otherDefinition(key: String): T {
+ return otherDefinitionMap[key] as T
+ }
+
+ override fun addOtherDefinition(key: String, definition: Any) {
+ otherDefinitionMap[key] = definition
+ }
+
+ override fun otherDefinitions(): MutableMap<String, Any> {
+ 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..80c91ca28
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintEnhancer.kt
@@ -0,0 +1,154 @@
+/*
+ * 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.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<T> {
+ fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T)
+}
+
+interface BluePrintServiceTemplateEnhancer : BluePrintEnhancer<ServiceTemplate>
+
+interface BluePrintTopologyTemplateEnhancer : BluePrintEnhancer<TopologyTemplate>
+
+interface BluePrintWorkflowEnhancer : BluePrintEnhancer<Workflow>
+
+interface BluePrintNodeTemplateEnhancer : BluePrintEnhancer<NodeTemplate>
+
+interface BluePrintNodeTypeEnhancer : BluePrintEnhancer<NodeType>
+
+interface BluePrintArtifactDefinitionEnhancer : BluePrintEnhancer<ArtifactDefinition>
+
+interface BluePrintPolicyTypeEnhancer : BluePrintEnhancer<PolicyType>
+
+interface BluePrintPropertyDefinitionEnhancer : BluePrintEnhancer<PropertyDefinition>
+
+interface BluePrintAttributeDefinitionEnhancer : BluePrintEnhancer<AttributeDefinition>
+
+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<BluePrintServiceTemplateEnhancer>
+
+ fun getTopologyTemplateEnhancers(): List<BluePrintTopologyTemplateEnhancer>
+
+ fun getWorkflowEnhancers(): List<BluePrintWorkflowEnhancer>
+
+ fun getNodeTemplateEnhancers(): List<BluePrintNodeTemplateEnhancer>
+
+ fun getNodeTypeEnhancers(): List<BluePrintNodeTypeEnhancer>
+
+ fun getArtifactDefinitionEnhancers(): List<BluePrintArtifactDefinitionEnhancer>
+
+ fun getPolicyTypeEnhancers(): List<BluePrintPolicyTypeEnhancer>
+
+ fun getPropertyDefinitionEnhancers(): List<BluePrintPropertyDefinitionEnhancer>
+
+ fun getAttributeDefinitionEnhancers(): List<BluePrintAttributeDefinitionEnhancer>
+
+ 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 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<String, PropertyDefinition>) {
+ properties.forEach { propertyName, propertyDefinition ->
+ enhancePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition)
+ }
+ }
+
+ fun enhancePropertyDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) {
+ val enhancers = getPropertyDefinitionEnhancers()
+ doEnhancement(bluePrintRuntimeService, name, propertyDefinition, enhancers)
+ }
+
+ fun enhanceAttributeDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, attributes: MutableMap<String, AttributeDefinition>) {
+ attributes.forEach { attributeName, attributeDefinition ->
+ enhanceAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition)
+ }
+ }
+
+ fun enhanceAttributeDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) {
+ val enhancers = getAttributeDefinitionEnhancers()
+ doEnhancement(bluePrintRuntimeService, name, attributeDefinition, enhancers)
+ }
+
+ @Suppress("UNCHECKED_CAST")
+ private fun <T> doEnhancement(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ definition: Any,
+ enhancers: List<BluePrintEnhancer<T>>
+ ) {
+ if (enhancers.isNotEmpty()) {
+ enhancers.forEach {
+ it.enhance(bluePrintRuntimeService, name, definition as T)
+ }
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt
new file mode 100644
index 000000000..8d04e5489
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintRepoService.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import java.io.Serializable
+
+/**
+ * BluePrintRepoFileService
+ * @author Brinda Santh
+ *
+ */
+
+interface BluePrintRepoService : Serializable {
+
+ @Throws(BluePrintException::class)
+ fun getNodeType(nodeTypeName: String): NodeType
+
+ @Throws(BluePrintException::class)
+ fun getDataType(dataTypeName: String): DataType
+
+ @Throws(BluePrintException::class)
+ fun getArtifactType(artifactTypeName: String): ArtifactType
+
+ @Throws(BluePrintException::class)
+ fun getRelationshipType(relationshipTypeName: String): RelationshipType
+
+ @Throws(BluePrintException::class)
+ fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt
new file mode 100644
index 000000000..aa61b0c4d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintScriptsService.kt
@@ -0,0 +1,39 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
+
+import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintSourceCode
+
+interface BluePrintScriptsService {
+
+ suspend fun <T> scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T
+
+ suspend fun <T> scriptInstance(
+ blueprintBasePath: String,
+ artifactName: String,
+ artifactVersion: String,
+ scriptClassName: String,
+ reCompile: Boolean
+ ): T
+
+ suspend fun <T> scriptInstance(blueprintBasePath: String, scriptClassName: String, reCompile: Boolean): T
+
+ suspend fun <T> scriptInstance(cacheKey: String, scriptClassName: String): T
+
+ suspend fun <T> scriptInstance(scriptClassName: String): T
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt
new file mode 100644
index 000000000..70c797326
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BluePrintWorkflowExecutionService.kt
@@ -0,0 +1,28 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.interfaces
+
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+
+interface BluePrintWorkflowExecutionService<Input, Output> {
+
+ suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: Input,
+ properties: MutableMap<String, Any> = hashMapOf()
+ ): Output
+}
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
new file mode 100644
index 000000000..b56fac541
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintFunctionNode.kt
@@ -0,0 +1,72 @@
+/*
+ * 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 kotlinx.coroutines.runBlocking
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import java.util.function.Function
+
+interface BlueprintFunctionNode<T, R> : Function<T, R> {
+
+ fun getName(): String
+
+ @Throws(BluePrintProcessorException::class)
+ fun prepareRequest(executionRequest: T): T = runBlocking {
+ prepareRequestNB(executionRequest)
+ }
+
+ @Throws(BluePrintProcessorException::class)
+ fun process(executionRequest: T) = runBlocking {
+ processNB(executionRequest)
+ }
+
+ @Throws(BluePrintProcessorException::class)
+ fun recover(runtimeException: RuntimeException, executionRequest: T) = runBlocking {
+ recoverNB(runtimeException, executionRequest)
+ }
+
+ @Throws(BluePrintProcessorException::class)
+ fun prepareResponse(): R = runBlocking {
+ prepareResponseNB()
+ }
+
+ override fun apply(executionServiceInput: T): R {
+ try {
+ prepareRequest(executionServiceInput)
+ process(executionServiceInput)
+ } catch (runtimeException: RuntimeException) {
+ recover(runtimeException, executionServiceInput)
+ }
+ return prepareResponse()
+ }
+
+ @Throws(BluePrintProcessorException::class)
+ suspend fun prepareRequestNB(executionRequest: T): T
+
+ @Throws(BluePrintProcessorException::class)
+ suspend fun processNB(executionRequest: T)
+
+ @Throws(BluePrintProcessorException::class)
+ suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: T)
+
+ @Throws(BluePrintProcessorException::class)
+ suspend fun prepareResponseNB(): R
+
+ @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/BlueprintTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintTemplateService.kt
new file mode 100644
index 000000000..6f6979772
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/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.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
+
+interface BlueprintTemplateService {
+
+ /**
+ * Generate dynamique content using Velocity Template or Jinja template
+ *
+ * @param bluePrintRuntimeService blueprint runtime
+ * @param nodeTemplateName node template
+ * @param artifactName Artifact Name
+ * @param jsonData json string data content to mash
+ * @param ignoreJsonNull Ignore Null value in the JSON content
+ * @param additionalContext (Key, value) mutable map for additional variables
+ * @return Content result
+ *
+ **/
+ suspend fun generateContent(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ artifactName: String,
+ jsonData: String = "",
+ ignoreJsonNull: Boolean = false,
+ additionalContext: MutableMap<String, Any> = mutableMapOf()
+ ): String
+}
+
+/**
+ * Customise JsonNodeFactory and TextNode, Since it introduces quotes for string data.
+ */
+open class BluePrintJsonNodeFactory : JsonNodeFactory() {
+
+ override fun textNode(text: String): TextNode {
+ return BluePrintTextNode(text)
+ }
+}
+
+open class BluePrintTextNode(v: String) : TextNode(v) {
+ override fun toString(): String {
+ var len = this._value.length
+ len = len + 2 + (len shr 4)
+ val sb = StringBuilder(len)
+ CharTypes.appendQuoted(sb, this._value)
+ return sb.toString()
+ }
+}
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
new file mode 100644
index 000000000..c6339f449
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/interfaces/BlueprintValidator.kt
@@ -0,0 +1,175 @@
+/*
+ * 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.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.NodeTemplate
+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.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
+
+interface BluePrintValidator<T> {
+
+ fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: T)
+}
+
+interface BluePrintServiceTemplateValidator : BluePrintValidator<ServiceTemplate>
+
+interface BluePrintTopologyTemplateValidator : BluePrintValidator<TopologyTemplate>
+
+interface BluePrintArtifactTypeValidator : BluePrintValidator<ArtifactType>
+
+interface BluePrintArtifactDefinitionValidator : BluePrintValidator<ArtifactDefinition>
+
+interface BluePrintDataTypeValidator : BluePrintValidator<DataType>
+
+interface BluePrintNodeTypeValidator : BluePrintValidator<NodeType>
+
+interface BluePrintNodeTemplateValidator : BluePrintValidator<NodeTemplate>
+
+interface BluePrintWorkflowValidator : BluePrintValidator<Workflow>
+
+interface BluePrintPropertyDefinitionValidator : BluePrintValidator<PropertyDefinition>
+
+interface BluePrintAttributeDefinitionValidator : BluePrintValidator<AttributeDefinition>
+
+/**
+ * Blueprint Validation Interface.
+ */
+interface BluePrintValidatorService {
+
+ @Throws(BluePrintException::class)
+ fun validateBluePrints(basePath: String): Boolean
+
+ @Throws(BluePrintException::class)
+ fun validateBluePrints(bluePrintRuntimeService: BluePrintRuntimeService<*>): Boolean
+}
+
+interface BluePrintTypeValidatorService {
+
+ fun <T : BluePrintValidator<*>> bluePrintValidator(referenceName: String, classType: Class<T>): T?
+
+ fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>?
+
+ fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>?
+
+ fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator>
+
+ fun getDataTypeValidators(): List<BluePrintDataTypeValidator>
+
+ fun getArtifactTypeValidators(): List<BluePrintArtifactTypeValidator>
+
+ fun getArtifactDefinitionsValidators(): List<BluePrintArtifactDefinitionValidator>
+
+ fun getNodeTypeValidators(): List<BluePrintNodeTypeValidator>
+
+ fun getTopologyTemplateValidators(): List<BluePrintTopologyTemplateValidator>
+
+ fun getNodeTemplateValidators(): List<BluePrintNodeTemplateValidator>
+
+ fun getWorkflowValidators(): List<BluePrintWorkflowValidator>
+
+ fun getPropertyDefinitionValidators(): List<BluePrintPropertyDefinitionValidator>
+
+ fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator>
+
+ fun validateServiceTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, serviceTemplate: ServiceTemplate) {
+ val validators = getServiceTemplateValidators()
+ doValidation(bluePrintRuntimeService, name, serviceTemplate, validators)
+ }
+
+ fun validateArtifactType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) {
+ val validators = getArtifactTypeValidators()
+ doValidation(bluePrintRuntimeService, name, artifactType, validators)
+ }
+
+ fun validateArtifactDefinition(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
+ val validators = getArtifactDefinitionsValidators()
+ doValidation(bluePrintRuntimeService, name, artifactDefinition, validators)
+ }
+
+ fun validateDataType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, dataType: DataType) {
+ val validators = getDataTypeValidators()
+ doValidation(bluePrintRuntimeService, name, dataType, validators)
+ }
+
+ fun validateNodeType(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) {
+ val validators = getNodeTypeValidators()
+ doValidation(bluePrintRuntimeService, name, nodeType, validators)
+ }
+
+ fun validateTopologyTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) {
+ val validators = getTopologyTemplateValidators()
+ doValidation(bluePrintRuntimeService, name, topologyTemplate, validators)
+ }
+
+ fun validateNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) {
+ val validators = getNodeTemplateValidators()
+ doValidation(bluePrintRuntimeService, name, nodeTemplate, validators)
+ }
+
+ fun validateWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, workflow: Workflow) {
+ val validators = getWorkflowValidators()
+ doValidation(bluePrintRuntimeService, name, workflow, validators)
+ }
+
+ fun validatePropertyDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, properties: MutableMap<String, PropertyDefinition>) {
+ properties.forEach { propertyName, propertyDefinition ->
+ validatePropertyDefinition(bluePrintRuntimeService, propertyName, propertyDefinition)
+ }
+ }
+
+ fun validatePropertyDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) {
+ val validators = getPropertyDefinitionValidators()
+ doValidation(bluePrintRuntimeService, name, propertyDefinition, validators)
+ }
+
+ fun validateAttributeDefinitions(bluePrintRuntimeService: BluePrintRuntimeService<*>, attributes: MutableMap<String, AttributeDefinition>) {
+ attributes.forEach { attributeName, attributeDefinition ->
+ validateAttributeDefinition(bluePrintRuntimeService, attributeName, attributeDefinition)
+ }
+ }
+
+ fun validateAttributeDefinition(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, attributeDefinition: AttributeDefinition) {
+ val validators = getAttributeDefinitionValidators()
+ doValidation(bluePrintRuntimeService, name, attributeDefinition, validators)
+ }
+
+ @Suppress("UNCHECKED_CAST")
+ private fun <T> doValidation(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ definition: Any,
+ validators: List<BluePrintValidator<T>>
+ ) {
+ 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/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..b2857c6ce
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompileService.kt
@@ -0,0 +1,178 @@
+/*
+ * 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.async
+import kotlinx.coroutines.coroutineScope
+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
+ }
+ }
+
+ /** Compile the [bluePrintSourceCode] and get the [kClassName] instance for the constructor [args] */
+ suspend fun <T> eval(
+ bluePrintSourceCode: BluePrintSourceCode,
+ kClassName: String,
+ args: ArrayList<Any?>?
+ ): T {
+ /** Compile the source code */
+ compile(bluePrintSourceCode)
+ /** Get the class loader with compiled jar */
+ 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
+
+ /** Check cache is present for the blueprint scripts */
+ val hasCompiledCache = BluePrintCompileCache.hasClassLoader(bluePrintSourceCode.cacheKey)
+
+ log.debug(
+ "Jar Exists : ${compiledJarFile.exists()}, Regenerate : ${bluePrintSourceCode.regenerate}," +
+ " Compiled hash(${bluePrintSourceCode.cacheKey}) : $hasCompiledCache"
+ )
+
+ if (!compiledJarFile.exists() || bluePrintSourceCode.regenerate || !hasCompiledCache) {
+ log.info("compiling for cache key(${bluePrintSourceCode.cacheKey})")
+ coroutineScope {
+ val timeTaken = measureTimeMillis {
+ /** Create compile arguments */
+ val args = mutableListOf<String>().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 <T> instance(classLoader: URLClassLoader, kClassName: String, args: ArrayList<Any?>? = 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<String>
+ 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<CompiledMessageData> = 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<CompiledMessageData> = 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..fbfcfb94f
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintCompilerCache.kt
@@ -0,0 +1,76 @@
+/*
+ * 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.normalizedFile
+import java.net.URL
+import java.net.URLClassLoader
+
+object BluePrintCompileCache {
+ val log = logger(BluePrintCompileCache::class)
+
+ private val classLoaderCache: LoadingCache<String, URLClassLoader> = 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<String, URLClassLoader>() {
+
+ val log = logger(BluePrintClassLoader::class)
+
+ override fun load(key: String): URLClassLoader {
+ log.info("loading compiled cache($key)")
+ val keyPath = normalizedFile(key)
+ if (!keyPath.exists()) {
+ throw BluePrintException("failed to load cache($key), missing files.")
+ }
+ val urls = arrayListOf<URL>()
+ keyPath.walkTopDown()
+ .filter { it.name.endsWith("cba-kts.jar") }
+ .forEach {
+ log.debug("Adding (${it.absolutePath}) to cache($key)")
+ urls.add(it.toURI().toURL())
+ }
+ return URLClassLoader(urls.toTypedArray(), this.javaClass.classLoader)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt
new file mode 100644
index 000000000..f3eb1a2b9
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImpl.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.scripts
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintScriptsService
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
+import java.util.ArrayList
+
+open class BluePrintScriptsServiceImpl : BluePrintScriptsService {
+
+ val log = logger(BluePrintScriptsServiceImpl::class)
+
+ override suspend fun <T> scriptInstance(bluePrintSourceCode: BluePrintSourceCode, scriptClassName: String): T {
+ val bluePrintCompileService = BluePrintCompileService()
+ return bluePrintCompileService.eval(bluePrintSourceCode, scriptClassName, null)
+ }
+
+ override suspend fun <T> scriptInstance(
+ blueprintBasePath: String,
+ artifactName: String,
+ artifactVersion: String,
+ scriptClassName: String,
+ reCompile: Boolean
+ ): T {
+
+ val sources: MutableList<String> = 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 <T> 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 <T> scriptInstance(cacheKey: String, scriptClassName: String): T {
+ val args = ArrayList<Any?>()
+ return BluePrintCompileCache.classLoader(cacheKey).loadClass(scriptClassName).constructors
+ .single().newInstance(*args.toArray()) as T
+ }
+
+ override suspend fun <T> scriptInstance(scriptClassName: String): T {
+ val args = ArrayList<Any?>()
+ return Thread.currentThread().contextClassLoader.loadClass(scriptClassName).constructors
+ .single().newInstance(*args.toArray()) as T
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintChainedService.kt
new file mode 100644
index 000000000..7d85963dc
--- /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
+ */
+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<String, AttributeDefinition>()
+ val properties = hashMapOf<String, PropertyDefinition>()
+ val requirements = hashMapOf<String, RequirementDefinition>()
+ val capabilities = hashMapOf<String, CapabilityDefinition>()
+ val interfaces = hashMapOf<String, InterfaceDefinition>()
+ val artifacts = hashMapOf<String, ArtifactDefinition>()
+
+ 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<String, PropertyDefinition>? {
+ val nodeType = bpc.nodeTypeByName(nodeTypeName)
+ val properties = hashMapOf<String, PropertyDefinition>()
+
+ 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<NodeType>? = arrayListOf()): MutableList<NodeType> {
+ 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<DataType>? = arrayListOf()): MutableList<DataType> {
+ 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..47cd62ea1
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContext.kt
@@ -0,0 +1,296 @@
+/*
+ * 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.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<String, Any> = hashMapOf()
+
+ fun <T> otherDefinition(key: String) = otherDefinitions[key] as T
+
+ fun checkOtherDefinition(key: String) = otherDefinitions.containsKey(key)
+
+ fun imports(): List<ImportDefinition>? = serviceTemplate.imports
+
+ fun dslDefinitions() = serviceTemplate.dslDefinitions
+
+ val metadata: MutableMap<String, String>? = serviceTemplate.metadata
+
+ fun dataTypes(): MutableMap<String, DataType>? = serviceTemplate.dataTypes
+
+ fun inputs(): MutableMap<String, PropertyDefinition>? = 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<String, Workflow>? = 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<String, ArtifactType>? = serviceTemplate.artifactTypes
+
+ // Policy Types
+ fun policyTypes(): MutableMap<String, PolicyType>? = 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<String, PolicyType>? {
+ return policyTypes()?.filterValues { policyType -> policyType.derivedFrom == name }?.toMutableMap()
+ }
+
+ fun policyTypesTarget(target: String): MutableMap<String, PolicyType>? {
+ return policyTypes()?.filterValues { it.targets.contains(target) }?.toMutableMap()
+ }
+
+ fun policyTypesTargetNDerivedFrom(target: String, derivedFrom: String): MutableMap<String, PolicyType>? {
+ return policyTypesDerivedFrom(derivedFrom)?.filterValues {
+ it.targets.contains(target)
+ }?.toMutableMap()
+ }
+
+ // Node Type Methods
+ fun nodeTypes(): MutableMap<String, NodeType>? = 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<String, NodeType>? {
+ 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<String, PropertyDefinition>? {
+ return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).inputs
+ }
+
+ fun nodeTypeInterfaceOperationOutputs(
+ nodeTypeName: String,
+ interfaceName: String,
+ operationName: String
+ ): MutableMap<String, PropertyDefinition>? {
+ return nodeTypeInterfaceOperation(nodeTypeName, interfaceName, operationName).outputs
+ }
+
+ // Node Template Methods
+ fun nodeTemplates(): MutableMap<String, NodeTemplate>? = 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<String, NodeTemplate>? {
+ 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<String, ArtifactDefinition>? {
+ return nodeTemplateByName(nodeTemplateName).artifacts
+ }
+
+ fun nodeTemplateArtifact(nodeTemplateName: String, artifactName: String): ArtifactDefinition {
+ return nodeTemplateArtifacts(nodeTemplateName)?.get(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<String, JsonNode>? {
+ return nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName).inputs
+ }
+
+ fun nodeTemplateInterfaceOperationOutputs(nodeTemplateName: String, interfaceName: String, operationName: String): MutableMap<String, JsonNode>? {
+ 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)
+ }
+
+ // Chained Functions
+
+ fun nodeTypeChained(nodeTypeName: String): NodeType {
+ return BluePrintChainedService(this).nodeTypeChained(nodeTypeName)
+ }
+
+ fun nodeTypeChainedProperties(nodeTypeName: String): MutableMap<String, PropertyDefinition>? {
+ 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..df3bde1b4
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintDependencyService.kt
@@ -0,0 +1,53 @@
+/*
+ * 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 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
+ }
+
+ inline fun <reified T> instance(name: String): T {
+ return applicationContext.getBean(name) as? T
+ ?: throw BluePrintProcessorException("failed to get instance($name)")
+ }
+
+ inline fun <reified T> instance(type: Class<T>): T {
+ return applicationContext.getBean(type)
+ ?: throw BluePrintProcessorException("failed to get instance($type)")
+ }
+
+ inline fun <reified T> 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..6a3c64650
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionService.kt
@@ -0,0 +1,230 @@
+/*
+ * 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<String> = 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 [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>, " +
+ "<nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ] , 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<String> = 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 [ <modelable_entity_name>, <optional_req_or_cap_name>, <attribute_name>," +
+ " <nested_attribute_name_or_index_1>, ..., <nested_attribute_name_or_index_n> ] , 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<String> = 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 (<modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>) , 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 [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ] , 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..24b7e261c
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintImportService.kt
@@ -0,0 +1,94 @@
+/*
+ * 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<String, ServiceTemplate> = 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<ImportDefinition>? = serviceTemplate.imports
+
+ imports?.let {
+ serviceTemplate.imports?.forEach { importDefinition ->
+ val childServiceTemplate = resolveImportDefinition(importDefinition)
+ val keyName: String = importDefinition.file
+ traverseSchema(keyName, childServiceTemplate)
+ }
+ }
+ }
+
+ private suspend fun resolveImportDefinition(importDefinition: ImportDefinition): ServiceTemplate {
+ var serviceTemplate: ServiceTemplate? = null
+ val file: String = importDefinition.file
+ val decodedSystemId: String = URLDecoder.decode(file, Charset.defaultCharset().toString())
+ log.trace("file ({}), decodedSystemId ({}) ", file, decodedSystemId)
+ try {
+ if (decodedSystemId.startsWith("http", true) ||
+ decodedSystemId.startsWith("https", true)
+ ) {
+ val givenUrl: String = URL(decodedSystemId).toString()
+ val systemUrl: String = File(".").toURI().toURL().toString()
+ log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl)
+ if (givenUrl.startsWith(systemUrl)) {
+ }
+ } else {
+ if (!decodedSystemId.startsWith("/")) {
+ importDefinition.file = StringBuilder().append(blueprintBasePath).append(File.separator).append(file).toString()
+ }
+ serviceTemplate = ServiceTemplateUtils.getServiceTemplate(importDefinition.file)
+ }
+ } catch (e: Exception) {
+ throw BluePrintException("failed to populate service template for ${importDefinition.file} original error: ${e.message}", e)
+ }
+ if (serviceTemplate == null) {
+ throw BluePrintException("failed to populate service template for : ${importDefinition.file}")
+ }
+ return serviceTemplate
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt
new file mode 100644
index 000000000..fdc348bf7
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintJinjaTemplateService.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright © 2019 IBM, Bell Canada.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.service
+
+import com.fasterxml.jackson.core.type.TypeReference
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.hubspot.jinjava.Jinjava
+import com.hubspot.jinjava.JinjavaConfig
+import com.hubspot.jinjava.interpret.JinjavaInterpreter
+import com.hubspot.jinjava.loader.ResourceLocator
+import com.hubspot.jinjava.loader.ResourceNotFoundException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode
+import java.io.IOException
+import java.nio.charset.Charset
+import java.nio.file.Files.readAllBytes
+import java.nio.file.Paths
+
+object BluePrintJinjaTemplateService {
+
+ /**
+ * To enable inheritance within CBA, we need Jinja runtime to know where to load the templates.
+ */
+ class BlueprintRelatedTemplateLocator(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val artifactName: String,
+ private val artifactVersion: String
+ ) : ResourceLocator {
+
+ @Throws(IOException::class)
+ override fun getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter): String {
+ try {
+ val deployFile =
+ normalizedPathName(
+ bluePrintLoadConfiguration.blueprintDeployPath,
+ artifactName,
+ artifactVersion,
+ fullName
+ )
+
+ return String(readAllBytes(Paths.get(deployFile)))
+ } catch (var5: IllegalArgumentException) {
+ throw ResourceNotFoundException("Couldn't find resource: $fullName")
+ }
+ }
+ }
+
+ fun generateContent(
+ template: String,
+ json: String,
+ ignoreJsonNull: Boolean,
+ additionalContext: MutableMap<String, Any>,
+ 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<String, Any>,
+ 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<JsonNode>(json, JsonNode::class.java)
+ ?: throw BluePrintProcessorException("couldn't get json node from json")
+ if (ignoreJsonNull) {
+ jsonNode.removeNullNode()
+ }
+
+ val jsonMap: Map<String, Any> = mapper.readValue(json, object : TypeReference<Map<String, Any>>() {})
+ additionalContext.putAll(jsonMap)
+ }
+
+ return jinJava.render(template, additionalContext)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt
new file mode 100644
index 000000000..1f71495a3
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileService.kt
@@ -0,0 +1,76 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.service
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.slf4j.LoggerFactory
+
+open class BluePrintRepoFileService(modelTypePath: String) : BluePrintRepoService {
+
+ private val log = LoggerFactory.getLogger(BluePrintRepoFileService::class.toString())
+
+ private val dataTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ private val nodeTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE)
+ private val artifactTypePath = modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE)
+ private val capabilityTypePath =
+ modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE)
+ private val relationshipTypePath =
+ modelTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE)
+ private val extension = ".json"
+
+ override fun getDataType(dataTypeName: String): DataType {
+ val fileName = dataTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(dataTypeName).plus(extension)
+ return getModelType(fileName, DataType::class.java)
+ }
+
+ override fun getNodeType(nodeTypeName: String): NodeType {
+ val fileName = nodeTypePath.plus(BluePrintConstants.PATH_DIVIDER).plus(nodeTypeName).plus(extension)
+ return getModelType(fileName, NodeType::class.java)
+ }
+
+ override fun getArtifactType(artifactTypeName: String): ArtifactType {
+ val fileName = artifactTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(artifactTypeName).plus(extension)
+ return getModelType(fileName, ArtifactType::class.java)
+ }
+
+ override fun getRelationshipType(relationshipTypeName: String): RelationshipType {
+ val fileName = relationshipTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(relationshipTypeName).plus(extension)
+ return getModelType(fileName, RelationshipType::class.java)
+ }
+
+ override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition {
+ val fileName = capabilityTypePath.plus(BluePrintConstants.PATH_DIVIDER)
+ .plus(capabilityDefinitionName).plus(extension)
+ return getModelType(fileName, CapabilityDefinition::class.java)
+ }
+
+ private fun <T> getModelType(fileName: String, valueType: Class<T>): 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..a6d2de476
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeService.kt
@@ -0,0 +1,649 @@
+/*
+ * 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.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.slf4j.LoggerFactory
+import java.io.File
+
+interface BluePrintRuntimeService<T> {
+
+ 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 resolveNodeTemplatePropertyAssignments(
+ nodeTemplateName: String,
+ propertyDefinitions: MutableMap<String, PropertyDefinition>,
+ propertyAssignments: MutableMap<String, JsonNode>
+ ): MutableMap<String, JsonNode>
+
+ fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>):
+ MutableMap<String, JsonNode>
+
+ fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>):
+ MutableMap<String, JsonNode>
+
+ fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, JsonNode>
+
+ fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String): MutableMap<String,
+ JsonNode>
+
+ fun resolveNodeTemplateInterfaceOperationInputs(
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String
+ ): MutableMap<String, JsonNode>
+
+ fun resolveNodeTemplateInterfaceOperationOutputs(
+ nodeTemplateName: String,
+ interfaceName: String,
+ operationName: String
+ ): MutableMap<String, JsonNode>
+
+ fun resolveNodeTemplateArtifact(nodeTemplateName: String, artifactName: String): String
+
+ fun resolveNodeTemplateArtifactDefinition(nodeTemplateName: String, artifactName: String): ArtifactDefinition
+
+ fun resolveDSLExpression(dslPropertyName: String): JsonNode
+
+ 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 assignInputs(jsonNode: JsonNode)
+
+ fun assignWorkflowInputs(workflowName: String, jsonNode: JsonNode)
+
+ fun resolveWorkflowOutputs(workflowName: String): MutableMap<String, JsonNode>
+
+ fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List<String>): JsonNode
+}
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+open class DefaultBluePrintRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) :
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+
+ @Transient
+ private val log = LoggerFactory.getLogger(BluePrintRuntimeService::class.toString())
+
+ private var store: MutableMap<String, JsonNode> = 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<String, JsonNode> {
+ return store
+ }
+
+ @Suppress("UNCHECKED_CAST")
+ override fun setExecutionContext(executionContext: MutableMap<String, JsonNode>) {
+ 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())
+ }
+ }
+
+ /**
+ * Resolve any property assignments for the node
+ */
+ override fun resolveNodeTemplatePropertyAssignments(
+ nodeTemplateName: String,
+ propertyDefinitions: MutableMap<String, PropertyDefinition>,
+ propertyAssignments: MutableMap<String, JsonNode>
+ ):
+ MutableMap<String, JsonNode> {
+
+ val propertyAssignmentValue: MutableMap<String, JsonNode> = 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(
+ nodeTemplateName, nodeTypePropertyName, propertyAssignment
+ )
+ }
+
+ // Set default value if null
+ if (resolvedValue is NullNode) {
+ nodeTypeProperty.defaultValue?.let { resolvedValue = nodeTypeProperty.defaultValue!! }
+ }
+
+ // Set for Return of method
+ propertyAssignmentValue[nodeTypePropertyName] = resolvedValue
+ }
+ return propertyAssignmentValue
+ }
+
+ override fun resolvePropertyDefinitions(name: String, propertyDefinitions: MutableMap<String, PropertyDefinition>):
+ MutableMap<String, JsonNode> {
+ val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
+
+ propertyDefinitions.forEach { propertyName, propertyDefinition ->
+ val propertyAssignmentExpression = PropertyAssignmentService(this)
+ val expression = propertyDefinition.value ?: propertyDefinition.defaultValue
+ if (expression != null) {
+ propertyAssignmentValue[propertyName] =
+ propertyAssignmentExpression.resolveAssignmentExpression(name, propertyName, expression)
+ }
+ }
+ return propertyAssignmentValue
+ }
+
+ override fun resolvePropertyAssignments(name: String, propertyAssignments: MutableMap<String, JsonNode>):
+ MutableMap<String, JsonNode> {
+ val propertyAssignmentValue: MutableMap<String, JsonNode> = hashMapOf()
+
+ propertyAssignments.forEach { (propertyName, propertyExpression) ->
+ val propertyAssignmentExpression = PropertyAssignmentService(this)
+ propertyAssignmentValue[propertyName] =
+ propertyAssignmentExpression.resolveAssignmentExpression(name, propertyName, propertyExpression)
+ }
+ return propertyAssignmentValue
+ }
+
+ override fun resolveNodeTemplateProperties(nodeTemplateName: String): MutableMap<String, JsonNode> {
+ log.info("resolveNodeTemplatePropertyValues for node template ({})", nodeTemplateName)
+
+ val nodeTemplate: NodeTemplate = bluePrintContext.nodeTemplateByName(nodeTemplateName)
+
+ val propertyAssignments: MutableMap<String, JsonNode> = nodeTemplate.properties!!
+
+ // Get the Node Type Definitions
+ val nodeTypePropertiesDefinitions: MutableMap<String, PropertyDefinition> = bluePrintContext
+ .nodeTypeChainedProperties(nodeTemplate.type)!!
+
+ /**
+ * Resolve the NodeTemplate Property Assignment Values.
+ */
+ return resolveNodeTemplatePropertyAssignments(nodeTemplateName, nodeTypePropertiesDefinitions, propertyAssignments)
+ }
+
+ override fun resolveNodeTemplateCapabilityProperties(nodeTemplateName: String, capabilityName: String):
+ MutableMap<String, JsonNode> {
+ 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<String, JsonNode> {
+ log.info(
+ "resolveNodeTemplateInterfaceOperationInputs for node template ($nodeTemplateName), " +
+ "interface name($interfaceName), operationName($operationName)"
+ )
+
+ val propertyAssignments: MutableMap<String, JsonNode> =
+ bluePrintContext.nodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
+ ?: hashMapOf()
+
+ val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type
+
+ val nodeTypeInterfaceOperationInputs: MutableMap<String, PropertyDefinition> =
+ 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<String, JsonNode> {
+ log.info(
+ "resolveNodeTemplateInterfaceOperationOutputs for node template ($nodeTemplateName),interface name " +
+ "($interfaceName), operationName($operationName)"
+ )
+
+ val propertyAssignments: MutableMap<String, JsonNode> =
+ bluePrintContext.nodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
+ ?: hashMapOf()
+
+ val nodeTypeName = bluePrintContext.nodeTemplateByName(nodeTemplateName).type
+
+ val nodeTypeInterfaceOperationOutputs: MutableMap<String, PropertyDefinition> =
+ 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 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"
+ )
+ }
+
+ /**
+ * 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<String, JsonNode> = hashMapOf()
+ rootKeyMap.forEach { (propertyName, propertyValue) ->
+ val propertyAssignmentExpression = PropertyAssignmentService(this)
+ propertyAssignmentValue[propertyName] = propertyAssignmentExpression
+ .resolveAssignmentExpression("DSL", propertyName, propertyValue)
+ }
+ propertyAssignmentValue.asJsonNode()
+ } else {
+ propertyAssignments
+ }
+ }
+
+ override fun setInputValue(propertyName: String, value: JsonNode) {
+ val path = """${BluePrintConstants.PATH_INPUTS}${BluePrintConstants.PATH_DIVIDER}$propertyName"""
+ log.trace("setting input path ({}), values ({})", path, value)
+ 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 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("For workflow ($workflowName) driving input data from ($jsonNode)")
+ val dynamicInputPropertiesName = "$workflowName-properties"
+
+ bluePrintContext.workflowByName(workflowName).inputs
+ ?.forEach { propertyName, property ->
+ if (propertyName != dynamicInputPropertiesName) {
+ val valueNode: JsonNode =
+ jsonNode.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
+ ?: property.defaultValue
+ ?: NullNode.getInstance()
+ log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
+ setInputValue(propertyName, valueNode)
+ }
+ }
+ // Load Dynamic data Types
+ jsonNode.get(dynamicInputPropertiesName)?.let {
+ bluePrintContext.dataTypeByName("dt-$dynamicInputPropertiesName")?.properties
+ ?.forEach { propertyName, property ->
+ val valueNode: JsonNode =
+ it.at(BluePrintConstants.PATH_DIVIDER + propertyName).returnNullIfMissing()
+ ?: property.defaultValue
+ ?: NullNode.getInstance()
+ log.trace("Setting input data - attribute:($propertyName) value:($valueNode)")
+ setInputValue(propertyName, valueNode)
+ }
+ }
+ }
+
+ override fun resolveWorkflowOutputs(workflowName: String): MutableMap<String, JsonNode> {
+ log.info("resolveWorkflowOutputs for workflow($workflowName)")
+ val outputs = bluePrintContext.workflowByName(workflowName).outputs ?: mutableMapOf()
+ return resolvePropertyDefinitions("WORKFLOW", outputs)
+ }
+
+ override fun getJsonForNodeTemplateAttributeProperties(nodeTemplateName: String, keys: List<String>): 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
+ }
+}
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..db733bda1
--- /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, Any>
+ ): String {
+
+ val artifactDefinition =
+ bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
+ val templateType = artifactDefinition.type
+ val template = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
+
+ return when (templateType) {
+ BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME -> {
+ BluePrintJinjaTemplateService.generateContent(
+ template,
+ jsonData,
+ ignoreJsonNull,
+ additionalContext,
+ bluePrintLoadConfiguration,
+ bluePrintRuntimeService.bluePrintContext().name(),
+ bluePrintRuntimeService.bluePrintContext().version()
+ )
+ }
+ BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME -> {
+ BluePrintVelocityTemplateService.generateContent(template, jsonData, ignoreJsonNull, additionalContext)
+ }
+ else -> {
+ throw BluePrintProcessorException(
+ "Unknown Artifact type, expecting ${BluePrintConstants.ARTIFACT_JINJA_TYPE_NAME}" +
+ "or ${BluePrintConstants.ARTIFACT_VELOCITY_TYPE_NAME}"
+ )
+ }
+ }
+ }
+}
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..f492c2bc6
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintValidatorService.kt
@@ -0,0 +1,706 @@
+/*
+ * 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<String, Any>)
+
+ @Throws(BluePrintException::class)
+ fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>)
+}
+
+@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<String, Any>
+ var message: StringBuilder = StringBuilder()
+ private val separator: String = BluePrintConstants.PATH_DIVIDER
+ var paths: MutableList<String> = arrayListOf()
+
+ @Throws(BluePrintException::class)
+ override fun validateBlueprint(bluePrintContext: BluePrintContext, properties: MutableMap<String, Any>) {
+ validateBlueprint(bluePrintContext.serviceTemplate, properties)
+ }
+
+ @Throws(BluePrintException::class)
+ override fun validateBlueprint(serviceTemplate: ServiceTemplate, properties: MutableMap<String, Any>) {
+ 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<String, String>) {
+ 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<String, ArtifactType>) {
+ 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<String, DataType>) {
+ 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<String, NodeType>) {
+ 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<String, PropertyDefinition>) {
+ paths.add("inputs")
+ message.appendln("---> Input :" + paths.joinToString(separator))
+ validatePropertyDefinitions(inputs)
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateNodeTemplates(nodeTemplates: MutableMap<String, NodeTemplate>) {
+ 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<String, ArtifactDefinition>) {
+ 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<String, Workflow>) {
+ 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<String, PropertyDefinition>) {
+ 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<String, PropertyDefinition>,
+ properties: MutableMap<String, JsonNode>
+ ) {
+ 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<String, InterfaceDefinition>) {
+ 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<String, OperationDefinition>) {
+ paths.add("operations")
+ operations.forEach { opertaionName, operationDefinition ->
+ paths.add(opertaionName)
+ message.appendln("Validating : " + paths.joinToString(separator))
+ operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) }
+ operationDefinition.inputs?.let { validatePropertyDefinitions(operationDefinition.inputs!!) }
+ operationDefinition.outputs?.let { validatePropertyDefinitions(operationDefinition.outputs!!) }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateImplementation(implementation: Implementation) {
+ checkNotEmpty(implementation.primary) { "couldn't get implementation" }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) {
+
+ val artifactType = serviceTemplate.artifactTypes?.get(artifactTypeName)
+ ?: throw BluePrintException("failed to artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
+
+ checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition")
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom))
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidRelationshipTypeDerivedFrom(relationshipTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validRelationShipDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException(format("Failed to get relationship type ({})'s derivedFrom({}) definition ", relationshipTypeName, derivedFrom))
+ }
+ }
+
+ open fun checkPropertyValue(propertyName: String, propertyDefinition: PropertyDefinition, propertyAssignment: JsonNode) {
+ val propertyType = propertyDefinition.type
+ val isValid: Boolean
+
+ if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
+ isValid = JacksonUtils.checkJsonNodeValueOfPrimitiveType(propertyType, propertyAssignment)
+ } else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
+
+ val entrySchemaType = propertyDefinition.entrySchema?.type
+ ?: throw BluePrintException(format("Failed to get EntrySchema type for the collection property ({})", propertyName))
+
+ if (!BluePrintTypes.validPropertyTypes().contains(entrySchemaType)) {
+ checkPropertyDataType(entrySchemaType, propertyName)
+ }
+ isValid = JacksonUtils.checkJsonNodeValueOfCollectionType(propertyType, propertyAssignment)
+ } else {
+ checkPropertyDataType(propertyType, propertyName)
+ isValid = true
+ }
+
+ check(isValid) {
+ throw BluePrintException(
+ format(
+ "property({}) defined of type({}) is not comptable with the value ({})",
+ propertyName, propertyType, propertyAssignment
+ )
+ )
+ }
+ }
+
+ private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
+
+ val dataType = serviceTemplate.dataTypes?.get(dataTypeName)
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+
+ checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
+ }
+
+ private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
+ if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) {
+ return true
+ } else {
+ throw BluePrintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName))
+ }
+ }
+
+ private fun checkDataType(key: String): Boolean {
+ return serviceTemplate.dataTypes?.containsKey(key) ?: false
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt
new file mode 100644
index 000000000..43e27d047
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintVelocityTemplateService.kt
@@ -0,0 +1,99 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ *
+ * Modifications Copyright © 2019 IBM, Bell Canada.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.service
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.apache.commons.lang3.BooleanUtils
+import org.apache.commons.lang3.StringUtils
+import org.apache.velocity.VelocityContext
+import org.apache.velocity.app.VelocityEngine
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory
+import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode
+import java.io.StringWriter
+
+object BluePrintVelocityTemplateService {
+
+ /**
+ * Generate Content from Velocity Template and JSON Content with injected API
+ */
+ fun generateContent(
+ template: String,
+ json: String,
+ ignoreJsonNull: Boolean = false,
+ additionalContext: MutableMap<String, Any> = 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<String, Any> = 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..98e5e5aec
--- /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<In, Out> {
+
+ /** 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<In, Out>
+
+ suspend fun prepareNodeSkipMessage(node: Graph.Node): NodeSkipMessage<In, Out>
+
+ 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<In, Out>
+
+class WorkflowExecuteMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>()
+
+class WorkflowCancelMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>()
+
+class WorkflowRestartMessage<In, Out>(val input: In, val output: CompletableDeferred<Out>) : WorkflowMessage<In, Out>()
+
+/** Node Message Types */
+sealed class NodeMessage<In, Out>
+
+class NodeReadyMessage<In, Out>(val fromEdge: Graph.Edge, val edgeAction: EdgeAction) : NodeMessage<In, Out>()
+
+class NodeExecuteMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>()
+
+class NodeRestartMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>()
+
+class NodeSkipMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>()
+
+class NodeCancelMessage<In, Out>(val node: Graph.Node, val nodeInput: In, val nodeOutput: Out) : NodeMessage<In, Out>()
+
+enum class EdgeAction(val id: String) {
+ EXECUTE("execute"),
+ SKIP("skip")
+}
+
+/** Abstract workflow service implementation */
+abstract class AbstractBluePrintWorkFlowService<In, Out> : CoroutineScope, BluePrintWorkFlowService<In, Out> {
+
+ lateinit var graph: Graph
+
+ private val log = logger(AbstractBluePrintWorkFlowService::class)
+
+ private val job = Job()
+
+ lateinit var workflowId: String
+
+ var exceptions: MutableList<Exception> = arrayListOf()
+
+ final 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<WorkflowMessage<In, Out>>(coroutineContext, Channel.UNLIMITED) {
+ /** Process the workflow execution message */
+ suspend fun executeMessageActor(workflowExecuteMessage: WorkflowExecuteMessage<In, Out>) {
+
+ 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<In, Out> -> {
+ launch {
+ try {
+ executeMessageActor(message)
+ } catch (e: Exception) {
+ exceptions.add(e)
+ }
+ }
+ }
+ is WorkflowRestartMessage<In, Out> -> {
+ launch {
+ TODO("")
+ }
+ }
+ is WorkflowCancelMessage<In, Out> -> {
+ launch {
+ TODO("")
+ }
+ }
+ }
+ }
+ }
+
+ private suspend fun nodeActor() = actor<NodeMessage<In, Out>>(coroutineContext, Channel.UNLIMITED) {
+
+ /** Send message to process from one state to other state */
+ fun sendNodeMessage(nodeMessage: NodeMessage<In, Out>) = 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<In, Out>(stateEdge, EdgeAction.EXECUTE)
+ sendNodeMessage(nodeReadyMessage)
+ }
+ }
+ }
+
+ suspend fun triggerToExecuteOrSkip(message: NodeReadyMessage<In, Out>) {
+ 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<In, Out>) {
+ 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<In, Out>) {
+ 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<In, Out>(skippingEdge, EdgeAction.SKIP)
+ sendNodeMessage(nodeReadyMessage)
+ }
+ // Process Success Node
+ processNextNodes(node, nodeState)
+ }
+ }
+
+ suspend fun skipNodeWorker(message: NodeSkipMessage<In, Out>) {
+ 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<In, Out>(outgoingEdge, EdgeAction.SKIP)
+ sendNodeMessage(nodeReadyMessage)
+ }
+ }
+ }
+
+ fun restartNodeWorker(message: NodeRestartMessage<In, Out>) = launch {
+ TODO()
+ }
+
+ fun cancelNodeWorker(messageWorkflow: WorkflowCancelMessage<In, Out>) = 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<In, Out> -> {
+ // Blocking call
+ try {
+ readyNodeWorker(nodeMessage)
+ } catch (e: Exception) {
+ exceptions.add(e)
+ channel.close()
+ }
+ }
+ is NodeExecuteMessage<In, Out> -> {
+ launch {
+ try {
+ executeNodeWorker(nodeMessage)
+ } catch (e: Exception) {
+ nodeMessage.node.status = NodeStatus.TERMINATED
+ exceptions.add(e)
+ channel.close()
+ }
+ }
+ }
+ is NodeSkipMessage<In, Out> -> {
+ launch {
+ try {
+ skipNodeWorker(nodeMessage)
+ } catch (e: Exception) {
+ nodeMessage.node.status = NodeStatus.TERMINATED
+ exceptions.add(e)
+ channel.close()
+ }
+ }
+ }
+ is NodeRestartMessage<In, Out> -> {
+ 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
new file mode 100644
index 000000000..2dc8b5cf7
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/PropertyAssignmentService.kt
@@ -0,0 +1,259 @@
+/*
+ * 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 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
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData
+import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationOutputExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyExpression
+import org.onap.ccsdk.cds.controllerblueprints.core.format
+import org.onap.ccsdk.cds.controllerblueprints.core.isComplexType
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.ResourceResolverUtils
+import org.slf4j.LoggerFactory
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class PropertyAssignmentService(var bluePrintRuntimeService: BluePrintRuntimeService<MutableMap<String, JsonNode>>) {
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
+
+ private var bluePrintContext: BluePrintContext = bluePrintRuntimeService.bluePrintContext()
+
+ /*
+
+ If Property Assignment is Expression.
+ Get the Expression
+ Recursively resolve the expression
+ */
+
+ fun resolveAssignmentExpression(
+ nodeTemplateName: String,
+ assignmentName: String,
+ assignment: JsonNode
+ ): JsonNode {
+ val valueNode: JsonNode
+ log.trace("Assignment ({})", assignment)
+ val expressionData = BluePrintExpressionService.getExpressionData(assignment)
+
+ if (expressionData.isExpression) {
+ valueNode = resolveExpression(nodeTemplateName, assignmentName, expressionData)
+ } else {
+ valueNode = expressionData.valueNode
+ }
+ return valueNode
+ }
+
+ fun resolveExpression(nodeTemplateName: String, propName: String, expressionData: ExpressionData): JsonNode {
+
+ var valueNode: JsonNode = NullNode.getInstance()
+
+ if (expressionData.isExpression) {
+ val command = expressionData.command!!
+
+ when (command) {
+ BluePrintConstants.EXPRESSION_GET_INPUT -> {
+ valueNode = bluePrintRuntimeService.getInputValue(expressionData.inputExpression?.propertyName!!)
+ }
+ BluePrintConstants.EXPRESSION_GET_ATTRIBUTE -> {
+ valueNode = resolveAttributeExpression(nodeTemplateName, expressionData.attributeExpression!!)
+ }
+ BluePrintConstants.EXPRESSION_GET_PROPERTY -> {
+ valueNode = resolvePropertyExpression(nodeTemplateName, expressionData.propertyExpression!!)
+ }
+ BluePrintConstants.EXPRESSION_GET_OPERATION_OUTPUT -> {
+ valueNode = resolveOperationOutputExpression(nodeTemplateName, expressionData.operationOutputExpression!!)
+ }
+ BluePrintConstants.EXPRESSION_GET_ARTIFACT -> {
+ valueNode = resolveArtifactExpression(nodeTemplateName, expressionData.artifactExpression!!)
+ }
+ BluePrintConstants.EXPRESSION_DSL_REFERENCE -> {
+ valueNode = bluePrintRuntimeService.resolveDSLExpression(expressionData.dslExpression!!.propertyName)
+ }
+ BluePrintConstants.EXPRESSION_GET_NODE_OF_TYPE -> {
+ }
+ else -> {
+ throw BluePrintException(format("for property ({}), command ({}) is not supported ", propName, command))
+ }
+ }
+ }
+ return valueNode
+ }
+
+ /*
+ get_attribute: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>,
+ <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ]
+ */
+ fun resolveAttributeExpression(nodeTemplateName: String, attributeExpression: AttributeExpression): JsonNode {
+ var valueNode: JsonNode
+
+ val attributeName = attributeExpression.attributeName
+ val subAttributeName: String? = attributeExpression.subAttributeName
+
+ var attributeNodeTemplateName = nodeTemplateName
+ /**
+ * Attributes are dynamic runtime properties information. There are multiple types of Attributes,
+ * ENV : Environment Variables
+ * APP : Application properties ( ie Spring resolved properties )
+ * BPP : Blueprint Properties, Specific to Blue Print execution.
+ * SELF : Current Node Template properties.
+ */
+ when (attributeExpression.modelableEntityName) {
+ BluePrintConstants.PROPERTY_ENV -> {
+ val environmentValue = System.getProperty(attributeName)
+ valueNode = environmentValue.asJsonPrimitive()
+ }
+ BluePrintConstants.PROPERTY_APP -> {
+ TODO("Get property from application properties")
+ }
+ BluePrintConstants.PROPERTY_BPP -> {
+ valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(BluePrintConstants.PROPERTY_BPP, attributeName)
+ ?: throw BluePrintException("failed to get env attribute name ($attributeName) ")
+ }
+ else -> {
+ if (!attributeExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) {
+ attributeNodeTemplateName = attributeExpression.modelableEntityName
+ }
+
+ var attributeDefinition: AttributeDefinition = bluePrintContext
+ .nodeTemplateNodeType(attributeNodeTemplateName).attributes?.get(attributeName)
+ ?: throw BluePrintException("failed to get attribute definitions for node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
+
+ valueNode = bluePrintRuntimeService.getNodeTemplateAttributeValue(attributeNodeTemplateName, attributeName)
+ ?: throw BluePrintException("failed to get node template ($attributeNodeTemplateName)'s attribute name ($attributeName) ")
+ }
+ }
+ if (subAttributeName != null) {
+ if (valueNode.isComplexType())
+ valueNode = valueNode.jsonPathParse(subAttributeName)
+ }
+ return valueNode
+ }
+
+ /*
+ get_property: [ <modelable_entity_name>, <optional_req_or_cap_name>, <property_name>,
+ <nested_property_name_or_index_1>, ..., <nested_property_name_or_index_n> ]
+ */
+ fun resolvePropertyExpression(nodeTemplateName: String, propertyExpression: PropertyExpression): JsonNode {
+ var valueNode: JsonNode
+
+ val propertyName = propertyExpression.propertyName
+ val subPropertyName: String? = propertyExpression.subPropertyName
+
+ var propertyNodeTemplateName = nodeTemplateName
+
+ if (!propertyExpression.modelableEntityName.equals(BluePrintConstants.PROPERTY_SELF, true)) {
+ propertyNodeTemplateName = propertyExpression.modelableEntityName
+ }
+
+ val nodeTemplatePropertyExpression = bluePrintContext.nodeTemplateByName(propertyNodeTemplateName).properties?.get(propertyName)
+ ?: throw BluePrintException(
+ format(
+ "failed to get property definitions for node template ({})'s property name ({}) ",
+ nodeTemplateName,
+ propertyName
+ )
+ )
+
+ var propertyDefinition: PropertyDefinition = bluePrintContext.nodeTemplateNodeType(propertyNodeTemplateName).properties?.get(propertyName)!!
+
+ log.info(
+ "node template name ({}), property Name ({}) resolved value ({})",
+ propertyNodeTemplateName,
+ propertyName,
+ nodeTemplatePropertyExpression
+ )
+
+ // Check it it is a nested expression
+ valueNode = resolveAssignmentExpression(propertyNodeTemplateName, propertyName, nodeTemplatePropertyExpression)
+
+ if (subPropertyName != null) {
+ if (valueNode.isComplexType())
+ valueNode = valueNode.jsonPathParse(subPropertyName)
+ }
+ return valueNode
+ }
+
+ /*
+ get_operation_output: <modelable_entity_name>, <interface_name>, <operation_name>, <output_variable_name>
+ */
+ fun resolveOperationOutputExpression(nodeTemplateName: String, operationOutputExpression: OperationOutputExpression): JsonNode {
+ var outputNodeTemplateName = nodeTemplateName
+ if (!operationOutputExpression.modelableEntityName.equals("SELF", true)) {
+ outputNodeTemplateName = operationOutputExpression.modelableEntityName
+ }
+
+ var valueNode = bluePrintRuntimeService.getNodeTemplateOperationOutputValue(
+ outputNodeTemplateName,
+ operationOutputExpression.interfaceName, operationOutputExpression.operationName,
+ operationOutputExpression.propertyName
+ )
+
+ val subPropertyName: String? = operationOutputExpression.subPropertyName
+ if (subPropertyName != null) {
+ if (valueNode.isComplexType())
+ valueNode = valueNode.jsonPathParse(subPropertyName)
+ }
+ return valueNode
+ }
+
+ /*
+ get_artifact: [ <modelable_entity_name>, <artifact_name>, <location>, <remove> ]
+ */
+ fun resolveArtifactExpression(nodeTemplateName: String, artifactExpression: ArtifactExpression): JsonNode {
+
+ var artifactNodeTemplateName = nodeTemplateName
+ if (!artifactExpression.modelableEntityName.equals("SELF", true)) {
+ artifactNodeTemplateName = artifactExpression.modelableEntityName
+ }
+ val artifactDefinition: ArtifactDefinition = bluePrintContext.nodeTemplateByName(artifactNodeTemplateName)
+ .artifacts?.get(artifactExpression.artifactName)
+ ?: throw BluePrintException(
+ format(
+ "failed to get artifact definitions for node template ({})'s " +
+ "artifact name ({}) ", nodeTemplateName, artifactExpression.artifactName
+ )
+ )
+
+ return JacksonUtils.jsonNodeFromObject(artifactContent(artifactDefinition))
+ }
+
+ fun artifactContent(artifactDefinition: ArtifactDefinition): String {
+ val bluePrintBasePath: String = bluePrintContext.rootPath
+
+ if (artifactDefinition.repository != null) {
+ TODO()
+ } else if (artifactDefinition.file != null) {
+ return ResourceResolverUtils.getFileContent(artifactDefinition.file, bluePrintBasePath)
+ }
+ return ""
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt
new file mode 100755
index 000000000..9ccf856b5
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintArchiveUtils.kt
@@ -0,0 +1,158 @@
+/*
+ * 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.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.slf4j.LoggerFactory
+import java.io.BufferedInputStream
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.nio.charset.Charset
+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.function.Predicate
+import java.util.zip.Deflater
+import java.util.zip.ZipEntry
+import java.util.zip.ZipFile
+import java.util.zip.ZipOutputStream
+
+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): Boolean {
+ try {
+ if (!destination.parentFile.exists()) {
+ destination.parentFile.mkdirs()
+ }
+ destination.createNewFile()
+ val ignoreZipFiles = Predicate<Path> { path -> !path.endsWith(".zip") && !path.endsWith(".ZIP") }
+ FileOutputStream(destination).use { out ->
+ compressFolder(source.toPath(), out, 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, compressionLevel: Int = Deflater.NO_COMPRESSION): ByteArray {
+ return compressFolder(baseDir, ByteArrayOutputStream(), 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 <T> compressFolder(
+ baseDir: Path,
+ output: T,
+ pathFilter: Predicate<Path> = Predicates.alwaysTrue(),
+ compressionLevel: Int = Deflater.DEFAULT_COMPRESSION,
+ fixedModificationTime: Long? = null
+ ): T
+ where T : OutputStream {
+ ZipOutputStream(output)
+ .apply { setLevel(compressionLevel) }
+ .use { zos ->
+ Files.walkFileTree(baseDir, object : SimpleFileVisitor<Path>() {
+ @Throws(IOException::class)
+ override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
+ if (pathFilter.test(file)) {
+ val zipEntry = ZipEntry(baseDir.relativize(file).toString())
+ fixedModificationTime?.let {
+ zipEntry.time = it
+ }
+ zipEntry.time = 0
+ zos.putNextEntry(zipEntry)
+ Files.copy(file, zos)
+ zos.closeEntry()
+ }
+ return FileVisitResult.CONTINUE
+ }
+
+ @Throws(IOException::class)
+ override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
+ val zipEntry = ZipEntry(baseDir.relativize(dir).toString() + "/")
+ fixedModificationTime?.let {
+ zipEntry.time = it
+ }
+ zos.putNextEntry(zipEntry)
+ zos.closeEntry()
+ return FileVisitResult.CONTINUE
+ }
+ })
+ }
+ return output
+ }
+
+ fun deCompress(zipFile: File, targetPath: String): File {
+ val zip = ZipFile(zipFile, Charset.defaultCharset())
+ val enumeration = zip.entries()
+ while (enumeration.hasMoreElements()) {
+ val entry = enumeration.nextElement()
+ val destFilePath = File(targetPath, entry.name)
+ destFilePath.parentFile.mkdirs()
+
+ if (entry.isDirectory)
+ continue
+
+ val bufferedIs = BufferedInputStream(zip.getInputStream(entry))
+ bufferedIs.use {
+ destFilePath.outputStream().buffered(1024).use { bos ->
+ bufferedIs.copyTo(bos)
+ }
+ }
+ }
+
+ val destinationDir = File(targetPath)
+ check(destinationDir.isDirectory && destinationDir.exists()) {
+ throw BluePrintProcessorException("failed to decompress blueprint(${zipFile.absolutePath}) to ($targetPath) ")
+ }
+
+ return destinationDir
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt
new file mode 100755
index 000000000..6605e8eca
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtils.kt
@@ -0,0 +1,292 @@
+/*
+ * 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.nio.file.Files
+import java.nio.file.Path
+import java.nio.file.Paths
+import java.nio.file.StandardOpenOption
+
+class BluePrintFileUtils {
+ companion object {
+
+ 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<ImportDefinition>()
+ 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: <VERSION>" +
+ "\nCreated-By: <AUTHOR NAME>" +
+ "\nEntry-Definitions: Definitions/<BLUEPRINT_NAME>.json" +
+ "\nTemplate-Name: <BLUEPRINT_NAME>" +
+ "\nTemplate-Tags: <BLUEPRINT_VERSION>" +
+ "\nTemplate-Tags: <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-cba-kts.jar"
+ }
+
+ 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
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt
new file mode 100644
index 000000000..d29fed0d9
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtils.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.utils
+
+object BluePrintIOUtils {
+
+ suspend fun <T> 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..4d7647f47
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtils.kt
@@ -0,0 +1,213 @@
+/*
+ * 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.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+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
+ }
+ }
+ }
+ }
+ return toscaMetaData
+ }
+
+ fun getBluePrintRuntime(id: String, blueprintBasePath: String):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath)
+ return getBluePrintRuntime(id, bluePrintContext)
+ }
+
+ fun getBluePrintRuntime(id: String, bluePrintContext: BluePrintContext):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ 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
+ }
+
+ suspend fun getBaseEnhancementBluePrintRuntime(id: String, blueprintBasePath: String):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+
+ 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
+ }
+
+ fun getBluePrintRuntime(id: String, blueprintBasePath: String, executionContext: MutableMap<String, JsonNode>):
+ BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ val bluePrintContext: BluePrintContext = getBluePrintContext(blueprintBasePath)
+ val bluePrintRuntimeService = DefaultBluePrintRuntimeService(id, bluePrintContext)
+ executionContext.forEach {
+ bluePrintRuntimeService.put(it.key, it.value)
+ }
+
+ bluePrintRuntimeService.setExecutionContext(executionContext)
+ return bluePrintRuntimeService
+ }
+
+ fun getBluePrintContext(blueprintBasePath: String): BluePrintContext = runBlocking {
+
+ val toscaMetaData: ToscaMetaData = toscaMetaData(blueprintBasePath)
+
+ log.info("Reading blueprint path($blueprintBasePath) and entry definition file (${toscaMetaData.entityDefinitions})")
+
+ // If the EntryDefinition is Kotlin file, compile and get Service Template
+ if (toscaMetaData.entityDefinitions.endsWith("kt")) {
+ readBlueprintKotlinFile(toscaMetaData, blueprintBasePath)
+ } else {
+ readBlueprintFile(toscaMetaData.entityDefinitions, blueprintBasePath)
+ }
+ }
+
+ 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)
+
+ // Clean the Import Definitions
+ BluePrintFileUtils.cleanImportTypes(rootServiceTemplate)
+
+ val blueprintContext = BluePrintContext(rootServiceTemplate)
+ blueprintContext.rootPath = blueprintBasePath
+ blueprintContext.entryDefinition = toscaMetaData.entityDefinitions
+ return blueprintContext
+ }
+
+ 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 {
+
+ checkNotNull(toscaMetaData.templateName) { "couldn't find 'Template-Name' key in TOSCA.meta" }
+ checkNotNull(toscaMetaData.templateVersion) { "couldn't find 'Template-Version' key in TOSCA.meta" }
+
+ val definitionClassName = toscaMetaData.entityDefinitions.removeSuffix(".kt")
+ val normalizedBasePath = normalizedPathName(basePath)
+
+ val bluePrintScriptsService = BluePrintScriptsServiceImpl()
+ val bluePrintDefinitions = bluePrintScriptsService
+ .scriptInstance<BluePrintDefinitions>(
+ 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
+ }
+ }
+}
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..c44355070
--- /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<String, JsonNode>) {
+ val jsonNode: JsonNode = JacksonUtils.jsonNodeFromFile(fileName)
+ return assignInputs(bluePrintContext, jsonNode, context)
+ }
+
+ fun assignInputsFromClassPathFile(
+ bluePrintContext: BluePrintContext,
+ fileName: String,
+ context: MutableMap<String,
+ JsonNode>
+ ) {
+ val jsonNode = JacksonUtils.jsonNodeFromClassPathFile(fileName)
+ return assignInputs(bluePrintContext, jsonNode, context)
+ }
+
+ fun assignInputsFromContent(bluePrintContext: BluePrintContext, content: String, context: MutableMap<String, JsonNode>) {
+ val jsonNode: JsonNode = JacksonUtils.jsonNode(content)
+ return assignInputs(bluePrintContext, jsonNode, context)
+ }
+
+ fun assignInputs(bluePrintContext: BluePrintContext, jsonNode: JsonNode, context: MutableMap<String, JsonNode>) {
+ 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/DateUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt
new file mode 100644
index 000000000..4fd907a5a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/DateUtils.kt
@@ -0,0 +1,47 @@
+/*
+ * 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 org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import java.text.SimpleDateFormat
+import java.time.LocalDateTime
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.util.Date
+
+fun controllerDate(): Date {
+ val localDateTime = LocalDateTime.now(ZoneId.systemDefault())
+ return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant())
+}
+
+fun currentTimestamp(): String {
+ val localDateTime = LocalDateTime.now(ZoneId.systemDefault())
+ 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)
+ return formatter.parse(this)
+}
+
+/** Return date to CDS string format */
+fun Date.currentTimestamp(): String {
+ 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/JacksonReactorUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt
new file mode 100644
index 000000000..6645ff7b4
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtils.kt
@@ -0,0 +1,92 @@
+/*
+ * 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.utils
+
+import com.fasterxml.jackson.databind.JsonNode
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.apache.commons.io.IOUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.nio.charset.Charset
+
+class JacksonReactorUtils {
+ companion object {
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
+
+ suspend fun getContent(fileName: String): String {
+ // log.info("Reading File($fileName)")
+ return getContent(normalizedFile(fileName))
+ }
+
+ suspend fun getContent(file: File): String = withContext(Dispatchers.IO) {
+ // log.info("Reading File(${file.absolutePath})")
+ file.readText(Charsets.UTF_8)
+ }
+
+ suspend fun getClassPathFileContent(fileName: String): String = withContext(Dispatchers.IO) {
+ // log.trace("Reading Classpath File($fileName)")
+ IOUtils.toString(
+ JacksonUtils::class.java.classLoader
+ .getResourceAsStream(fileName), Charset.defaultCharset()
+ )
+ }
+
+ suspend fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? {
+ val content: String = getContent(fileName)
+ return JacksonUtils.readValue(content, valueType)
+ }
+
+ suspend fun <T> readValueFromClassPathFile(fileName: String, valueType: Class<T>): T? {
+ val content: String = getClassPathFileContent(fileName)
+ return JacksonUtils.readValue(content, valueType)
+ }
+
+ suspend fun jsonNodeFromClassPathFile(fileName: String): JsonNode {
+ val content: String = getClassPathFileContent(fileName)
+ return JacksonUtils.jsonNode(content)
+ }
+
+ suspend fun jsonNodeFromFile(fileName: String): JsonNode {
+ val content: String = getContent(fileName)
+ return JacksonUtils.jsonNode(content)
+ }
+
+ suspend fun <T> getListFromFile(fileName: String, valueType: Class<T>): List<T> {
+ val content: String = getContent(fileName)
+ return JacksonUtils.getListFromJson(content, valueType)
+ }
+
+ suspend fun <T> getListFromClassPathFile(fileName: String, valueType: Class<T>): List<T> {
+ val content: String = getClassPathFileContent(fileName)
+ return JacksonUtils.getListFromJson(content, valueType)
+ }
+
+ suspend fun <T> getMapFromFile(file: File, valueType: Class<T>): MutableMap<String, T> {
+ val content: String = getContent(file)
+ return JacksonUtils.getMapFromJson(content, valueType)
+ }
+
+ suspend fun <T> getMapFromClassPathFile(fileName: String, valueType: Class<T>): MutableMap<String, T> {
+ val content: String = getClassPathFileContent(fileName)
+ return JacksonUtils.getMapFromJson(content, valueType)
+ }
+ }
+}
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
new file mode 100644
index 000000000..945f300af
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtils.kt
@@ -0,0 +1,327 @@
+/*
+ * 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.annotation.JsonInclude
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.SerializationFeature
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.DoubleNode
+import com.fasterxml.jackson.databind.node.FloatNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+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.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.readNBText
+import java.io.File
+import java.io.InputStream
+import java.nio.charset.Charset
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class JacksonUtils {
+
+ companion object {
+
+ val objectMapper = jacksonObjectMapper()
+
+ inline fun <reified T : Any> readValue(content: String): T =
+ objectMapper.readValue(content, T::class.java)
+
+ inline fun <reified T : Any> readValue(stream: InputStream): T =
+ objectMapper.readValue(stream, T::class.java)
+
+ fun <T> readValue(content: String, valueType: Class<T>): T? {
+ return objectMapper.readValue(content, valueType)
+ }
+
+ fun <T> readValue(stream: InputStream, valueType: Class<T>): T? {
+ return objectMapper.readValue(stream, valueType)
+ }
+
+ fun <T> readValue(node: JsonNode, valueType: Class<T>): T? {
+ return objectMapper.treeToValue(node, valueType)
+ }
+
+ fun getContent(fileName: String): String = runBlocking {
+ try {
+ normalizedFile(fileName).readNBText()
+ } catch (e: Exception) {
+ throw BluePrintException("couldn't get file ($fileName) content : ${e.message}")
+ }
+ }
+
+ fun getClassPathFileContent(fileName: String): String {
+ return runBlocking {
+ withContext(Dispatchers.Default) {
+ IOUtils.toString(
+ JacksonUtils::class.java.classLoader
+ .getResourceAsStream(fileName), Charset.defaultCharset()
+ )
+ }
+ }
+ }
+
+ fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? {
+ val content: String = getContent(fileName)
+ return readValue(content, valueType)
+ }
+
+ fun <T> readValueFromClassPathFile(fileName: String, valueType: Class<T>): T? {
+ val content: String = getClassPathFileContent(fileName)
+ return readValue(content, valueType)
+ }
+
+ fun objectNodeFromObject(from: kotlin.Any): ObjectNode {
+ return objectMapper.convertValue(from, ObjectNode::class.java)
+ }
+
+ fun jsonNodeFromObject(from: kotlin.Any): JsonNode {
+ return objectMapper.convertValue(from, JsonNode::class.java)
+ }
+
+ fun jsonNodeFromClassPathFile(fileName: String): JsonNode {
+ val content: String = getClassPathFileContent(fileName)
+ return jsonNode(content)
+ }
+
+ fun jsonNodeFromFile(fileName: String): JsonNode {
+ val content: String = getContent(fileName)
+ return jsonNode(content)
+ }
+
+ fun jsonNode(content: String): JsonNode {
+ return jacksonObjectMapper().readTree(content)
+ }
+
+ fun getJson(any: kotlin.Any): String {
+ return getJson(any, false)
+ }
+
+ fun getWrappedJson(wrapper: String, any: kotlin.Any, pretty: Boolean = false): String {
+ val wrapperMap = hashMapOf<String, Any>()
+ wrapperMap[wrapper] = any
+ return getJson(wrapperMap, pretty)
+ }
+
+ fun getJson(any: kotlin.Any, pretty: Boolean = false): String {
+ val objectMapper = jacksonObjectMapper()
+ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ if (pretty) {
+ objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
+ }
+ return objectMapper.writeValueAsString(any)
+ }
+
+ fun getJsonNode(any: kotlin.Any?, pretty: Boolean = false): JsonNode {
+ val objectMapper = jacksonObjectMapper()
+ objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
+ if (pretty) {
+ objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
+ }
+ return objectMapper.valueToTree(any)
+ }
+
+ fun <T> getListFromJsonNode(node: JsonNode, valueType: Class<T>): List<T> {
+ return getListFromJson(node.toString(), valueType)
+ }
+
+ fun <T> getListFromJson(content: String, valueType: Class<T>): List<T> {
+ val objectMapper = jacksonObjectMapper()
+ val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, valueType)
+ return objectMapper.readValue<List<T>>(content, javaType)
+ }
+
+ fun <T> getListFromFile(fileName: String, valueType: Class<T>): List<T> {
+ val content: String = getContent(fileName)
+ return getListFromJson(content, valueType)
+ }
+
+ fun <T> getListFromClassPathFile(fileName: String, valueType: Class<T>): List<T> {
+ val content: String = getClassPathFileContent(fileName)
+ return getListFromJson(content, valueType)
+ }
+
+ fun <T> getMapFromJson(content: String, valueType: Class<T>): MutableMap<String, T> {
+ val objectMapper = jacksonObjectMapper()
+ val mapType = objectMapper.typeFactory.constructMapType(Map::class.java, String::class.java, valueType)
+ return objectMapper.readValue(content, mapType)
+ }
+
+ fun <T> getMapFromFile(file: File, valueType: Class<T>): MutableMap<String, T> = runBlocking {
+ val content: String = file.readNBText()
+ getMapFromJson(content, valueType)
+ }
+
+ fun <T> getMapFromFile(fileName: String, valueType: Class<T>): MutableMap<String, T> = getMapFromFile(File(fileName), valueType)
+
+ fun <T> getInstanceFromMap(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
+ return readValue(getJson(properties), classType)
+ ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)")
+ }
+
+ fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean {
+ if (BluePrintTypes.validPrimitiveTypes().contains(type.toLowerCase())) {
+ return checkJsonNodeValueOfPrimitiveType(type, jsonNode)
+ } else if (BluePrintTypes.validCollectionTypes().contains(type)) {
+ return checkJsonNodeValueOfCollectionType(type, jsonNode)
+ }
+ return false
+ }
+
+ 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
+ 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
+ else -> false
+ }
+ }
+
+ fun checkJsonNodeValueOfCollectionType(type: String, jsonNode: JsonNode): Boolean {
+ return when (type.toLowerCase()) {
+ BluePrintConstants.DATA_TYPE_LIST -> jsonNode.isArray
+ BluePrintConstants.DATA_TYPE_MAP -> jsonNode.isContainerNode
+ else -> false
+ }
+ }
+
+ fun getValue(value: JsonNode): Any {
+ return when (value) {
+ is BooleanNode -> value.booleanValue()
+ is IntNode -> value.intValue()
+ is FloatNode -> value.floatValue()
+ is DoubleNode -> value.doubleValue()
+ is TextNode -> value.textValue()
+ else -> value
+ }
+ }
+
+ 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()
+ 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 ->
+ objectNode.set(key, 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 ->
+ arrayNode.add(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)")
+ objectNode.set(key, defaultValue)
+ }
+
+ fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) {
+ val defaultValue = getDefaultValueOfPrimitiveAsJsonNode(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()
+ else -> null
+ }
+ }
+
+ 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)) {
+ populatePrimitiveValues(key, nodeValue, type, objectNode)
+ } else {
+ objectNode.set(key, nodeValue)
+ }
+ }
+
+ 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)
+ else -> getJsonNode(value)
+ }
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt
new file mode 100644
index 000000000..0e3d4f93d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtils.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright © 2018 IBM.
+ * 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.utils
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.jayway.jsonpath.Configuration
+import com.jayway.jsonpath.JsonPath
+import com.jayway.jsonpath.Option
+import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider
+import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
+
+class JsonParserUtils {
+ companion object {
+
+ // TODO("Optimise this")
+ val JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder()
+ .mappingProvider(JacksonMappingProvider()).jsonProvider(JacksonJsonNodeJsonProvider()).build()
+
+ val PATH_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST).build()
+
+ fun paths(jsonContent: String, expression: String): List<String> {
+ return JsonPath.using(PATH_CONFIGURATION).parse(jsonContent).read(expression)
+ }
+
+ fun paths(jsonNode: JsonNode, expression: String): List<String> {
+ return paths(jsonNode.asJsonString(), expression)
+ }
+
+ fun parse(jsonContent: String, expression: String): JsonNode {
+ return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).read(expression)
+ }
+
+ fun parse(jsonNode: JsonNode, expression: String): JsonNode {
+ return parse(jsonNode.asJsonString(), expression)
+ }
+
+ fun parseNSet(jsonContent: String, expression: String, value: JsonNode): JsonNode {
+ return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).set(expression, value).json()
+ }
+
+ fun parseNSet(jsonNode: JsonNode, expression: String, valueNode: JsonNode): JsonNode {
+
+ return parseNSet(jsonNode.asJsonString(), expression, valueNode)
+ }
+ }
+}
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
new file mode 100644
index 000000000..c0204af8d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ResourceResolverUtils.kt
@@ -0,0 +1,62 @@
+/*
+ * 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.utils
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.isNotEmpty
+import org.slf4j.LoggerFactory
+import java.io.File
+import java.net.URL
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ResourceResolverUtils {
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
+
+ fun getFileContent(filename: String, basePath: String?): String {
+ log.trace("file ({}), basePath ({}) ", filename, basePath)
+ try {
+ var resolvedFileName: String = filename
+ if (filename.startsWith("http", true) ||
+ filename.startsWith("https", true)
+ ) {
+ val givenUrl: String = URL(filename).toString()
+ val systemUrl: String = File(".").toURI().toURL().toString()
+ log.trace("givenUrl ({}), systemUrl ({}) ", givenUrl, systemUrl)
+ if (givenUrl.startsWith(systemUrl)) {
+ }
+ } else {
+ if (!filename.startsWith("/")) {
+ if (isNotEmpty(basePath)) {
+ resolvedFileName = basePath.plus(File.separator).plus(filename)
+ } else {
+ resolvedFileName = javaClass.classLoader.getResource(".").path.plus(filename)
+ }
+ }
+ }
+ // FIXME("Convert into reactive")
+ return JacksonUtils.getContent(resolvedFileName)
+ } catch (e: Exception) {
+ 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/ServiceTemplateUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt
new file mode 100644
index 000000000..a74722f31
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/ServiceTemplateUtils.kt
@@ -0,0 +1,108 @@
+/*
+ * 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.utils
+
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ServiceTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+object ServiceTemplateUtils {
+
+ suspend fun getServiceTemplate(fileName: String): ServiceTemplate {
+ val content: String = JacksonReactorUtils.getContent(fileName)
+ return getServiceTemplateFromContent(content)
+ }
+
+ fun getServiceTemplateFromContent(content: String): ServiceTemplate {
+ return JacksonUtils.readValue(content)
+ }
+
+ fun merge(parentServiceTemplate: ServiceTemplate, toMerge: ServiceTemplate, removeImports: Boolean? = true): ServiceTemplate {
+ if (removeImports!!) {
+ parentServiceTemplate.imports = null
+ toMerge.imports = null
+ }
+
+ toMerge.metadata?.let {
+ parentServiceTemplate.metadata = parentServiceTemplate.metadata ?: hashMapOf()
+ parentServiceTemplate.metadata?.putAll(toMerge.metadata as MutableMap)
+ }
+
+ toMerge.dslDefinitions?.let {
+ parentServiceTemplate.dslDefinitions = parentServiceTemplate.dslDefinitions ?: hashMapOf()
+ parentServiceTemplate.dslDefinitions?.putAll(toMerge.dslDefinitions as MutableMap)
+ }
+
+ toMerge.dataTypes?.let {
+ parentServiceTemplate.dataTypes = parentServiceTemplate.dataTypes ?: hashMapOf()
+ parentServiceTemplate.dataTypes?.putAll(toMerge.dataTypes as MutableMap)
+ }
+
+ toMerge.nodeTypes?.let {
+ parentServiceTemplate.nodeTypes = parentServiceTemplate.nodeTypes ?: hashMapOf()
+ parentServiceTemplate.nodeTypes?.putAll(toMerge.nodeTypes as MutableMap)
+ }
+
+ toMerge.artifactTypes?.let {
+ parentServiceTemplate.artifactTypes = parentServiceTemplate.artifactTypes ?: hashMapOf()
+ parentServiceTemplate.artifactTypes?.putAll(toMerge.artifactTypes as MutableMap)
+ }
+
+ toMerge.repositories?.let {
+ parentServiceTemplate.repositories = parentServiceTemplate.repositories ?: hashMapOf()
+ parentServiceTemplate.repositories?.putAll(toMerge.repositories as MutableMap)
+ }
+
+ parentServiceTemplate.topologyTemplate = parentServiceTemplate.topologyTemplate ?: TopologyTemplate()
+
+ toMerge.topologyTemplate?.inputs?.let {
+ parentServiceTemplate.topologyTemplate?.inputs = parentServiceTemplate.topologyTemplate?.inputs
+ ?: hashMapOf()
+ parentServiceTemplate.topologyTemplate?.inputs?.putAll(parentServiceTemplate.topologyTemplate?.inputs as MutableMap)
+ }
+
+ toMerge.topologyTemplate?.nodeTemplates?.let {
+ parentServiceTemplate.topologyTemplate?.nodeTemplates = parentServiceTemplate.topologyTemplate?.nodeTemplates
+ ?: hashMapOf()
+ parentServiceTemplate.topologyTemplate?.nodeTemplates?.putAll(parentServiceTemplate.topologyTemplate?.nodeTemplates as MutableMap)
+ }
+
+ toMerge.topologyTemplate?.relationshipTemplates?.let {
+ parentServiceTemplate.topologyTemplate?.relationshipTemplates = parentServiceTemplate.topologyTemplate?.relationshipTemplates
+ ?: hashMapOf()
+ parentServiceTemplate.topologyTemplate?.relationshipTemplates?.putAll(parentServiceTemplate.topologyTemplate?.relationshipTemplates as MutableMap)
+ }
+
+ toMerge.topologyTemplate?.policies?.let {
+ parentServiceTemplate.topologyTemplate?.policies = parentServiceTemplate.topologyTemplate?.policies
+ ?: hashMapOf()
+ parentServiceTemplate.topologyTemplate?.policies?.putAll(parentServiceTemplate.topologyTemplate?.policies as MutableMap)
+ }
+
+ toMerge.topologyTemplate?.workflows?.let {
+ parentServiceTemplate.topologyTemplate?.workflows = parentServiceTemplate.topologyTemplate?.workflows
+ ?: hashMapOf()
+ parentServiceTemplate.topologyTemplate?.workflows?.putAll(parentServiceTemplate.topologyTemplate?.workflows as MutableMap)
+ }
+ return parentServiceTemplate
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt
new file mode 100644
index 000000000..fb990c486
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtils.kt
@@ -0,0 +1,132 @@
+/*
+ * 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 java.util.ArrayList
+import java.util.HashMap
+import java.util.LinkedList
+import java.util.Stack
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class TopologicalSortingUtils<V> {
+
+ private val neighbors: MutableMap<V, MutableList<V>> = hashMapOf()
+
+ val isDag: Boolean
+ get() = topSort() != null
+
+ override fun toString(): String {
+ val s = StringBuffer()
+ for (v in neighbors.keys)
+ s.append("\n " + v + " -> " + neighbors[v])
+ return s.toString()
+ }
+
+ fun getNeighbors(): Map<V, List<V>> {
+ return neighbors
+ }
+
+ fun add(vertex: V) {
+ if (neighbors.containsKey(vertex))
+ return
+ neighbors[vertex] = arrayListOf()
+ }
+
+ operator fun contains(vertex: V): Boolean {
+ return neighbors.containsKey(vertex)
+ }
+
+ fun add(from: V, to: V) {
+ this.add(from)
+ this.add(to)
+ neighbors[from]?.add(to)
+ }
+
+ fun remove(from: V, to: V) {
+ if (!(this.contains(from) && this.contains(to)))
+ throw IllegalArgumentException("Nonexistent vertex")
+ neighbors[from]?.remove(to)
+ }
+
+ fun outDegree(): Map<V, Int> {
+ val result: MutableMap<V, Int> = hashMapOf()
+ for (v in neighbors.keys)
+ result[v] = neighbors[v]!!.size
+ return result
+ }
+
+ fun inDegree(): MutableMap<V, Int> {
+ val result = HashMap<V, Int>()
+ for (v in neighbors.keys)
+ result[v] = 0 // All in-degrees are 0
+ for (from in neighbors.keys) {
+ for (to in neighbors[from]!!) {
+ result[to] = result[to]!! + 1 // Increment in-degree
+ }
+ }
+ return result
+ }
+
+ fun topSort(): List<V>? {
+ val degree = inDegree()
+ // Determine all vertices with zero in-degree
+ val zeroVerts = Stack<V>() // Stack as good as any here
+ for (v in degree.keys) {
+ if (degree[v] == 0) zeroVerts.push(v)
+ }
+ // Determine the topological order
+ val result = ArrayList<V>()
+ while (!zeroVerts.isEmpty()) {
+ val v = zeroVerts.pop() // Choose a vertex with zero in-degree
+ result.add(v) // Vertex v is next in topol order
+ // "Remove" vertex v by updating its neighbors
+ for (neighbor in neighbors[v]!!) {
+ degree[neighbor] = degree[neighbor]!! - 1
+ // Remember any vertices that now have zero in-degree
+ if (degree[neighbor] == 0) zeroVerts.push(neighbor)
+ }
+ }
+ // Check that we have used the entire graph (if not, there was a cycle)
+ return if (result.size != neighbors.size) null else result
+ }
+
+ fun bfsDistance(start: V): Map<*, *> {
+ val distance: MutableMap<V, Int> = hashMapOf()
+ // Initially, all distance are infinity, except start node
+ for (v in neighbors.keys)
+ distance[v] = -1
+ distance[start] = 0
+ // Process nodes in queue order
+ val queue = LinkedList<V>()
+ queue.offer(start) // Place start node in queue
+ while (!queue.isEmpty()) {
+ val v = queue.remove()
+ val vDist = distance[v]!!
+ // Update neighbors
+ for (neighbor in neighbors[v]!!) {
+ if (distance[neighbor] != null) continue // Ignore if already done
+ distance[neighbor] = vDist + 1
+ queue.offer(neighbor)
+ }
+ }
+ return distance
+ }
+}
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
new file mode 100644
index 000000000..fea637f61
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtils.kt
@@ -0,0 +1,46 @@
+/*
+ * 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 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
+import org.onap.ccsdk.cds.controllerblueprints.core.endNodes
+import org.onap.ccsdk.cds.controllerblueprints.core.startNodes
+
+object WorkflowGraphUtils {
+
+ fun workFlowToGraph(workflow: Workflow): Graph {
+ val graph = Graph()
+ workflow.steps?.forEach { (stepName, step) ->
+ step.onSuccess?.forEach { successTarget ->
+ graph.addEdge(stepName, successTarget, EdgeLabel.SUCCESS)
+ }
+ step.onFailure?.forEach { failureTarget ->
+ graph.addEdge(stepName, failureTarget, EdgeLabel.FAILURE)
+ }
+ }
+ graph.startNodes().forEach { rootNode ->
+ 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)
+ }
+ return graph
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/kotlin/script/templates/org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintKotlinScript
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory
new file mode 100644
index 000000000..89838f44f
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/main/resources/META-INF/services/javax.script.ScriptEngineFactory
@@ -0,0 +1,17 @@
+#
+# 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.
+#
+
+org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory \ No newline at end of file
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..6a028d36f
--- /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
new file mode 100644
index 000000000..3ae87b32d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/CustomFunctionsTest.kt
@@ -0,0 +1,238 @@
+/*
+ * 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
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.BooleanNode
+import com.fasterxml.jackson.databind.node.IntNode
+import com.fasterxml.jackson.databind.node.JsonNodeType
+import com.fasterxml.jackson.databind.node.MissingNode
+import com.fasterxml.jackson.databind.node.NullNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import com.fasterxml.jackson.databind.node.TextNode
+import org.junit.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class CustomFunctionsTest {
+
+ @Test
+ fun testFormat() {
+ val returnValue: String = format("This is {} for times {}", "test", 2)
+ assertEquals("This is test for times 2", returnValue, "Failed to format String")
+
+ val returnValue1: String = format("This is test for times 2")
+ assertEquals("This is test for times 2", returnValue1, "Failed to format empty args")
+ }
+
+ @Test
+ fun testStringAsJsonPrimitive() {
+ val returnValue: TextNode = "hello".asJsonPrimitive()
+ assertEquals("hello", returnValue.textValue())
+ }
+
+ @Test
+ fun testIntAsJsonPrimitive() {
+ val returnValue: IntNode = 1.asJsonPrimitive()
+ assertEquals(1, returnValue.intValue())
+ }
+
+ @Test
+ fun testBooleanAsJsonPrimitive() {
+ val returnValue: BooleanNode = false.asJsonPrimitive()
+ assertFalse(returnValue.asBoolean())
+ }
+
+ @Test
+ fun testAsJsonType() {
+ val nullReturnValue: JsonNode = null.asJsonType()
+ assertEquals(NullNode.instance, nullReturnValue)
+
+ val returnValueString: JsonNode = "hello".asJsonType()
+ assertEquals("hello", returnValueString.textValue())
+
+ val returnValueJsonNode: JsonNode = returnValueString.asJsonType()
+ assertEquals(returnValueString, returnValueJsonNode)
+
+ val returnValueInt: JsonNode = 1.asJsonType()
+ assertEquals(1, returnValueInt.intValue())
+
+ val returnValueBool: JsonNode = false.asJsonType()
+ assertFalse(returnValueBool.asBoolean())
+
+ val returnValue: JsonNode = BluePrintError().asJsonType()
+ assertEquals(JsonNodeType.OBJECT, returnValue.getNodeType())
+ }
+
+ @Test
+ fun testMapAsObjectNode() {
+ val returnValue: ObjectNode = hashMapOf("test" to BluePrintError()).asObjectNode()
+ assertNotNull(returnValue.get("test"))
+ }
+
+ @Test
+ fun testCastOptionalValue() {
+ val initMap: Map<String, *> = hashMapOf("test" to 1.1, "test2" to null)
+ val returnValue = initMap.castOptionalValue("test", Number::class)
+
+ assert(returnValue is Number)
+
+ val returnValueNull = initMap.castOptionalValue("test1", Number::class)
+
+ assertNull(returnValueNull)
+
+ val returnValueString: String? = initMap.castOptionalValue("test2", String::class)
+
+ assertNull(returnValueString)
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testCastValue() {
+ val initMap: Map<String, Double> = hashMapOf("test" to 1.1)
+ val returnValue = initMap.castValue("test", Number::class)
+
+ assertNotNull(returnValue)
+
+ initMap.castValue("test1", Number::class)
+ }
+
+ @Test
+ fun testAsListOfString() {
+ val arrayNode: ArrayNode = ObjectMapper().createObjectNode().putArray("array")
+
+ val result: List<String> = arrayNode.asListOfString()
+
+ assertTrue(result.isEmpty())
+ }
+
+ @Test
+ fun testReturnNullIfMissing() {
+ val valueExist = "hello".asJsonType().returnNullIfMissing()
+ assertNotNull(valueExist)
+
+ val valueNull = NullNode.instance.returnNullIfMissing()
+ assertNull(valueNull)
+
+ val missingValue = MissingNode.getInstance().returnNullIfMissing()
+ assertNull(missingValue)
+ }
+
+ @Test
+ fun testIsNullOrMissing() {
+ assertTrue(NullNode.instance.isNullOrMissing())
+ assertTrue(MissingNode.getInstance().isNullOrMissing())
+
+ assertFalse(TextNode("").isNullOrMissing())
+ assertFalse("".asJsonType().isNullOrMissing())
+ assertFalse("hello".asJsonType().isNullOrMissing())
+ assertFalse("{\"key\": \"value\"}".asJsonType().isNullOrMissing())
+ assertFalse(TextNode("hello").isNullOrMissing())
+ }
+
+ @Test
+ fun testIsComplexType() {
+ assertFalse(NullNode.instance.isComplexType())
+ assertFalse(MissingNode.getInstance().isComplexType())
+
+ assertFalse(TextNode("").isComplexType())
+ assertFalse("".asJsonType().isComplexType())
+ assertFalse("hello".asJsonType().isComplexType())
+ assertFalse(TextNode("hello").isComplexType())
+
+ assertTrue("{\"key\": \"value\"}".asJsonType().isComplexType())
+ assertTrue("[{\"key\": \"value\"},{\"key\": \"value\"}]".asJsonType().isComplexType())
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testRootFieldsToMap() {
+ 1.asJsonType().rootFieldsToMap()
+ }
+
+ @Test
+ fun testPutJsonElement() {
+ val mutMap = mutableMapOf("test" to 2.asJsonType())
+
+ mutMap.putJsonElement("hello", 3)
+
+ assertEquals(3, mutMap["hello"]?.asInt())
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testMapGetAsString() {
+ val initMap = hashMapOf("test" to "hello".asJsonType())
+
+ assertEquals("hello", initMap.getAsString("test"))
+
+ initMap.getAsString("test2")
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testMapGetAsBoolean() {
+ val initMap = hashMapOf("test" to true.asJsonType())
+
+ assertTrue(initMap.getAsBoolean("test"))
+
+ initMap.getAsBoolean("test2")
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testMapGetAsInt() {
+ val initMap = hashMapOf("test" to 1.asJsonType())
+
+ assertEquals(1, initMap.getAsInt("test"))
+
+ initMap.getAsInt("test2")
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testCheckEquals() {
+ assertTrue(checkEquals("hello", "hello", { -> "error" }))
+
+ checkEquals("hello", "test", { -> "error" })
+ }
+
+ @Test(expected = IllegalStateException::class)
+ fun testCheckNotEmpty() {
+ assertEquals("hello", checkNotEmpty("hello", { -> "error" }))
+
+ checkNotEmpty("", { -> "error" })
+ }
+
+ @Test(expected = IllegalStateException::class)
+ fun testCheckNotBlank() {
+ assertEquals("hello", checkNotBlank("hello", { -> "error" }))
+
+ checkNotBlank(" ", { -> "error" })
+ }
+
+ @Test
+ fun testNullToEmpty() {
+ assertEquals("", nullToEmpty(null))
+
+ assertEquals("hello", nullToEmpty("hello"))
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctionTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctionTest.kt
new file mode 100644
index 000000000..6383fb4a8
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/FileExtensionFunctionTest.kt
@@ -0,0 +1,33 @@
+/*
+ * 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.junit.Test
+import kotlin.test.assertTrue
+
+class FileExtensionFunctionTest {
+ val blueprintBasePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG
+
+ @Test
+ fun testCompress() {
+ val blueprintFile = normalizedFile(blueprintBasePath)
+ val targetZip = normalizedFile("target", "compress.zip")
+ targetZip.deleteRecursively()
+ blueprintFile.compress(targetZip)
+ assertTrue(blueprintFile.exists(), "failed to create compressed file(${targetZip.absolutePath} ")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctionsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctionsTest.kt
new file mode 100644
index 000000000..86cb473ae
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/GraphExtensionFunctionsTest.kt
@@ -0,0 +1,37 @@
+/*
+ * 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.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel
+import kotlin.test.assertNotNull
+
+class GraphExtensionFunctionsTest {
+
+ @Test
+ fun testGraph() {
+ val graph = "[p>q/SUCCESS, m>q/SUCCESS, k, p>m/FAILURE, o>p/SUCCESS]".toGraph()
+ assertNotNull(graph, "failed to create graph")
+ assertNotNull(graph.toAdjacencyList(), "failed to adjacency list from graph")
+
+ val neighbors = graph.nodes["p"]!!.neighbors()
+ assertNotNull(neighbors, "failed to neighbors from graph for 'p' node")
+
+ val nodePath = graph.nodes["p"]!!.neighbors(EdgeLabel.SUCCESS)
+ assertNotNull(nodePath, "failed to nodePath from graph for 'p' node 'SUCCESS' label")
+ }
+}
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
new file mode 100644
index 000000000..498a85239
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/MDCContextTest.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core
+
+import kotlinx.coroutines.GlobalScope
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Before
+import org.slf4j.MDC
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+class MDCContextTest {
+ val log = logger(MDCContextTest::class)
+ @Before
+ fun setup() {
+ MDC.clear()
+ }
+
+ @After
+ fun tearDow() {
+ MDC.clear()
+ }
+
+ @Test
+ fun testContextCanBePassedBetweenCoroutines() {
+ MDC.put(BluePrintConstants.ONAP_REQUEST_ID, "12345")
+ runBlocking {
+ GlobalScope.launch {
+ assertEquals(null, MDC.get(BluePrintConstants.ONAP_REQUEST_ID))
+ }
+ launch(MDCContext()) {
+ assertEquals(
+ "12345", MDC.get(BluePrintConstants.ONAP_REQUEST_ID),
+ "couldn't get request id"
+ )
+
+ MDC.put("client_id", "client-1")
+ assertEquals("client-1", MDC.get("client_id"), "couldn't get client id")
+ }
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/TestConstants.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/TestConstants.kt
new file mode 100644
index 000000000..4182a3fcd
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/TestConstants.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core
+
+object TestConstants {
+ const val PATH_TEST_BLUEPRINTS = "./../../../../../components/model-catalog/blueprint-model/test-blueprint"
+ const val PATH_TEST_BLUEPRINTS_BASECONFIG = "$PATH_TEST_BLUEPRINTS/baseconfiguration"
+
+ const val PATH_TEST_DEFINITION_TYPE_STARTER = "./../../../../../components/model-catalog/definition-type/starter-type"
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt
new file mode 100644
index 000000000..a75262f96
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/annotations/BluePrintsAnnotationsTest.kt
@@ -0,0 +1,119 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.annotations
+
+import com.fasterxml.jackson.databind.JsonNode
+import org.onap.ccsdk.cds.controllerblueprints.core.asBluePrintsDataTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asPropertyDefinitionMap
+import kotlin.test.Test
+import kotlin.test.assertNotNull
+
+class BluePrintsAnnotationsTest {
+
+ @Test
+ fun testBluePrintWorkflowData() {
+ val wfInput = TestBluePrintsWorkflowInput::class.asPropertyDefinitionMap()
+ // println(wfInput.asJsonString(true))
+ assertNotNull(wfInput, "failed to generate wfInput property map")
+
+ val wfOutput = TestBluePrintsWorkflowOutput::class.asPropertyDefinitionMap()
+ // println(wfOutput.asJsonString(true))
+ assertNotNull(wfInput, "failed to generate wfOutput property map")
+ }
+
+ @Test
+ fun testBluePrintDataType() {
+ val dataTypes = TestBluePrintsDataType::class.asBluePrintsDataTypes()
+ // println(dataTypes.asJsonString(true))
+ assertNotNull(dataTypes, "failed to generate dataTypes definition")
+ }
+}
+
+@BluePrintsDataType(
+ name = "dt-test-datatype", description = "I am test",
+ version = "1.0.0", derivedFrom = "tosca.datatypes.root"
+)
+data class TestBluePrintsDataType(
+ @BluePrintsProperty(description = "this stringData")
+ var stringData: String,
+ @BluePrintsProperty(description = "this stringDataWithValue")
+ @PropertyDefaultValue(value = "USA")
+ val stringDataWithValue: String,
+ @BluePrintsProperty(description = "this intDataWithValue")
+ @PropertyDefaultValue(value = "30")
+ val intDataWithValue: Int,
+ @BluePrintsProperty(description = "this booleanDataWithValue")
+ @PropertyDefaultValue(value = "true")
+ val booleanDataWithValue: Boolean,
+ @BluePrintsProperty(description = "this anyData")
+ val anyData: Any,
+ @BluePrintsProperty(description = "this jsonDataWithValue")
+ @PropertyDefaultValue(value = """{"data" : "1234"}""")
+ val jsonDataWithValue: JsonNode?,
+ @BluePrintsProperty(description = "listData")
+ val listData: MutableList<String>,
+ @BluePrintsProperty(description = "this mapData")
+ val mapData: MutableMap<String, String> = hashMapOf(),
+ @BluePrintsProperty(description = "this complexData")
+ val complexData: TestBluePrintsChildDataType?,
+ @BluePrintsProperty(description = "this complexDataList")
+ val complexDataList: MutableList<TestBluePrintsChildDataType>
+)
+
+data class TestBluePrintsChildDataType(val name: String)
+
+@BluePrintsWorkflowInput
+data class TestBluePrintsWorkflowInput(
+ @BluePrintsProperty(description = "this sample name")
+ @PropertyDefaultValue(value = "Brinda")
+ var name: String,
+ @BluePrintsProperty(description = "this sample name")
+ val place: String
+)
+
+@BluePrintsWorkflowOutput
+data class TestBluePrintsWorkflowOutput(
+ @BluePrintsProperty(description = "this is dslExpression")
+ @DSLExpression("field1")
+ var dslExpression: String,
+
+ @BluePrintsProperty(description = "this is withNodeAttributeExpression")
+ @AttributeExpression(modelableEntityName = "sample-node", attributeName = "response-data")
+ var withNodeAttributeExpression: String,
+
+ @BluePrintsProperty(description = "this is withNodeAttributeExpressionSubAttribute")
+ @AttributeExpression(
+ modelableEntityName = "sample-node", attributeName = "response-data",
+ subAttributeName = ".\$field1"
+ )
+ var withNodeAttributeExpressionSubAttribute: String,
+
+ @BluePrintsProperty(description = "this is withAttributeExpressionSubAttribute")
+ @AttributeExpression(attributeName = "response-data", subAttributeName = ".\$field1")
+ var withAttributeExpressionSubAttribute: String,
+
+ @BluePrintsProperty(description = "this is withAttributeExpression")
+ @AttributeExpression(attributeName = "response-data")
+ var withAttributeExpression: String,
+
+ @BluePrintsProperty(description = "this is withAArtifactExpression")
+ @ArtifactExpression(modelableEntityName = "test-node", artifactName = "content-template")
+ var withAArtifactExpression: String,
+
+ @BluePrintsProperty(description = "this status")
+ val status: String = "success"
+)
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt
new file mode 100644
index 000000000..c2d764bd6
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/dsl/BluePrintDSLTest.kt
@@ -0,0 +1,292 @@
+/*
+ * 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"}""")
+ 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())
+ }
+ }
+ }
+ }
+ }
+
+ 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)")
+ // println(serviceTemplate.asJsonString(true))
+ }
+
+ @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<TestProperty, TestInput, TestOutput>(
+ id, "component-test-executor",
+ "ComponentTestExecutor",
+ description
+ )
+
+class TestProperty : PropertiesAssignmentBuilder() {
+ fun prop1(prop1: String) {
+ property("prop1", prop1.asJsonPrimitive())
+ }
+
+ fun prop2(prop2: String) {
+ property("prop2", prop2.asJsonPrimitive())
+ }
+}
+
+class TestInput : PropertiesAssignmentBuilder() {
+ fun request(request: String) {
+ property("request", request.asJsonPrimitive())
+ }
+}
+
+class TestOutput : PropertiesAssignmentBuilder() {
+ fun response(response: String) {
+ response(response.asJsonPrimitive())
+ }
+
+ fun response(response: JsonNode) {
+ property("response", response)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt
new file mode 100644
index 000000000..60bef8a8d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/scripts/BluePrintScriptsServiceImplTest.kt
@@ -0,0 +1,87 @@
+/*
+ * 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<BluePrintDefinitions>(
+ 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>("datatype-custom-datatype")
+ assertNotNull(customDataType, "failed to get custom definitions")
+
+ val instance = bluePrintScriptsService
+ .scriptInstance<BlueprintFunctionNode<String, String>>(
+ basePath,
+ "cba.scripts.SampleBlueprintFunctionNode", false
+ )
+ assertNotNull(instance, "failed to get compiled instance")
+
+ val cachedInstance = bluePrintScriptsService
+ .scriptInstance<BlueprintFunctionNode<String, String>>(
+ basePath,
+ "cba.scripts.SampleBlueprintFunctionNode", false
+ )
+ assertNotNull(cachedInstance, "failed to get cached compile instance")
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt
new file mode 100644
index 000000000..597194c29
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintContextTest.kt
@@ -0,0 +1,583 @@
+/*
+ * 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 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() {
+ val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(blueprintBasePath)
+ assertNotNull(bluePrintContext, "Failed to populate Blueprint context")
+ }
+
+ @Test
+ fun testChainedProperty() {
+ 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..f8cad990d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintExpressionServiceTest.kt
@@ -0,0 +1,140 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.service
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
+import org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ExpressionData
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+
+/**
+ *
+ *
+ * @author Brinda Santh
+ */
+class BluePrintExpressionServiceTest {
+
+ @Test
+ fun testInputExpression() {
+ val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_input\" : \"input-name\" }")
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.inputExpression, " Failed to populate input expression data")
+ assertEquals("input-name", expressionData.inputExpression?.propertyName, "Failed to get propertyName from expression data")
+ }
+
+ @Test
+ fun testPropertyExpression() {
+ val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"property-name\"] }")
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.propertyExpression, " Failed to populate property expression data")
+ assertEquals("SELF", expressionData.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("property-name", expressionData.propertyExpression?.propertyName, " Failed to get expected propertyName")
+
+ val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_property\" : [\"SELF\", \"\",\"property-name\", \"resource\", \"name\"] }")
+ val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1)
+ assertNotNull(expressionData1, " Failed to populate expression data")
+ assertEquals(expressionData1.isExpression, true, "Failed to identify as nested property expression")
+ assertNotNull(expressionData1.propertyExpression, " Failed to populate nested property expression data")
+ assertEquals("SELF", expressionData1.propertyExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("property-name", expressionData1.propertyExpression?.propertyName, " Failed to get expected propertyName")
+ assertEquals(
+ "resource/name",
+ expressionData1.propertyExpression?.subPropertyName,
+ " Failed to populate nested subPropertyName expression data"
+ )
+ }
+
+ @Test
+ fun testAttributeExpression() {
+ val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"resource\"] }")
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.attributeExpression, " Failed to populate attribute expression data")
+ assertEquals("SELF", expressionData.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("resource", expressionData.attributeExpression?.attributeName, " Failed to get expected attributeName")
+
+ val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_attribute\" : [\"SELF\", \"\",\"attribute-name\", \"resource\", \"name\"] }")
+ val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1)
+ assertNotNull(expressionData1, " Failed to populate expression data")
+ assertEquals(expressionData1.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData1.attributeExpression, " Failed to populate attribute expression data")
+ assertEquals("SELF", expressionData1.attributeExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("attribute-name", expressionData1.attributeExpression?.attributeName, " Failed to get expected attributeName")
+ assertEquals(
+ "resource/name",
+ expressionData1.attributeExpression?.subAttributeName,
+ " Failed to populate nested subAttributeName expression data"
+ )
+ }
+
+ @Test
+ fun testOutputOperationExpression() {
+ val node: JsonNode =
+ jacksonObjectMapper().readTree("{ \"get_operation_output\": [\"SELF\", \"interface-name\", \"operation-name\", \"output-property-name\"] }")
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.operationOutputExpression, " Failed to populate output expression data")
+ assertEquals("SELF", expressionData.operationOutputExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("interface-name", expressionData.operationOutputExpression?.interfaceName, " Failed to get expected interfaceName")
+ assertEquals("operation-name", expressionData.operationOutputExpression?.operationName, " Failed to get expected operationName")
+ assertEquals("output-property-name", expressionData.operationOutputExpression?.propertyName, " Failed to get expected propertyName")
+ }
+
+ @Test
+ fun testArtifactExpression() {
+ val node: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\"] }")
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.artifactExpression, " Failed to populate Artifact expression data")
+ assertEquals("SELF", expressionData.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("artifact-template", expressionData.artifactExpression?.artifactName, " Failed to get expected artifactName")
+
+ val node1: JsonNode = jacksonObjectMapper().readTree("{ \"get_artifact\" : [\"SELF\", \"artifact-template\", \"location\", true] }")
+ val expressionData1: ExpressionData = BluePrintExpressionService.getExpressionData(node1)
+ assertNotNull(expressionData1, " Failed to populate expression data")
+ assertEquals(expressionData1.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData1.artifactExpression, " Failed to populate Artifact expression data")
+ assertEquals("SELF", expressionData1.artifactExpression?.modelableEntityName, " Failed to get expected modelableEntityName")
+ assertEquals("artifact-template", expressionData1.artifactExpression?.artifactName, " Failed to get expected artifactName")
+ assertEquals("location", expressionData1.artifactExpression?.location, " Failed to get expected location")
+ assertEquals(true, expressionData1.artifactExpression?.remove, " Failed to get expected remove")
+ }
+
+ @Test
+ fun testDSLExpression() {
+ val node: JsonNode = "*dynamic-rest-source".asJsonPrimitive()
+ val expressionData: ExpressionData = BluePrintExpressionService.getExpressionData(node)
+ assertNotNull(expressionData, " Failed to populate expression data")
+ assertEquals(expressionData.isExpression, true, "Failed to identify as expression")
+ assertNotNull(expressionData.dslExpression, " Failed to populate dsl expression data")
+ assertEquals(
+ "dynamic-rest-source", expressionData.dslExpression!!.propertyName,
+ " Failed to populate dsl property name"
+ )
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt
new file mode 100644
index 000000000..265175165
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRepoFileServiceTest.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.service
+
+import org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants
+import kotlin.test.assertNotNull
+
+/**
+ * BluePrintRepoFileServiceTest
+ * @author Brinda Santh
+ *
+ */
+class BluePrintRepoFileServiceTest {
+
+ private val basePath = TestConstants.PATH_TEST_DEFINITION_TYPE_STARTER
+ private val bluePrintRepoFileService = BluePrintRepoFileService(basePath)
+
+ @Test
+ fun testGetDataType() {
+ val dataType = bluePrintRepoFileService.getDataType("dt-v4-aggregate")
+ assertNotNull(dataType, "Failed to get DataType from repo")
+ }
+
+ @Test
+ fun testGetNodeType() {
+ val nodeType = bluePrintRepoFileService.getNodeType("component-resource-resolution")
+ assertNotNull(nodeType, "Failed to get NodeType from repo")
+ }
+
+ @Test
+ fun testGetArtifactType() {
+ val nodeType = bluePrintRepoFileService.getArtifactType("artifact-template-velocity")
+ assertNotNull(nodeType, "Failed to get ArtifactType from repo")
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testModelNotFound() {
+ val dataType = bluePrintRepoFileService.getDataType("dt-not-found")
+ assertNotNull(dataType, "Failed to get DataType from repo")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt
new file mode 100644
index 000000000..dea46224d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintRuntimeServiceTest.kt
@@ -0,0 +1,207 @@
+/*
+ * 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.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<String, JsonNode> = bluePrintRuntimeService
+ .resolveNodeTemplateProperties("activate-process")
+
+ assertNotNull(propContext, "Failed to populate interface property values")
+ }
+
+ @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<String, JsonNode> = 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")
+ }
+
+ private fun getBluePrintRuntimeService(): BluePrintRuntimeService<MutableMap<String, JsonNode>> {
+ val blueprintBasePath = normalizedPathName(TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG)
+ val blueprintRuntime = BluePrintMetadataUtils.getBluePrintRuntime("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..e525bfc27
--- /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.getBluePrintRuntime("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<String, Any> = 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..72fa3e1eb
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/service/BluePrintWorkflowServiceTest.kt
@@ -0,0 +1,271 @@
+/*
+ * 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<BluePrintRuntimeService<*>>()
+ every { bluePrintRuntimeService.id() } returns id
+ return bluePrintRuntimeService
+ }
+
+ private fun prepareSimulation(successes: List<String>?, failures: List<String>?): MutableMap<String, EdgeLabel> {
+ val simulatedState: MutableMap<String, EdgeLabel> = hashMapOf()
+ successes?.forEach {
+ simulatedState[it] = EdgeLabel.SUCCESS
+ }
+ failures?.forEach {
+ simulatedState[it] = EdgeLabel.FAILURE
+ }
+ return simulatedState
+ }
+}
+
+class TestBluePrintWorkFlowService :
+ AbstractBluePrintWorkFlowService<String, String>() {
+
+ val log = logger(TestBluePrintWorkFlowService::class)
+
+ lateinit var simulatedState: MutableMap<String, EdgeLabel>
+
+ 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<String>()
+ 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<String, String> {
+ 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<String, String> {
+ val nodeOutput = ""
+ return NodeSkipMessage(node, "$node Skip Input", nodeOutput)
+ }
+
+ override suspend fun skipNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ return simulatedState[node.id] ?: throw BluePrintException("failed to get status for the node($node)")
+ }
+
+ override suspend fun cancelNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun restartNode(
+ node: Graph.Node,
+ nodeInput: String,
+ nodeOutput: String
+ ): EdgeLabel {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun prepareWorkflowOutput(): String {
+ if (exceptions.isNotEmpty()) {
+ exceptions.forEach {
+ log.error("workflow($workflowId) exceptions :", it)
+ }
+ }
+ return "Final Response"
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt
new file mode 100644
index 000000000..6e19656ec
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintFileUtilsTest.kt
@@ -0,0 +1,57 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.utils
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.TestConstants
+import java.io.File
+import java.nio.file.Paths
+import kotlin.test.assertTrue
+
+class BluePrintFileUtilsTest {
+
+ @Test
+ fun testNewBlueprint() = runBlocking {
+ val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-new-test")
+ BluePrintFileUtils.createEmptyBluePrint(targetPath)
+ }
+
+ @Test
+ fun testBlueprintCopy() = runBlocking {
+ val sourcePath = TestConstants.PATH_TEST_BLUEPRINTS_BASECONFIG
+
+ val targetPath: String = Paths.get("target").toUri().toURL().path.plus("/bp-copy-test")
+
+ val targetDir = File(targetPath)
+ targetDir.deleteOnExit()
+ // Copy the BP file
+ BluePrintFileUtils.copyBluePrint(sourcePath, targetDir.absolutePath)
+
+ assertTrue(targetDir.exists(), "faield to copy blueprint to ${targetDir.absolutePath}")
+
+ // Delete Type Files
+ BluePrintFileUtils.deleteBluePrintTypes(targetDir.absolutePath)
+
+ // Generate the Type Files
+ val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext(sourcePath)
+ bluePrintContext.rootPath = targetDir.absolutePath
+
+ BluePrintFileUtils.writeBluePrintTypes(bluePrintContext)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt
new file mode 100644
index 000000000..62bb0afcb
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintIOUtilsTest.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.utils
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintRetryException
+
+class BluePrintIOUtilsTest {
+
+ @Test
+ fun testRetry() {
+ runBlocking {
+ val executionBlock: suspend (Int) -> String = { count: Int ->
+ "success"
+ }
+ val exceptionBlock = { e: Exception ->
+ if (e is BluePrintRetryException) {
+ println("this is blueprint error")
+ } else {
+ throw e
+ }
+ }
+ BluePrintIOUtils.retry<String>(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..302daf67e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/BluePrintMetadataUtilsTest.kt
@@ -0,0 +1,80 @@
+/*
+ * 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() {
+ 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/JacksonReactorUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtilsTest.kt
new file mode 100644
index 000000000..aa4008759
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonReactorUtilsTest.kt
@@ -0,0 +1,42 @@
+/*
+ * 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.slf4j.LoggerFactory
+
+class JacksonReactorUtilsTest {
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
+
+ @Test
+ fun testJsonNodeFromClassPathFile() {
+ runBlocking {
+ val filePath = "data/default-context.json"
+ JacksonReactorUtils.jsonNodeFromClassPathFile(filePath)
+ }
+ }
+
+ @Test
+ fun testJsonNodeFromFile() {
+ runBlocking {
+ val filePath = "src/test/resources/data/default-context.json"
+ JacksonReactorUtils.jsonNodeFromFile(filePath)
+ }
+ }
+}
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
new file mode 100644
index 000000000..5facad7ef
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JacksonUtilsTest.kt
@@ -0,0 +1,74 @@
+/*
+ * 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 org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.slf4j.LoggerFactory
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+
+/**
+ * JacksonUtilsTest
+ * @author Brinda Santh
+ * ${DATA}
+ */
+class JacksonUtilsTest {
+
+ private val log = LoggerFactory.getLogger(this::class.toString())
+
+ @Test
+ fun testJsonNodeFromClassPathFile() {
+ val filePath = "data/default-context.json"
+ JacksonUtils.jsonNodeFromClassPathFile(filePath)
+ }
+
+ @Test
+ fun testJsonNodeFromFile() {
+ val filePath = "src/test/resources/data/default-context.json"
+ JacksonUtils.jsonNodeFromFile(filePath)
+ }
+
+ @Test
+ fun testGetListFromJson() {
+ val content = "[\"good\",\"boy\" ]"
+ val nodeType = JacksonUtils.getListFromJson(content, String::class.java)
+ assertNotNull(nodeType, "Failed to get String array from content")
+ }
+
+ @Test
+ fun testJsonValue() {
+ val filePath = "data/alltype-data.json"
+ 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")
+ val floatValue = rootJson.get("floatValue")
+ 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")
+ val booleanValue = rootJson.get("booleanValue")
+ 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")
+ 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_LIST, stringValue), "Negative type failed")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtilsTest.kt
new file mode 100644
index 000000000..336e47604
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/JsonParserUtilsTest.kt
@@ -0,0 +1,58 @@
+/*
+ * 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 org.junit.Test
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPaths
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+
+class JsonParserUtilsTest {
+
+ @Test
+ fun `test parse Node`() {
+ val dataNode = JacksonUtils.jsonNodeFromClassPathFile("data/default-context.json")
+
+ val parsedNode = dataNode.jsonPathParse("$.request-id")
+
+ assertEquals(parsedNode, "12345".asJsonPrimitive(), "failed to parse json request-id")
+ }
+
+ @Test
+ fun testPaths() {
+ val json: String = """
+ {
+ "data" : {
+ "prop1" : "1234"
+ },
+ "data2" : {
+ "prop1" : "12345"
+ },
+ "data3" : [{
+ "prop1" : "12345"
+ }
+ ]
+ }
+ """.trimIndent()
+ val jsonNode = json.jsonAsJsonType()
+ val parsedPath = jsonNode.jsonPaths("$..prop1")
+ assertNotNull(parsedPath, "failed to get parsed path")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtilsTest.kt
new file mode 100644
index 000000000..fc11947de
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/TopologicalSortingUtilsTest.kt
@@ -0,0 +1,38 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.core.utils
+
+import org.junit.Test
+import org.slf4j.LoggerFactory
+
+class TopologicalSortingUtilsTest {
+
+ private val log = LoggerFactory.getLogger(TopologicalSortingUtilsTest::class.java)
+ @Test
+ fun testSorting() {
+ val graph: TopologicalSortingUtils<String> = TopologicalSortingUtils()
+ graph.add("bundle-id", "bundle-mac")
+ graph.add("bundle-id", "bundle-ip")
+ graph.add("bundle-mac", "bundle-ip")
+ graph.add("bundle-ip", "bundle-mac")
+
+ log.debug("The current graph: $graph")
+ log.debug("In-degrees: " + graph.inDegree())
+ log.debug("Out-degrees: " + graph.outDegree())
+ log.debug("A topological sort of the vertices: " + graph.topSort())
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtilsTest.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtilsTest.kt
new file mode 100644
index 000000000..66272d61a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/core/utils/WorkflowGraphUtilsTest.kt
@@ -0,0 +1,42 @@
+/*
+ * 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 org.onap.ccsdk.cds.controllerblueprints.core.dsl.workflow
+import kotlin.test.Test
+import kotlin.test.assertNotNull
+
+class WorkflowGraphUtilsTest {
+
+ @Test
+ fun testWorkFlowToGraph() {
+
+ val workflow = workflow("sample", "") {
+ step("A", "A", "") {
+ success("B")
+ }
+ step("B", "B", "") {
+ success("C")
+ failure("D")
+ }
+ step("C", "C", "")
+ step("D", "D", "")
+ }
+ val graph = WorkflowGraphUtils.workFlowToGraph(workflow)
+ assertNotNull(graph, "failed to create graph")
+ }
+}
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
new file mode 100644
index 000000000..5dd1937f8
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/ActivateBlueprintDefinitions.kt
@@ -0,0 +1,57 @@
+/*
+ * 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 cba.scripts
+
+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
+
+class ActivateBlueprintDefinitions : AbstractBluePrintDefinitions() {
+
+ override fun serviceTemplate(): ServiceTemplate {
+
+ return serviceTemplate(
+ "sample-blue-print", "1.0.0",
+ "brindasanth@onap.com", "sample, blueprints"
+ ) {
+ topologyTemplate {
+ workflowNodeTemplate("activate", "component-resource-resolution", "") {
+ operation("ResourceResolutionExecutor", "") {
+ inputs {
+ property("string-value", "sample")
+ }
+ }
+ }
+ }
+ }
+ }
+
+ override fun loadOtherDefinitions() {
+ /** Sample Definitions */
+ val customDataType = dataType(
+ "custom-datatype", "1.0.0",
+ BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT, ""
+ ) {
+ 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-core/src/test/resources/compile/Scripts/kotlin/SampleBlueprintFunctionNode.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/SampleBlueprintFunctionNode.kt
new file mode 100644
index 000000000..8bd060e17
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/Scripts/kotlin/SampleBlueprintFunctionNode.kt
@@ -0,0 +1,66 @@
+/*
+ * 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 cba.scripts
+
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
+
+open class SampleBlueprintFunctionNode : BlueprintFunctionNode<String, String> {
+
+ override fun getName(): String {
+ return "Kotlin-Script-Function-Node"
+ }
+
+ override fun prepareRequest(executionRequest: String): String {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun process(executionRequest: String) {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun recover(runtimeException: RuntimeException, executionRequest: String) {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun prepareResponse(): String {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override fun apply(t: String): String {
+ return "$t-status"
+ }
+
+ override suspend fun prepareRequestNB(executionRequest: String): String {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun processNB(executionRequest: String) {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: String) {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun prepareResponseNB(): String {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+
+ override suspend fun applyNB(t: String): String {
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/TOSCA-Metadata/TOSCA.meta b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/TOSCA-Metadata/TOSCA.meta
new file mode 100644
index 000000000..b1ffabd13
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/compile/TOSCA-Metadata/TOSCA.meta
@@ -0,0 +1,7 @@
+TOSCA-Meta-File-Version: 1.0.0
+CSAR-Version: 1.0
+Created-By: Brinda Santh <brindasanth@in.ibm.com>
+Entry-Definitions: cba.scripts.ActivateBlueprintDefinitions.kt
+Template-Tags: Brinda Santh, activation-blueprint
+Template-Name: activate-blueprint
+Template-Version: 1.0.0
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/componentnode/default.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/componentnode/default.json
new file mode 100644
index 000000000..a1982631b
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/componentnode/default.json
@@ -0,0 +1,100 @@
+{
+ "metadata": {
+ "template_author": "bs2796",
+ "vendor": "Juniper",
+ "os": "XXX",
+ "service-type": "AVPN",
+ "vnf-type": "VRR",
+ "action": "Base Configuration",
+ "sub-action": "Generate Configuration",
+ "template_name": "VRR-baseconfiguration",
+ "template_version": "1.0.0"
+ },
+ "topology_template": {
+ "inputs": {
+ "service-instance-id": {
+ "required": true,
+ "type": "string"
+ },
+ "vnf-id": {
+ "required": true,
+ "type": "string"
+ },
+ "service": {
+ "required": true,
+ "type": "string"
+ },
+ "region": {
+ "required": true,
+ "type": "string"
+ },
+ "bundle-id": {
+ "required": true,
+ "type": "string"
+ },
+ "bundle-mac": {
+ "required": true,
+ "type": "string"
+ }
+ },
+ "node_templates": {
+ "generate-configuration": {
+ "type": "mock-component-generateConfig",
+ "interfaces": {
+ "org-onap-ccsdk-config-params-service-MockComponentNode": {
+ "operations": {
+ "process": {
+ "inputs": {
+ "entity-type": "vnf-type",
+ "template-content": "sample-template",
+ "entity-id": { "get_input" : "vnf-id" }
+ },
+ "outputs": {
+ "mergedData": "merged Data",
+ "status": "status"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "node_types": {
+ "mock-component-generateConfig": {
+ "interfaces": {
+ "org-onap-ccsdk-config-params-service-MockComponentNode": {
+ "operations": {
+ "process": {
+ "inputs": {
+ "entity-type": {
+ "required": false,
+ "type": "string"
+ },
+ "template-content": {
+ "required": false,
+ "type": "string"
+ },
+ "entity-id": {
+ "required": true,
+ "type": "string"
+ }
+ },
+ "outputs": {
+ "generated-config": {
+ "required": true,
+ "type": "string"
+ },
+ "status": {
+ "required": true,
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "derived_from": "tosca.nodes.Component"
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/alltype-data.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/alltype-data.json
new file mode 100644
index 000000000..055b09658
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/alltype-data.json
@@ -0,0 +1,10 @@
+{
+ "intValue" : 1,
+ "floatValue" : 1.34,
+ "booleanValue" : true,
+ "stringValue" : "sample-String",
+ "timeValue" : "2018-09-29",
+ "arrayStringValue" : ["one", "two"],
+ "mapValue" : {"profile_name1":"profile_name1",
+ "profile_name2":"profile_name2"}
+} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/default-context.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/default-context.json
new file mode 100644
index 000000000..9f733f0fd
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/data/default-context.json
@@ -0,0 +1,7 @@
+{
+ "request-id": "12345",
+ "hostname": "localhost",
+ "template_name": "baseconfiguration",
+ "template_version": "1.0.0",
+ "action-name": "sample-action"
+} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/dictionary/dictionary_schema.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/dictionary/dictionary_schema.json
new file mode 100644
index 000000000..b7340f336
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/dictionary/dictionary_schema.json
@@ -0,0 +1,299 @@
+{
+ "type": "object",
+ "properties": {
+ "resource-path": {
+ "type": "string",
+ "required": true
+ },
+ "description": {
+ "type": "string"
+ },
+ "updated-by": {
+ "type": "string"
+ },
+ "data-type": {
+ "type": "string",
+ "required": true
+ },
+ "source": {
+ "type": "object",
+ "required": true,
+ "properties": {
+ "input": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string"
+ }
+ }
+ },
+ "component": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "required": true
+ },
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "default": {
+ "type": "any"
+ },
+ "aai-data": {
+ "type": "object",
+ "properties": {
+ "verb": {
+ "type": "string",
+ "required": true
+ },
+ "path": {
+ "type": "string",
+ "required": true
+ },
+ "url-path": {
+ "type": "string",
+ "required": true
+ },
+ "payload": {
+ "type": "string",
+ "required": false
+ },
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "type": {
+ "type": "string",
+ "required": true
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "base": {
+ "type": "string",
+ "required": true
+ }
+ }
+ },
+ "sdnc": {
+ "type": "object",
+ "properties": {
+ "path": {
+ "type": "string",
+ "required": true
+ },
+ "url-path": {
+ "type": "string",
+ "required": true
+ },
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "type": {
+ "type": "string",
+ "required": true
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "base": {
+ "type": "string",
+ "required": true
+ }
+ }
+ },
+ "network-resource-discovery": {
+ "type": "object",
+ "properties": {
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "processor-db": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "required": true
+ },
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "type": {
+ "type": "string",
+ "required": true
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "base": {
+ "type": "string",
+ "required": true
+ }
+ }
+ },
+ "policy": {
+ "type": "object",
+ "properties": {
+ "input-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "output-key-mapping": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "candidate-dependency": {
+ "type": "object",
+ "properties": {
+ "input": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "component": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "aai-data": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "sdnc": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "network-resource-discovery": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "processor-db": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "policy": {
+ "type": "object",
+ "properties": {
+ "names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
+ "tags": {
+ "type": "string"
+ },
+ "default": {
+ "type": "any"
+ },
+ "name": {
+ "type": "string",
+ "required": true
+ },
+ "valid-values": {
+ "type": "string"
+ },
+ "resource-type": {
+ "type": "string",
+ "required": true
+ },
+ "sample-value": {
+ "type": "string"
+ },
+ "entry-schema": {
+ "type": "string"
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment1.properties b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment1.properties
new file mode 100644
index 000000000..d735087bb
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment1.properties
@@ -0,0 +1,2 @@
+blueprintsprocessor.database.alt1.username=username1
+blueprintsprocessor.database.alt1.password=password1 \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment2.properties b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment2.properties
new file mode 100644
index 000000000..5530a8f8a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/environments/Environments/environment2.properties
@@ -0,0 +1,2 @@
+blueprintsprocessor.database.alt2.username=username2
+blueprintsprocessor.database.alt2.password=password2 \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/logback-test.xml
new file mode 100644
index 000000000..83e0bc674
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/logback-test.xml
@@ -0,0 +1,31 @@
+<!--
+ ~ 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.
+ -->
+
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- encoders are assigned the type
+ ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n</pattern>
+ </encoder>
+ </appender>
+
+ <logger name="org.onap.ccsdk.cds.controllerblueprints" level="info"/>
+ <root level="info">
+ <appender-ref ref="STDOUT"/>
+ </root>
+
+</configuration>
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/convert.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/convert.json
new file mode 100644
index 000000000..f7893ce53
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/convert.json
@@ -0,0 +1,36 @@
+{
+ "type": "sdnc-component-getResourceAssignment",
+ "interfaces": {
+ "ResourceAssignmentService": {
+ "operations": {
+ "getResourceAssignment": {
+ "inputs": {
+ "assignment-mappings": [
+ {
+ "name": "service-name",
+ "mapping-field": "service",
+ "mapping-category": "SDN",
+ "required": true
+ },
+ {
+ "name": "region-name",
+ "mapping-field": "region",
+ "mapping-category": "SDN",
+ "required": true
+ }
+ ],
+ "pre-data": {
+ "get_input": "get-resource-assignment.config-params"
+ },
+ "prifix": "get-resource-assignment"
+ },
+ "outputs": {
+ "resource-assignment-status": "success",
+ "resource-assignment-params": "{ \"set_value\" : \"get-resource-assignment.config-params"
+ }
+ }
+ }
+ }
+ }
+}
+
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/default.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/default.json
new file mode 100644
index 000000000..9f17574e7
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/properties/default.json
@@ -0,0 +1,16 @@
+{
+ "default": { "get_input" : "loopback-default" },
+ "domain": "ethernet",
+ "criteria": [
+ {
+ "value": "attga301me1",
+ "type": "complex",
+ "nodeString": "layer3-service-list[].service-data.l3sdn-vnf-fields.vnf-name"
+ },
+ {
+ "value": { "get_input" : "host-ip-address" },
+ "type": "simple",
+ "nodeString": "layer3-service-list[].service-data.l3sdn-vnf-fields.vnf-name"
+ }
+ ]
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-jinja.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-jinja.json
new file mode 100644
index 000000000..ab7abf3d4
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-jinja.json
@@ -0,0 +1,3 @@
+{
+ "occurrence": 2
+} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-velocity.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-velocity.json
new file mode 100755
index 000000000..2acc6fcdd
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-data-velocity.json
@@ -0,0 +1,36 @@
+{
+ "node0_hostname": "sdnc-host",
+ "node0_backup_router_address": "2001:1890:1253::192:168:100:1",
+ "servers": [
+ "Server1",
+ "Server2",
+ "Server3"
+ ],
+ "tacplus-servers": [
+ {
+ "tacplus-server-name": "tacplus-server-name1",
+ "tacplus-server-source-address": "enc-dsdsasa1"
+ },
+ {
+ "tacplus-server-name": "tacplus-server-name2",
+ "tacplus-server-source-address": "enc-dsdsasa2"
+ }
+ ],
+ "classes": [
+ {
+ "name": "superuser-class",
+ "idle-timeout": 5,
+ "permissions": "all"
+ },
+ {
+ "name": "tacacs-adv-class",
+ "idle-timeout": 5
+ },
+ {
+ "name": "tacacs-base-class",
+ "idle-timeout": 5
+ }
+ ],
+ "system-password": "teamops-system-password",
+ "root-password": "teamops-root-password"
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-velocity-template.vtl b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-velocity-template.vtl
new file mode 100755
index 000000000..f7b1269b3
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/base-config-velocity-template.vtl
@@ -0,0 +1,61 @@
+<configuration xmlns="http://xml.juniper.net/xnm/1.1/xnm"
+xmlns:a="http://xml.juniper.net/junos/15.1X49/junos">
+ <version>15.1X49-D50.3</version>
+ <groups>
+ <name>node0</name>
+ <system>
+ #foreach($server in ${servers})
+ <server-host-name>$StringUtils.upperCase("$server")</server-host-name>
+ #end
+ </system>
+ <system>
+ <host-name>${node0_hostname}</host-name>
+ <backup-router>
+ <address>${node0_backup_router_address}</address>
+ <destination>$node0_backup_router_address</destination>
+ </backup-router>
+ #foreach($tacplus-server in ${tacplus-servers})
+ <tacplus-server>
+ <name>$tacplus-server.tacplus-server-name</name>
+ <source-address>$tacplus-server.tacplus-server-source-address</source-address>
+ </tacplus-server>
+ #end
+ <login>
+ <message>ONAP information assets</message>
+ #foreach($class in ${classes})
+ <class>
+ <name>$class.name</name>
+ <idle-timeout>$class.idle-timeout</idle-timeout>
+ #if ($class.permissions)
+ <permissions>$class.permissions</permissions>
+ #end
+ </class>
+ #end
+ <user>
+ <name>readonly</name>
+ <full-name>Read Only Account Access</full-name>
+ <uid>1001</uid>
+ <class>tacacs-base-class</class>
+ </user>
+ <user>
+ <name>readwrite</name>
+ <full-name>Read - Write Account Access</full-name>
+ <uid>1002</uid>
+ <class>tacacs-adv-class</class>
+ <authentication>
+ <encrypted-password>${system-password}</encrypted-password>
+ </authentication>
+ </user>
+ <user>
+ <name>readwrite</name>
+ <full-name>Emergency Access Only</full-name>
+ <uid>1000</uid>
+ <class>superuser-class</class>
+ <authentication>
+ <encrypted-password>${root-password}</encrypted-password>
+ </authentication>
+ </user>
+ </login>
+ </system>
+ </groups>
+</configuration> \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-data.json b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-data.json
new file mode 100755
index 000000000..940ca8d73
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-data.json
@@ -0,0 +1,3 @@
+{
+ "node0_hostname": "sample-hostname"
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-velocity-template.vtl b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-velocity-template.vtl
new file mode 100755
index 000000000..ce2458e2e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/default-variable-value-velocity-template.vtl
@@ -0,0 +1,2 @@
+$node0_hostname
+${node0_backup_router_address} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/interface.jinja b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/interface.jinja
new file mode 100755
index 000000000..93114d90a
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/interface.jinja
@@ -0,0 +1,3 @@
+ <interface-configurations xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-ifmgr-cfg">
+blo
+ </interface-configurations> \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/isis.jinja b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/isis.jinja
new file mode 100644
index 000000000..f46d91330
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/isis.jinja
@@ -0,0 +1,3 @@
+ <isis xmlns="http://cisco.com/ns/yang/Cisco-IOS-XR-clns-isis-cfg">
+blah
+ </isis> \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/master.jinja b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/master.jinja
new file mode 100644
index 000000000..1137b2595
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-core/src/test/resources/templates/master.jinja
@@ -0,0 +1,7 @@
+{%- for i in range(occurrence) %}
+<config>
+{% include "templates/isis.jinja" %}
+{% include "templates/interface.jinja" %}
+</config>
+{{ "]]>]]" if not loop.last }}
+{%- endfor %} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/krotoPlusConfig.asciipb b/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/krotoPlusConfig.asciipb
new file mode 100644
index 000000000..30255b96d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/krotoPlusConfig.asciipb
@@ -0,0 +1,6 @@
+grpc_coroutines {
+ filter { exclude_path: "google/*" }
+}
+grpc_stub_exts {
+ support_coroutines: true
+} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/pom.xml b/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/pom.xml
new file mode 100644
index 000000000..b208cbda5
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-proto/pom.xml
@@ -0,0 +1,114 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprints</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>blueprint-proto</artifactId>
+
+ <name>Controller Blueprints Proto</name>
+ <description>Controller Blueprints Proto</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.github.marcoferrer.krotoplus</groupId>
+ <artifactId>kroto-plus-coroutines</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.xolstice.maven.plugins</groupId>
+ <artifactId>protobuf-maven-plugin</artifactId>
+ <version>0.6.1</version>
+ <configuration>
+ <protocArtifact>
+ com.google.protobuf:protoc:3.10.0:exe:${os.detected.classifier}
+ </protocArtifact>
+ <protoSourceRoot>${project.basedir}/../../../../../components/model-catalog/proto-definition/proto
+ </protoSourceRoot>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>grpc-java</id>
+ <goals>
+ <goal>compile-custom</goal>
+ </goals>
+ <configuration>
+ <pluginId>grpc-java</pluginId>
+ <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
+ </pluginArtifact>
+ </configuration>
+ </execution>
+ <!--
+ <execution>
+ <id>grpc-coroutines</id>
+ <goals>
+ <goal>compile-custom</goal>
+ </goals>
+ <configuration>
+ <pluginId>kroto-plus</pluginId>
+ <pluginArtifact>
+ com.github.marcoferrer.krotoplus:protoc-gen-kroto-plus:${kroto-plus.version}:jar:jvm8
+ </pluginArtifact>
+ <pluginParameter>ConfigPath=${project.basedir}/krotoPlusConfig.asciipb</pluginParameter>
+ </configuration>
+ </execution>
+ -->
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-maven-plugin</artifactId>
+ <version>${kotlin.maven.version}</version>
+ <executions>
+ <execution>
+ <id>compile</id>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ <configuration>
+ <sourceDirs>
+ <sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>
+ <sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>
+ <!--<sourceDir>${project.basedir}/target/generated-sources/protobuf/kroto-plus</sourceDir>-->
+ </sourceDirs>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ <extensions>
+ <extension>
+ <groupId>kr.motd.maven</groupId>
+ <artifactId>os-maven-plugin</artifactId>
+ <version>1.6.2</version>
+ </extension>
+ </extensions>
+ </build>
+</project>
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/pom.xml b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/pom.xml
new file mode 100644
index 000000000..d0072b810
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/pom.xml
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprints</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>blueprint-validation</artifactId>
+
+ <name>Controller Blueprints Validation Service</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>resource-dict</artifactId>
+ </dependency>
+
+ <!--Testing dependencies-->
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-test-junit</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.mockk</groupId>
+ <artifactId>mockk</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlinx</groupId>
+ <artifactId>kotlinx-coroutines-test</artifactId>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt
new file mode 100644
index 000000000..73504314b
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactDefinitionValidatorImpl.kt
@@ -0,0 +1,99 @@
+/*
+ * Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.config.ConfigurableBeanFactory
+import org.springframework.context.annotation.Scope
+import org.springframework.stereotype.Service
+import java.io.File
+
+@Service("default-artifact-definition-validator")
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class BluePrintArtifactDefinitionValidatorImpl(
+ private val bluePrintTypeValidatorService: BluePrintTypeValidatorService
+) : BluePrintArtifactDefinitionValidator {
+
+ private val log = LoggerFactory.getLogger(BluePrintArtifactDefinitionValidatorImpl::class.toString())
+
+ lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
+ lateinit var bluePrintContext: BluePrintContext
+ var paths: MutableList<String> = arrayListOf()
+
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
+
+ this.bluePrintRuntimeService = bluePrintRuntimeService
+ this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
+
+ paths.add(name)
+ val type: String = artifactDefinition.type
+ log.trace("Validation ArtifactDefinition of type {$type}")
+ // Check Artifact Type
+ checkValidArtifactType(name, type)
+
+ val file: String = artifactDefinition.file
+
+ val completePath = bluePrintContext.rootPath.plus(File.separator).plus(file)
+
+ check(File(completePath).exists()) {
+ throw BluePrintException("couldn't find file ($completePath)")
+ }
+
+ // Perform Extension Validation
+ validateExtension("$type-artifact-definition-validator", name, artifactDefinition)
+
+ paths.removeAt(paths.lastIndex)
+ }
+
+ open fun checkValidArtifactType(artifactDefinitionName: String, artifactTypeName: String) {
+
+ val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName)
+ ?: throw BluePrintException("failed to get artifactType($artifactTypeName) for ArtifactDefinition($artifactDefinitionName)")
+
+ checkValidArtifactTypeDerivedFrom(artifactTypeName, artifactType.derivedFrom)
+ }
+
+ @Throws(BluePrintException::class)
+ open fun checkValidArtifactTypeDerivedFrom(artifactTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validArtifactTypeDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException("failed to get artifactType($artifactTypeName)'s derivedFrom($derivedFrom) definition")
+ }
+ }
+
+ private fun validateExtension(referencePrefix: String, name: String, artifactDefinition: ArtifactDefinition) {
+
+ val customValidators = bluePrintTypeValidatorService
+ .bluePrintValidators(referencePrefix, BluePrintArtifactDefinitionValidator::class.java)
+
+ customValidators?.let {
+ it.forEach { validator ->
+ validator.validate(bluePrintRuntimeService, name, artifactDefinition)
+ }
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt
new file mode 100644
index 000000000..b31211e2d
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintArtifactTypeValidatorImpl.kt
@@ -0,0 +1,36 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.springframework.stereotype.Service
+
+@Service("default-artifact-type-validator")
+open class BluePrintArtifactTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintArtifactTypeValidator {
+
+ override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactType: ArtifactType) {
+
+ artifactType.properties?.let {
+ bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, artifactType.properties!!)
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt
new file mode 100644
index 000000000..9a4650104
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintAttributeDefinitionValidatorImpl.kt
@@ -0,0 +1,92 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.data.AttributeDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.format
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.config.ConfigurableBeanFactory
+import org.springframework.context.annotation.Scope
+import org.springframework.stereotype.Service
+
+@Service("default-attribute-definition-validator")
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class BluePrintAttributeDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintAttributeDefinitionValidator {
+
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+
+ lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
+
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ attributeDefinition: AttributeDefinition
+ ) {
+
+ log.trace("Validating AttributeDefinition($name)")
+ this.bluePrintRuntimeService = bluePrintRuntimeService
+ val dataType: String = attributeDefinition.type
+
+ when {
+ BluePrintTypes.validPrimitiveTypes().contains(dataType) -> {
+ // Do Nothing
+ }
+ BluePrintTypes.validComplexTypes().contains(dataType) -> {
+ // Do Nothing
+ }
+ BluePrintTypes.validCollectionTypes().contains(dataType) -> {
+ val entrySchemaType: String = attributeDefinition.entrySchema?.type
+ ?: throw BluePrintException("Entry schema for DataType ($dataType) for the property ($name) not found")
+ checkPrimitiveOrComplex(entrySchemaType, name)
+ }
+ else -> checkPropertyDataType(dataType, name)
+ }
+ }
+
+ private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
+ if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) {
+ return true
+ } else {
+ throw BluePrintException("DataType($dataType) for the attribute($propertyName) is not valid")
+ }
+ }
+
+ private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
+
+ val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName)
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+
+ checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
+ }
+
+ private fun checkDataType(key: String): Boolean {
+ return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false
+ }
+
+ open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException("Failed to get DataType($dataTypeName)'s derivedFrom($derivedFrom) definition ")
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt
new file mode 100644
index 000000000..dab6a78bc
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDataTypeValidatorImpl.kt
@@ -0,0 +1,35 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.springframework.stereotype.Service
+
+@Service("default-data-type-validator")
+open class BluePrintDataTypeValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : BluePrintDataTypeValidator {
+
+ override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, dataType: DataType) {
+ dataType.properties?.let {
+
+ bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, dataType.properties!!)
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorService.kt
new file mode 100644
index 000000000..5df2decdb
--- /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 fun validateBluePrints(basePath: String): Boolean {
+
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(UUID.randomUUID().toString(), basePath)
+ return validateBluePrints(bluePrintRuntimeService)
+ }
+
+ override 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..2dfc09be6
--- /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<String> = 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<String, ArtifactDefinition>) {
+ 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..5384744ee
--- /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<String> = 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<String, InterfaceDefinition>) {
+ 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<String, OperationDefinition>) {
+ paths.add("operations")
+ operations.forEach { opertaionName, operationDefinition ->
+ paths.add(opertaionName)
+ operationDefinition.implementation?.let { validateImplementation(operationDefinition.implementation!!) }
+
+ operationDefinition.inputs?.let {
+ bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.inputs!!)
+ }
+
+ operationDefinition.outputs?.let {
+ bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, operationDefinition.outputs!!)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ open fun validateImplementation(implementation: Implementation) {
+ checkNotEmpty(implementation.primary) { "couldn't get implementation" }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt
new file mode 100644
index 000000000..5683c0170
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintPropertyDefinitionValidatorImpl.kt
@@ -0,0 +1,89 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.format
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.config.ConfigurableBeanFactory
+import org.springframework.context.annotation.Scope
+import org.springframework.stereotype.Service
+
+@Service("default-property-definition-validator")
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class BluePrintPropertyDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintPropertyDefinitionValidator {
+
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+
+ lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
+
+ override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, propertyDefinition: PropertyDefinition) {
+ this.bluePrintRuntimeService = bluePrintRuntimeService
+
+ log.trace("Validating PropertyDefinition($name)")
+
+ val dataType: String = propertyDefinition.type
+
+ when {
+ BluePrintTypes.validPrimitiveTypes().contains(dataType) -> {
+ // Do Nothing
+ }
+ BluePrintTypes.validComplexTypes().contains(dataType) -> {
+ // Do Nothing
+ }
+ BluePrintTypes.validCollectionTypes().contains(dataType) -> {
+ val entrySchemaType: String = propertyDefinition.entrySchema?.type
+ ?: throw BluePrintException(format("Entry schema for DataType ({}) for the property ({}) not found", dataType, name))
+ checkPrimitiveOrComplex(entrySchemaType, name)
+ }
+ else -> checkPropertyDataType(dataType, name)
+ }
+ }
+
+ private fun checkPrimitiveOrComplex(dataType: String, propertyName: String): Boolean {
+ if (BluePrintTypes.validPrimitiveTypes().contains(dataType) || checkDataType(dataType)) {
+ return true
+ } else {
+ throw BluePrintException(format("DataType({}) for the property({}) is not valid", dataType, propertyName))
+ }
+ }
+
+ private fun checkPropertyDataType(dataTypeName: String, propertyName: String) {
+
+ val dataType = bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.get(dataTypeName)
+ ?: throw BluePrintException(format("DataType ({}) for the property ({}) not found", dataTypeName, propertyName))
+
+ checkValidDataTypeDerivedFrom(propertyName, dataType.derivedFrom)
+ }
+
+ private fun checkDataType(key: String): Boolean {
+ return bluePrintRuntimeService.bluePrintContext().serviceTemplate.dataTypes?.containsKey(key) ?: false
+ }
+
+ open fun checkValidDataTypeDerivedFrom(dataTypeName: String, derivedFrom: String) {
+ check(BluePrintTypes.validDataTypeDerivedFroms.contains(derivedFrom)) {
+ throw BluePrintException(format("Failed to get DataType({})'s derivedFrom({}) definition ", dataTypeName, derivedFrom))
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintServiceTemplateValidatorImpl.kt
new file mode 100644
index 000000000..d71e78c43
--- /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<String> = 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<String, String>) {
+
+ 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<String, DataType>) {
+
+ 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<String, ArtifactType>) {
+ 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<String, NodeType>) {
+ paths.add(BluePrintConstants.PATH_NODE_TYPES)
+ nodeTypes.forEach { nodeTypeName, nodeType ->
+ // Validate Single Node Type
+ bluePrintTypeValidatorService.validateNodeType(bluePrintRuntimeService, nodeTypeName, nodeType)
+ }
+ paths.removeAt(paths.lastIndex)
+ }
+
+ fun validateTopologyTemplate(topologyTemplate: TopologyTemplate) {
+ paths.add(BluePrintConstants.PATH_TOPOLOGY_TEMPLATE)
+ bluePrintTypeValidatorService.validateTopologyTemplate(bluePrintRuntimeService, "topologyTemplate", topologyTemplate)
+ paths.removeAt(paths.lastIndex)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt
new file mode 100644
index 000000000..a7fb3d57e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTopologyTemplateValidatorImpl.kt
@@ -0,0 +1,76 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.TopologyTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.config.ConfigurableBeanFactory
+import org.springframework.context.annotation.Scope
+import org.springframework.stereotype.Service
+
+@Service("default-topology-template-validator")
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class BluePrintTopologyTemplateValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintTopologyTemplateValidator {
+
+ private val log = LoggerFactory.getLogger(BluePrintServiceTemplateValidatorImpl::class.toString())
+
+ lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
+
+ override fun validate(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, topologyTemplate: TopologyTemplate) {
+ log.trace("Validating Topology Template..")
+ this.bluePrintRuntimeService = bluePrintRuntimeService
+
+ // Validate Inputs
+ topologyTemplate.inputs?.let { validateInputs(topologyTemplate.inputs!!) }
+ // Validate Node Templates
+ topologyTemplate.nodeTemplates?.let { validateNodeTemplates(topologyTemplate.nodeTemplates!!) }
+ // Validate Workflow
+ topologyTemplate.workflows?.let { validateWorkflows(topologyTemplate.workflows!!) }
+ }
+
+ @Throws(BluePrintException::class)
+ fun validateInputs(inputs: MutableMap<String, PropertyDefinition>) {
+ bluePrintTypeValidatorService.validatePropertyDefinitions(bluePrintRuntimeService, inputs)
+ }
+
+ @Throws(BluePrintException::class)
+ fun validateNodeTemplates(nodeTemplates: MutableMap<String, NodeTemplate>) {
+
+ nodeTemplates.forEach { nodeTemplateName, nodeTemplate ->
+ // Validate Single Node Template
+ bluePrintTypeValidatorService.validateNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeTemplate)
+ }
+ }
+
+ @Throws(BluePrintException::class)
+ open fun validateWorkflows(workflows: MutableMap<String, Workflow>) {
+
+ 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..1fb70503f
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintTypeValidatorServiceImpl.kt
@@ -0,0 +1,114 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.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 <T : BluePrintValidator<*>> bluePrintValidator(referenceName: String, classType: Class<T>): T? {
+ return if (context.containsBean(referenceName)) {
+ context.getBean(referenceName, classType)
+ } else {
+ null
+ }
+ }
+
+ override fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>? {
+ return context.getBeansOfType(classType)
+ .filter { it.key.startsWith(referenceNamePrefix) }
+ .mapNotNull { it.value }
+ }
+
+ override fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>? {
+ return context.getBeansOfType(classType).mapNotNull { it.value }
+ }
+
+ override fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintServiceTemplateValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default ServiceTemplate validators")
+ }
+
+ override fun getDataTypeValidators(): List<BluePrintDataTypeValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintDataTypeValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default DataType validators")
+ }
+
+ override fun getArtifactTypeValidators(): List<BluePrintArtifactTypeValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactTypeValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default ArtifactType validators")
+ }
+
+ override fun getArtifactDefinitionsValidators(): List<BluePrintArtifactDefinitionValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintArtifactDefinitionValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default ArtifactDefinition validators")
+ }
+
+ override fun getNodeTypeValidators(): List<BluePrintNodeTypeValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTypeValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default NodeType validators")
+ }
+
+ override fun getTopologyTemplateValidators(): List<BluePrintTopologyTemplateValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintTopologyTemplateValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default TopologyTemplate validators")
+ }
+
+ override fun getNodeTemplateValidators(): List<BluePrintNodeTemplateValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintNodeTemplateValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default NodeTemplate validators")
+ }
+
+ override fun getWorkflowValidators(): List<BluePrintWorkflowValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintWorkflowValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default Workflow validators")
+ }
+
+ override fun getPropertyDefinitionValidators(): List<BluePrintPropertyDefinitionValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintPropertyDefinitionValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default PropertyDefinition validators")
+ }
+
+ override fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator> {
+ return bluePrintValidators(PREFIX_DEFAULT, BluePrintAttributeDefinitionValidator::class.java)
+ ?: throw BluePrintProcessorException("failed to get default AttributeDefinition validators")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt
new file mode 100644
index 000000000..a1a9eb913
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintValidationConfiguration.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright © 2019 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.springframework.context.annotation.ComponentScan
+import org.springframework.context.annotation.Configuration
+
+@Configuration
+@ComponentScan
+open class BluePrintValidationConfiguration
diff --git a/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt
new file mode 100644
index 000000000..a2b598017
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintWorkflowValidatorImpl.kt
@@ -0,0 +1,108 @@
+/*
+ * 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<String> = 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
new file mode 100644
index 000000000..78a5d379e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ArtifactMappingResourceValidator.kt
@@ -0,0 +1,50 @@
+/*
+ * 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.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.utils.JacksonUtils
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.service.ResourceAssignmentValidationServiceImpl
+import org.slf4j.LoggerFactory
+import org.springframework.stereotype.Service
+import java.io.File
+
+@Service("artifact-mapping-resource-artifact-definition-validator")
+open class ArtifactMappingResourceValidator(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) :
+ BluePrintArtifactDefinitionValidator {
+
+ private val log = LoggerFactory.getLogger(ArtifactMappingResourceValidator::class.toString())
+
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ artifactDefinition: ArtifactDefinition
+ ) {
+
+ val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
+ val file: String = artifactDefinition.file
+ val completePath = bluePrintContext.rootPath.plus(File.separator).plus(file)
+ log.trace("Validation artifact-mapping-resource($completePath)")
+ val resourceAssignment = JacksonUtils.getListFromFile(completePath, ResourceAssignment::class.java)
+ val resourceAssignmentValidationService = ResourceAssignmentValidationServiceImpl()
+ resourceAssignmentValidationService.validate(resourceAssignment)
+ }
+}
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
new file mode 100644
index 000000000..dc5da2669
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/extension/ResourceDefinitionValidation.kt
@@ -0,0 +1,46 @@
+/*
+ * 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.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.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<ResourceDefinition>
+
+@Service
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class ResourceDefinitionValidatorImpl(private val bluePrintTypeValidatorService: BluePrintTypeValidatorService) : ResourceDefinitionValidator {
+
+ private val log = LoggerFactory.getLogger(ResourceDefinitionValidatorImpl::class.java)
+
+ override fun validate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ name: String,
+ resourceDefinition: ResourceDefinition
+ ) {
+ log.trace("validating resource definition($name)")
+ resourceDefinition.sources.forEach { name, nodeTemplate ->
+ bluePrintTypeValidatorService.validateNodeTemplate(bluePrintRuntimeService, name, nodeTemplate)
+ }
+ }
+}
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
new file mode 100644
index 000000000..63aa7e537
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/utils/PropertyAssignmentValidationUtils.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright © 2019 IBM.
+ * Modifications Copyright © 2019 Bell Canada.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.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.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.utils.JacksonUtils
+
+open class PropertyAssignmentValidationUtils(private val bluePrintContext: BluePrintContext) {
+
+ // Property Definition holds both Definitons and Expression in same construct
+ open fun validatePropertyDefinitionNAssignments(propertyDefinitions: MutableMap<String, PropertyDefinition>) {
+ propertyDefinitions.forEach { propertyName, propertyDefinition ->
+ validatePropertyDefinitionNAssignment(propertyName, propertyDefinition)
+ }
+ }
+
+ // Property Definition holds both Definitons and Expression in same construct
+ 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)")
+ }
+ val propertyAssignment = propertyDefinition.value!!
+ val expressionData = BluePrintExpressionService.getExpressionData(propertyAssignment)
+ if (!expressionData.isExpression) {
+ checkPropertyValue(propertyName, propertyDefinition, propertyAssignment)
+ }
+ }
+
+ open fun validatePropertyAssignments(
+ nodeTypeProperties: MutableMap<String, PropertyDefinition>,
+ properties: MutableMap<String, JsonNode>
+ ) {
+ properties.forEach { propertyName, propertyAssignment ->
+ val propertyDefinition: PropertyDefinition = nodeTypeProperties[propertyName]
+ ?: throw BluePrintException("validatePropertyAssignments failed to get definition for the property ($propertyName)")
+
+ validatePropertyAssignment(propertyName, propertyDefinition, propertyAssignment)
+ }
+ }
+
+ 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)
+ }
+ }
+
+ 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.validComplexTypes().contains(propertyType)) {
+ isValid = true
+ } 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("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")
+
+ 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 ")
+ }
+ }
+}
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..19d1ef0a4
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/BluePrintDesignTimeValidatorServiceTest.kt
@@ -0,0 +1,108 @@
+/*
+ * 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 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.getBluePrintRuntime("1234", blueprintBasePath)
+ private val mockBluePrintTypeValidatorService = MockBluePrintTypeValidatorService()
+ private val resourceDefinitionValidator = mockk<ResourceDefinitionValidator>()
+ private val defaultBluePrintValidatorService = BluePrintDesignTimeValidatorService(mockBluePrintTypeValidatorService, resourceDefinitionValidator)
+ private val workflowValidator = BluePrintWorkflowValidatorImpl(mockBluePrintTypeValidatorService)
+
+ @Test
+ fun testValidateOfType() {
+ 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<NodeTemplate>()
+ every { nodeTemplate.type } returns "TestNodeType"
+
+ val nodeType = mockk<NodeType>()
+ every { nodeType.derivedFrom } returns "tosca.nodes.TEST"
+
+ val blueprintContext = mockk<BluePrintContext>()
+ every { blueprintContext.nodeTemplateByName(nodeTemplateName) } returns nodeTemplate
+ every { blueprintContext.nodeTemplateNodeType(nodeTemplateName) } returns nodeType
+
+ val bluePrintRuntime = mockk<DefaultBluePrintRuntimeService>("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
new file mode 100644
index 000000000..11c6c037c
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/blueprint-validation/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/validation/MockBluePrintTypeValidatorService.kt
@@ -0,0 +1,86 @@
+/*
+ * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Modifications Copyright © 2018 IBM.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.controllerblueprints.validation
+
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintDataTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidator
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowValidator
+
+class MockBluePrintTypeValidatorService : BluePrintTypeValidatorService {
+
+ override fun <T : BluePrintValidator<*>> bluePrintValidator(referenceName: String, classType: Class<T>): T? {
+ return null
+ }
+
+ override fun <T : BluePrintValidator<*>> bluePrintValidators(referenceNamePrefix: String, classType: Class<T>): List<T>? {
+ return null
+ }
+
+ override fun <T : BluePrintValidator<*>> bluePrintValidators(classType: Class<T>): List<T>? {
+ return null
+ }
+
+ override fun getServiceTemplateValidators(): List<BluePrintServiceTemplateValidator> {
+ return listOf(BluePrintServiceTemplateValidatorImpl(this))
+ }
+
+ override fun getDataTypeValidators(): List<BluePrintDataTypeValidator> {
+ return listOf(BluePrintDataTypeValidatorImpl(this))
+ }
+
+ override fun getArtifactTypeValidators(): List<BluePrintArtifactTypeValidator> {
+ return listOf(BluePrintArtifactTypeValidatorImpl(this))
+ }
+
+ override fun getArtifactDefinitionsValidators(): List<BluePrintArtifactDefinitionValidator> {
+ return listOf(BluePrintArtifactDefinitionValidatorImpl(this))
+ }
+
+ override fun getNodeTypeValidators(): List<BluePrintNodeTypeValidator> {
+ return listOf(BluePrintNodeTypeValidatorImpl(this))
+ }
+
+ override fun getTopologyTemplateValidators(): List<BluePrintTopologyTemplateValidator> {
+ return listOf(BluePrintTopologyTemplateValidatorImpl(this))
+ }
+
+ override fun getNodeTemplateValidators(): List<BluePrintNodeTemplateValidator> {
+ return listOf(BluePrintNodeTemplateValidatorImpl(this))
+ }
+
+ override fun getWorkflowValidators(): List<BluePrintWorkflowValidator> {
+ return listOf(BluePrintWorkflowValidatorImpl(this))
+ }
+
+ override fun getPropertyDefinitionValidators(): List<BluePrintPropertyDefinitionValidator> {
+ return listOf(BluePrintPropertyDefinitionValidatorImpl(this))
+ }
+
+ override fun getAttributeDefinitionValidators(): List<BluePrintAttributeDefinitionValidator> {
+ return listOf(BluePrintAttributeDefinitionValidatorImpl(this))
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/pom.xml b/ms/blueprintsprocessor/modules/blueprints/pom.xml
new file mode 100644
index 000000000..cd6a17e88
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/pom.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright © 2018-2019 AT&T Intellectual Property.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>modules</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>blueprints</artifactId>
+ <packaging>pom</packaging>
+
+ <name>Blueprints POM</name>
+ <description>Blueprints POM</description>
+
+ <modules>
+ <module>blueprint-core</module>
+ <module>resource-dict</module>
+ <module>blueprint-validation</module>
+ <module>blueprint-proto</module>
+ </modules>
+</project>
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/pom.xml b/ms/blueprintsprocessor/modules/blueprints/resource-dict/pom.xml
new file mode 100644
index 000000000..2e2fab150
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/pom.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprints</artifactId>
+ <version>0.7.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>resource-dict</artifactId>
+
+ <name>Controller Blueprints Resource Dictionary</name>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-test-junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinition.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinition.kt
new file mode 100644
index 000000000..10930ffab
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinition.kt
@@ -0,0 +1,108 @@
+/*
+ * Copyright © 2018 IBM.
+ * Modifications 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.resource.dict
+
+import com.fasterxml.jackson.annotation.JsonFormat
+import com.fasterxml.jackson.annotation.JsonProperty
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeTemplate
+import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
+import java.io.Serializable
+import java.util.Date
+
+open class ResourceDefinition {
+
+ @JsonProperty(value = "name", required = true)
+ lateinit var name: String
+
+ @JsonProperty(value = "property", required = true)
+ lateinit var property: PropertyDefinition
+
+ var tags: String? = null
+
+ @JsonProperty(value = "updated-by")
+ lateinit var updatedBy: String
+
+ @JsonProperty(value = "sources", required = true)
+ lateinit var sources: MutableMap<String, NodeTemplate>
+}
+
+open class ResourceAssignment {
+
+ @JsonProperty(value = "name", required = true)
+ lateinit var name: String
+
+ @JsonProperty(value = "property")
+ var property: PropertyDefinition? = null
+
+ @JsonProperty("input-param")
+ var inputParameter: Boolean = false
+
+ @JsonProperty("dictionary-name")
+ var dictionaryName: String? = null
+
+ @JsonProperty("dictionary-source")
+ var dictionarySource: String? = null
+
+ /** Modified Source definition, Capability Source will use for script reference changes,
+ * Rest Source will use for extra headers etc **/
+ @JsonProperty("dictionary-source-definition")
+ var dictionarySourceDefinition: NodeTemplate? = null
+
+ /** Duplicate field : Shall be used directly from Dictionary Source definition dependencies. **/
+ @JsonProperty("dependencies")
+ var dependencies: MutableList<String>? = null
+
+ @JsonProperty("version")
+ var version: Int = 0
+
+ @JsonProperty("status")
+ var status: String? = null
+
+ @JsonProperty("message")
+ var message: String? = null
+
+ @JsonProperty("updated-date")
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
+ var updatedDate: Date? = null
+
+ @JsonProperty("updated-by")
+ var updatedBy: String? = null
+
+ override fun toString(): String {
+ return """
+ [
+ name = $name
+ status = $status
+ required = ${property?.required}
+ dependencies = $dependencies
+ dictionaryName = $dictionaryName
+ dictionarySource = $dictionarySource
+ ]
+ """.trimIndent()
+ }
+}
+
+/**
+ * Interface for Source Definitions (ex Input Source,
+ * Default Source, Database Source, Rest Sources, etc)
+ */
+interface ResourceSource : Serializable
+
+open class ResourceSourceMapping {
+ lateinit var resourceSourceMappings: MutableMap<String, String>
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDictionaryConstants.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDictionaryConstants.kt
new file mode 100644
index 000000000..366a4dcd4
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDictionaryConstants.kt
@@ -0,0 +1,38 @@
+/*
+ * 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.resource.dict
+
+/**
+ * ResourceDictionaryConstants
+ *
+ * @author Brinda Santh
+ */
+object ResourceDictionaryConstants {
+
+ const val SOURCE_INPUT = "input"
+ const val SOURCE_DEFAULT = "default"
+ const val PROCESSOR_DB = "processor-db"
+
+ const val MODEL_DIR_RESOURCE_DEFINITION: String = "resource_dictionary"
+
+ const val PROPERTY_TYPE = "type"
+ const val PROPERTY_INPUT_KEY_MAPPING = "input-key-mapping"
+ const val PROPERTY_OUTPUT_KEY_MAPPING = "output-key-mapping"
+ const val PROPERTY_KEY_DEPENDENCIES = "key-dependencies"
+
+ const val PATH_RESOURCE_DEFINITION_TYPE = "resources_definition_types"
+}
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
new file mode 100644
index 000000000..f8dea9871
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactory.kt
@@ -0,0 +1,46 @@
+/*
+ * 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.resource.dict.factory
+
+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
+
+/**
+ * ResourceSourceMappingFactory.
+ *
+ * @author Brinda Santh
+ */
+object ResourceSourceMappingFactory {
+
+ private val resourceSourceMappings: MutableMap<String, String> = hashMapOf()
+
+ fun registerSourceMapping(sourceInstance: String, nodeTypeName: String) {
+ resourceSourceMappings[sourceInstance] = nodeTypeName
+ }
+
+ fun getRegisterSourceMapping(sourceInstance: String): String {
+ return resourceSourceMappings[sourceInstance]
+ ?: throw BluePrintException(format("failed to get source({}) mapping", sourceInstance))
+ }
+
+ fun getRegisterSourceMapping(): ResourceSourceMapping {
+ val resourceSourceMapping = ResourceSourceMapping()
+ resourceSourceMapping.resourceSourceMappings = resourceSourceMappings
+ return 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
new file mode 100644
index 000000000..a5171d25c
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationService.kt
@@ -0,0 +1,142 @@
+/*
+ * 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.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.utils.TopologicalSortingUtils
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
+import org.slf4j.LoggerFactory
+import java.io.Serializable
+
+/**
+ * ResourceAssignmentValidationService.
+ *
+ * @author Brinda Santh
+ */
+interface ResourceAssignmentValidationService : Serializable {
+
+ @Throws(BluePrintException::class)
+ fun validate(resourceAssignments: List<ResourceAssignment>): Boolean
+}
+
+/**
+ * ResourceAssignmentValidationServiceImpl.
+ *
+ * @author Brinda Santh
+ */
+open class ResourceAssignmentValidationServiceImpl : ResourceAssignmentValidationService {
+
+ private val log = LoggerFactory.getLogger(ResourceAssignmentValidationServiceImpl::class.java)
+
+ open var resourceAssignmentMap: Map<String, ResourceAssignment> = hashMapOf()
+ open val validationMessage = StrBuilder()
+
+ override fun validate(resourceAssignments: List<ResourceAssignment>): Boolean {
+ try {
+ validateTemplateNDictionaryKeys(resourceAssignments)
+ validateCyclicDependency(resourceAssignments)
+ if (StringUtils.isNotBlank(validationMessage)) {
+ throw BluePrintException("Resource Assignment Validation Failure")
+ }
+ } catch (e: Exception) {
+ throw BluePrintException("Resource Assignment Validation :" + validationMessage.toString(), e)
+ }
+ return true
+ }
+
+ open fun validateTemplateNDictionaryKeys(resourceAssignments: List<ResourceAssignment>) {
+
+ resourceAssignmentMap = resourceAssignments.map { it.name to it }.toMap()
+
+ // Check the Resource Assignment has Duplicate Key Names
+ val duplicateKeyNames = resourceAssignments.groupBy { it.name }
+ .filter { it.value.size > 1 }
+ .map { it.key }
+
+ if (duplicateKeyNames.isNotEmpty()) {
+ validationMessage.appendln(String.format("Duplicate Assignment Template Keys (%s) is Present", duplicateKeyNames))
+ }
+
+ // Collect all the dependencies as a single list
+ val dependenciesNames = resourceAssignments.mapNotNull { it.dependencies }.flatten()
+
+ // Check all the dependencies keys have Resource Assignment mappings.
+ val notPresentDictionaries = dependenciesNames.filter { !resourceAssignmentMap.containsKey(it) }.distinct()
+ if (notPresentDictionaries.isNotEmpty()) {
+ validationMessage.appendln(String.format("No assignments for Dictionary Keys (%s)", notPresentDictionaries))
+ }
+
+ if (StringUtils.isNotBlank(validationMessage)) {
+ throw BluePrintException("Resource Assignment Validation Failure")
+ }
+ }
+
+ open fun validateCyclicDependency(resourceAssignments: List<ResourceAssignment>) {
+ val startResourceAssignment = ResourceAssignment()
+ startResourceAssignment.name = "*"
+
+ val topologySorting = TopologicalSortingUtils<ResourceAssignment>()
+
+ resourceAssignmentMap.map { it.value }.map { resourceAssignment ->
+ if (CollectionUtils.isNotEmpty(resourceAssignment.dependencies)) {
+ resourceAssignment.dependencies!!.map {
+ log.trace("Topological Graph link from {} to {}", it, resourceAssignment.name)
+ topologySorting.add(resourceAssignmentMap[it]!!, resourceAssignment)
+ }
+ } else {
+ topologySorting.add(startResourceAssignment, resourceAssignment)
+ }
+ }
+
+ if (!topologySorting.isDag) {
+ val graph = getTopologicalGraph(topologySorting)
+ validationMessage.appendln("Cyclic Dependency :$graph")
+ }
+ }
+
+ open fun getTopologicalGraph(topologySorting: TopologicalSortingUtils<ResourceAssignment>): String {
+ val s = StringBuilder()
+ val neighbors = topologySorting.getNeighbors()
+
+ neighbors.forEach { v, vs ->
+ if (v.name == "*") {
+ s.append("\n * -> [")
+ for (resourceAssignment in vs) {
+ s.append(
+ "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
+ "),"
+ )
+ }
+ s.append("]")
+ } else {
+ s.append("\n (" + v.dictionaryName + ":" + v.name + ") -> [")
+ for (resourceAssignment in vs) {
+ s.append(
+ "(" + resourceAssignment.dictionaryName + ":" + resourceAssignment.name +
+ "),"
+ )
+ }
+ s.append("]")
+ }
+ }
+ return s.toString()
+ }
+}
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
new file mode 100644
index 000000000..9a5523113
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtils.kt
@@ -0,0 +1,119 @@
+/*
+ * 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.resource.dict.utils
+
+import org.apache.commons.collections.CollectionUtils
+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
+import org.slf4j.LoggerFactory
+import java.util.ArrayList
+
+/**
+ * BulkResourceSequencingUtils.
+ *
+ * @author Brinda Santh
+ */
+object BulkResourceSequencingUtils {
+
+ private val log = LoggerFactory.getLogger(BulkResourceSequencingUtils::class.java)
+
+ @JvmStatic
+ fun process(resourceAssignments: MutableList<ResourceAssignment>): List<List<ResourceAssignment>> {
+ val resourceAssignmentMap: MutableMap<String, ResourceAssignment> = hashMapOf()
+ val sequenceBatchResourceAssignment = ArrayList<List<ResourceAssignment>>()
+ log.trace("Assignments ({})", resourceAssignments)
+ // Prepare Map
+ resourceAssignments.forEach { resourceAssignment ->
+ log.trace("Processing Key ({})", resourceAssignment.name)
+ resourceAssignmentMap.put(resourceAssignment.name, resourceAssignment)
+ }
+
+ val startResourceAssignment = ResourceAssignment()
+ startResourceAssignment.name = "*"
+
+ // Preepare Sorting Map
+ val topologySorting = TopologicalSortingUtils<ResourceAssignment>()
+ resourceAssignmentMap.forEach { _, resourceAssignment ->
+ // Get the dependencies from the assignment sources, if not get from the Resource Assignment dependencies
+ if (resourceAssignment.dictionarySourceDefinition != null) {
+ val dependencies = resourceAssignment.dictionarySourceDefinition?.properties?.get("key-dependencies")?.asListOfString()
+ dependencies?.forEach { dependency ->
+ topologySorting.add(resourceAssignmentMap[dependency]!!, resourceAssignment)
+ }
+ } else if (CollectionUtils.isNotEmpty(resourceAssignment.dependencies)) {
+ for (dependency in resourceAssignment.dependencies!!) {
+ topologySorting.add(resourceAssignmentMap[dependency]!!, resourceAssignment)
+ }
+ } else {
+ topologySorting.add(startResourceAssignment, resourceAssignment)
+ }
+ }
+
+ val sequencedResourceAssignments: MutableList<ResourceAssignment> = topologySorting.topSort()!! as MutableList<ResourceAssignment>
+ log.trace("Sorted Sequenced Assignments ({})", sequencedResourceAssignments)
+
+ var batchResourceAssignment: MutableList<ResourceAssignment>? = null
+ var batchAssignmentName: MutableList<String>? = null
+
+ // Prepare Sorting
+ sequencedResourceAssignments.forEachIndexed { index, resourceAssignment ->
+
+ var previousResourceAssignment: ResourceAssignment? = null
+
+ if (index > 0) {
+ previousResourceAssignment = sequencedResourceAssignments[index - 1]
+ }
+
+ var dependencyPresence = false
+ if (batchAssignmentName != null && resourceAssignment.dependencies != null) {
+ dependencyPresence = CollectionUtils.containsAny(batchAssignmentName, resourceAssignment.dependencies)
+ }
+
+ log.trace(
+ "({}) -> Checking ({}), with ({}), result ({})", resourceAssignment.name,
+ batchAssignmentName, resourceAssignment.dependencies, dependencyPresence
+ )
+
+ if (previousResourceAssignment != null && resourceAssignment.dictionarySource != null &&
+ resourceAssignment.dictionarySource!!.equals(previousResourceAssignment.dictionarySource, true) &&
+ !dependencyPresence
+ ) {
+ batchResourceAssignment!!.add(resourceAssignment)
+ batchAssignmentName!!.add(resourceAssignment.name)
+ } else {
+ if (batchResourceAssignment != null) {
+ sequenceBatchResourceAssignment.add(batchResourceAssignment!!)
+ log.trace("Created old Set ({})", batchAssignmentName)
+ }
+ batchResourceAssignment = arrayListOf()
+ batchResourceAssignment!!.add(resourceAssignment)
+
+ batchAssignmentName = arrayListOf()
+ batchAssignmentName!!.add(resourceAssignment.name)
+ }
+
+ if (index == sequencedResourceAssignments.size - 1) {
+ log.trace("Created old Set ({})", batchAssignmentName)
+ sequenceBatchResourceAssignment.add(batchResourceAssignment!!)
+ }
+ }
+ log.info("Batched Sequence : ({})", sequenceBatchResourceAssignment)
+
+ return sequenceBatchResourceAssignment
+ }
+}
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
new file mode 100644
index 000000000..f26c5098f
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtils.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.resource.dict.utils
+
+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.data.NodeTemplate
+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
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
+import org.slf4j.LoggerFactory
+import java.io.File
+
+object ResourceDictionaryUtils {
+ private val log = LoggerFactory.getLogger(ResourceDictionaryUtils::class.java)
+
+ @JvmStatic
+ fun populateSourceMapping(
+ resourceAssignment: ResourceAssignment,
+ resourceDefinition: ResourceDefinition
+ ) {
+
+ if (StringUtils.isBlank(resourceAssignment.dictionarySource)) {
+
+ if (MapUtils.isNotEmpty(resourceDefinition.sources)) {
+ val source = findFirstSource(resourceDefinition.sources)
+
+ // Populate and Assign First Source
+ if (StringUtils.isNotBlank(source)) {
+ // Set Dictionary Source
+ resourceAssignment.dictionarySource = source
+ } else {
+ resourceAssignment.dictionarySource = ResourceDictionaryConstants.SOURCE_INPUT
+ }
+ log.info("auto map resourceAssignment : {}", resourceAssignment)
+ } else {
+ resourceAssignment.dictionarySource = ResourceDictionaryConstants.SOURCE_INPUT
+ }
+ }
+ }
+
+ @JvmStatic
+ fun findFirstSource(sources: Map<String, NodeTemplate>): String? {
+ var source: String? = null
+ if (MapUtils.isNotEmpty(sources)) {
+ source = sources.keys.stream().findFirst().get()
+ }
+ return source
+ }
+
+ @JvmStatic
+ fun assignInputs(data: JsonNode, context: MutableMap<String, Any>) {
+ log.trace("assignInputs from input JSON ({})", data.toString())
+ 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)
+ log.trace("setting path ({}), values ({})", path, valueNode)
+ context[path] = valueNode
+ }
+ }
+
+ fun getResourceAssignmentFromFile(filePath: String): List<ResourceAssignment> {
+ return JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java)
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
+ }
+
+ fun writeResourceDefinitionTypes(basePath: String, resourceDefinitions: List<ResourceDefinition>) {
+ val resourceDefinitionMap = resourceDefinitions.map { it.name to it }.toMap()
+ writeResourceDefinitionTypes(basePath, resourceDefinitionMap)
+ }
+
+ fun writeResourceDefinitionTypes(basePath: String, resourceDefinitionMap: Map<String, ResourceDefinition>) {
+ 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)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinitionTest.java b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinitionTest.java
new file mode 100644
index 000000000..b8e1d519b
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/ResourceDefinitionTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.resource.dict;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ResourceDefinitionTest {
+ private Logger log = LoggerFactory.getLogger(ResourceDefinitionTest.class);
+ private String basePath = "./../../../../../components/model-catalog/resource-dictionary/starter-dictionary";
+
+ @Test
+ public void testDictionaryDefinitionInputSource() {
+
+ String fileName = basePath + "/input-source.json";
+ ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
+ Assert.assertNotNull("Failed to populate dictionaryDefinition for input type", resourceDefinition);
+ }
+
+ @Test
+ public void testDictionaryDefinitionDefaultSource() {
+
+ String fileName = basePath + "/default-source.json";
+ ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
+ Assert.assertNotNull("Failed to populate dictionaryDefinition for default type", resourceDefinition);
+ }
+
+ @Test
+ public void testDictionaryDefinitionDBSource() {
+
+ String fileName = basePath + "/db-source.json";
+ ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
+ Assert.assertNotNull("Failed to populate dictionaryDefinition for processor-db type", resourceDefinition);
+ }
+
+ @Test
+ public void testDictionaryDefinitionMDSALSource() {
+ String fileName = basePath + "/mdsal-source.json";
+ ResourceDefinition resourceDefinition = JacksonUtils.Companion.readValueFromFile(fileName, ResourceDefinition.class);
+ Assert.assertNotNull("Failed to populate dictionaryDefinition for mdsal type", resourceDefinition);
+ }
+
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactoryTest.java b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactoryTest.java
new file mode 100644
index 000000000..eae944ad9
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/factory/ResourceSourceMappingFactoryTest.java
@@ -0,0 +1,43 @@
+/*
+ * 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.resource.dict.factory;
+
+import org.junit.Test;
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping;
+import org.springframework.util.Assert;
+
+public class ResourceSourceMappingFactoryTest {
+
+ @Test
+ public void testRegisterResourceMapping() {
+
+ ResourceSourceMappingFactory.INSTANCE.registerSourceMapping("processor-db", "source-db");
+ ResourceSourceMappingFactory.INSTANCE.registerSourceMapping("input", "source-input");
+ ResourceSourceMappingFactory.INSTANCE.registerSourceMapping("default", "source-default");
+ ResourceSourceMappingFactory.INSTANCE.registerSourceMapping("sdnc", "source-rest");
+ ResourceSourceMappingFactory.INSTANCE.registerSourceMapping("aai-data", "source-rest");
+
+ String nodeTypeName = ResourceSourceMappingFactory.INSTANCE.getRegisterSourceMapping("processor-db");
+ Assert.notNull(nodeTypeName, "Failed to get processor-db mapping");
+
+ ResourceSourceMapping resourceSourceMapping = ResourceSourceMappingFactory.INSTANCE.getRegisterSourceMapping();
+ Assert.notNull(resourceSourceMapping, "Failed to get resource source mapping");
+ Assert.notNull(resourceSourceMapping.getResourceSourceMappings(), "Failed to get resource source mappings");
+
+ }
+
+}
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
new file mode 100644
index 000000000..77af5dbe0
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/service/ResourceAssignmentValidationServiceTest.kt
@@ -0,0 +1,66 @@
+/*
+ * 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.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.utils.JacksonUtils
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryTestUtils
+import org.slf4j.LoggerFactory
+
+/**
+ * ResourceAssignmentValidationServiceTest.
+ *
+ * @author Brinda Santh
+ */
+class ResourceAssignmentValidationServiceTest {
+
+ private val log = LoggerFactory.getLogger(ResourceAssignmentValidationServiceTest::class.java)
+ @Before
+ fun setUp() {
+ // Setup dummy Source Instance Mapping
+ ResourceDictionaryTestUtils.setUpResourceSourceMapping()
+ }
+
+ @Test
+ fun testValidateSuccess() {
+ log.info("**************** testValidateSuccess *****************")
+ val assignments = JacksonUtils.getListFromClassPathFile("validation/success.json", ResourceAssignment::class.java)
+ val resourceAssignmentValidator = ResourceAssignmentValidationServiceImpl()
+ val result = resourceAssignmentValidator.validate(assignments!!)
+ Assert.assertTrue("Failed to Validate", result)
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testValidateDuplicate() {
+ log.info(" **************** testValidateDuplicate *****************")
+ val assignments = JacksonUtils.getListFromClassPathFile("validation/duplicate.json", ResourceAssignment::class.java)
+ val resourceAssignmentValidator = ResourceAssignmentValidationServiceImpl()
+ resourceAssignmentValidator.validate(assignments!!)
+ }
+
+ @Test(expected = BluePrintException::class)
+ fun testValidateCyclic() {
+ log.info(" **************** testValidateCyclic *****************")
+ val assignments = JacksonUtils.getListFromClassPathFile("validation/cyclic.json", ResourceAssignment::class.java)
+ val resourceAssignmentValidator = ResourceAssignmentValidationServiceImpl()
+ resourceAssignmentValidator.validate(assignments!!)
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtilsTest.java b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtilsTest.java
new file mode 100644
index 000000000..30b4d4544
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/BulkResourceSequencingUtilsTest.java
@@ -0,0 +1,40 @@
+/*
+ * 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.resource.dict.utils;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils;
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment;
+
+import java.util.List;
+
+/**
+ * BulkResourceSequencingUtils.
+ *
+ * @author Brinda Santh
+ */
+public class BulkResourceSequencingUtilsTest {
+
+ @Test
+ public void testProcess() {
+ List<ResourceAssignment> assignments = JacksonUtils.Companion.getListFromClassPathFile("validation/success.json", ResourceAssignment.class);
+ Assert.assertNotNull("failed to get ResourceAssignment from validation/success.json ", assignments);
+ BulkResourceSequencingUtils.process(assignments);
+ }
+
+} \ No newline at end of file
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
new file mode 100644
index 000000000..8004d2ca2
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/java/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryUtilsTest.java
@@ -0,0 +1,100 @@
+/*
+ * 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.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.data.NodeTemplate;
+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;
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * ResourceDictionaryUtilsTest.
+ *
+ * @author Brinda Santh
+ */
+public class ResourceDictionaryUtilsTest {
+ private static final Logger log = LoggerFactory.getLogger(ResourceDictionaryUtilsTest.class);
+
+ @Test
+ public void testPopulateSourceMapping() {
+
+ ResourceAssignment resourceAssignment = new ResourceAssignment();
+ resourceAssignment.setName("sample-assignment");
+ ResourceDefinition resourceDefinition = new ResourceDefinition();
+ Map<String, NodeTemplate> sources = new HashMap<>();
+ resourceDefinition.setSources(sources);
+ // To Check Empty Source
+ ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, resourceDefinition);
+ Assert.assertEquals("Expected Empty source Input, but.", ResourceDictionaryConstants.SOURCE_INPUT, resourceAssignment.getDictionarySource());
+
+ // To Check First Source
+ resourceAssignment.setDictionarySource(null);
+ sources.put(ResourceDictionaryConstants.SOURCE_DEFAULT, new NodeTemplate());
+ ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, resourceDefinition);
+ Assert.assertEquals("Expected First source Default, but.",
+ ResourceDictionaryConstants.SOURCE_DEFAULT,
+ resourceAssignment.getDictionarySource());
+
+ // To Check Assigned Source
+ resourceAssignment.setDictionarySource(ResourceDictionaryConstants.PROCESSOR_DB);
+ ResourceDictionaryUtils.populateSourceMapping(resourceAssignment, resourceDefinition);
+ Assert.assertEquals("Expected Assigned source DB, but.", ResourceDictionaryConstants.PROCESSOR_DB, resourceAssignment.getDictionarySource());
+
+ }
+
+ @Test
+ public void testFindFirstSource() {
+ //To check if Empty Source
+ Map<String, NodeTemplate> sources = new HashMap<>();
+ String firstSource = ResourceDictionaryUtils.findFirstSource(sources);
+ Assert.assertNull("Source populated, which is not expected.", firstSource);
+
+ // TO check the first Source
+ sources.put(ResourceDictionaryConstants.SOURCE_INPUT, new NodeTemplate());
+ String inputFirstSource = ResourceDictionaryUtils.findFirstSource(sources);
+ Assert.assertEquals("Expected source Input, but.", ResourceDictionaryConstants.SOURCE_INPUT, inputFirstSource);
+
+ // TO check the multiple Source
+ sources.put(ResourceDictionaryConstants.PROCESSOR_DB, new NodeTemplate());
+ String multipleFirstSource = ResourceDictionaryUtils.findFirstSource(sources);
+ Assert.assertEquals("Expected source Input, but.", ResourceDictionaryConstants.SOURCE_INPUT, multipleFirstSource);
+
+ }
+
+ @Test
+ public void testAssignInputs() {
+ JsonNode data = JacksonUtils.Companion.jsonNodeFromClassPathFile("data/resource-assignment-input.json");
+ Map<String, Object> context = new HashMap<>();
+ ResourceDictionaryUtils.assignInputs(data, context);
+ String path = BluePrintConstants.PATH_INPUTS.concat(BluePrintConstants.PATH_DIVIDER).concat("mapValue");
+ log.info("populated context {}", context);
+ Assert.assertTrue(String.format("failed to get variable : %s", path), context.containsKey(path));
+
+ }
+
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryTestUtils.kt b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryTestUtils.kt
new file mode 100644
index 000000000..639ed05d3
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/kotlin/org/onap/ccsdk/cds/controllerblueprints/resource/dict/utils/ResourceDictionaryTestUtils.kt
@@ -0,0 +1,31 @@
+/*
+ * 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.resource.dict.utils
+
+import org.onap.ccsdk.cds.controllerblueprints.resource.dict.factory.ResourceSourceMappingFactory
+
+object ResourceDictionaryTestUtils {
+
+ @JvmStatic
+ fun setUpResourceSourceMapping() {
+ ResourceSourceMappingFactory.registerSourceMapping("processor-db", "source-db")
+ ResourceSourceMappingFactory.registerSourceMapping("input", "source-input")
+ ResourceSourceMappingFactory.registerSourceMapping("default", "source-default")
+ ResourceSourceMappingFactory.registerSourceMapping("sdnc", "source-rest")
+ ResourceSourceMappingFactory.registerSourceMapping("aai-data", "source-rest")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/data/resource-assignment-input.json b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/data/resource-assignment-input.json
new file mode 100644
index 000000000..d79c90682
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/data/resource-assignment-input.json
@@ -0,0 +1,10 @@
+{
+ "intValue" : 1,
+ "floatValue" : 1.34,
+ "booleanValue" : true,
+ "stringValue" : "sample-String",
+ "timeValue" : "2018-09-29",
+ "arrayStringValue" : ["one", "two"],
+ "mapValue" : {"profile_name1":"profile_name1",
+ "profile_name2":"profile_name2"}
+} \ No newline at end of file
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/cyclic.json b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/cyclic.json
new file mode 100644
index 000000000..f58c7a705
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/cyclic.json
@@ -0,0 +1,111 @@
+[
+ {
+ "name": "vnf-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "service-instance-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "service-instance-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "bundle-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-id",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-ip",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-ip",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-mac",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "bundle-mac",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id",
+ "bundle-id"
+ ]
+ },
+ {
+ "name": "managed-ip",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "managed-ip",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "vnf-name",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-name",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "managed-ip1",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "managed-ip1",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "loopback-ip",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "loopback-ip",
+ "dictionary-source": "processor-db",
+ "dependencies": [
+ "bundle-mac",
+ "managed-ip1"
+ ]
+ }
+]
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/duplicate.json b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/duplicate.json
new file mode 100644
index 000000000..13a4c9f3e
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/duplicate.json
@@ -0,0 +1,110 @@
+[
+ {
+ "name": "vnf-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "service-instance-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "service-instance-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "bundle-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-id",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-ip",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-ip",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-mac",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "bundle-mac",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id",
+ "bundle-id"
+ ]
+ },
+ {
+ "name": "bundle-mac",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "bundle-mac",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "vnf-name",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-name",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "managed-ip1",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "managed-ip1",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "loopback-ip",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "loopback-ip",
+ "dictionary-source": "processor-db",
+ "dependencies": [
+ "bundle-mac"
+ ]
+ }
+]
diff --git a/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/success.json b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/success.json
new file mode 100644
index 000000000..79925bfac
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/blueprints/resource-dict/src/test/resources/validation/success.json
@@ -0,0 +1,110 @@
+[
+ {
+ "name": "vnf-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "service-instance-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "service-instance-id",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "bundle-id",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-id",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-ip",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "bundle-ip",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id"
+ ]
+ },
+ {
+ "name": "bundle-mac",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "bundle-mac",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "vnf-id",
+ "bundle-id"
+ ]
+ },
+ {
+ "name": "managed-ip",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "managed-ip",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "vnf-name",
+ "input-param": true,
+ "property": {
+ "type": "string",
+ "required": true
+ },
+ "dictionary-name": "vnf-name",
+ "dictionary-source": "input",
+ "dependencies": []
+ },
+ {
+ "name": "managed-ip1",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "managed-ip1",
+ "dictionary-source": "sdnc",
+ "dependencies": [
+ "loopback-ip"
+ ]
+ },
+ {
+ "name": "loopback-ip",
+ "input-param": true,
+ "property": {
+ "type": "string"
+ },
+ "dictionary-name": "loopback-ip",
+ "dictionary-source": "processor-db",
+ "dependencies": [
+ "bundle-mac"
+ ]
+ }
+]
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml
index f444fde66..f11deb44c 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml
@@ -32,12 +32,12 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-validation</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-validation</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt
index a7ad921de..0d737f4ca 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt
@@ -16,47 +16,62 @@
package org.onap.ccsdk.cds.blueprintsprocessor.db
+import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice
-import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService
+import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertyService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
+import javax.sql.DataSource
@Configuration
+@Import(
+ BluePrintPropertyConfiguration::class,
+ BluePrintPropertiesService::class,
+ BluePrintCoreConfiguration::class
+)
@EnableConfigurationProperties
open class BluePrintDBLibConfiguration(private var bluePrintPropertiesService: BluePrintPropertiesService) {
@Bean("primary-database-properties")
open fun getPrimaryProperties(): PrimaryDataSourceProperties {
- return bluePrintPropertiesService.propertyBeanType(DBLibConstants.PREFIX_DB,
- PrimaryDataSourceProperties::class.java)
+ return bluePrintPropertiesService.propertyBeanType(
+ DBLibConstants.PREFIX_DB,
+ PrimaryDataSourceProperties::class.java
+ )
+ }
+
+ @Bean("primaryNamedParameterJdbcTemplate")
+ open fun primaryNamedParameterJdbcTemplate(primaryDataSource: DataSource): NamedParameterJdbcTemplate {
+ return NamedParameterJdbcTemplate(primaryDataSource)
}
}
/**
* Exposed Dependency Service by this SSH Lib Module
*/
-fun BluePrintDependencyService.dbLibPropertyService(): BluePrintDBLibPropertySevice =
- instance(BluePrintDBLibPropertySevice::class)
+fun BluePrintDependencyService.dbLibPropertyService(): BluePrintDBLibPropertyService =
+ instance(BluePrintDBLibPropertyService::class)
fun BluePrintDependencyService.primaryDBLibGenericService(): BluePrintDBLibGenericService =
- instance(PrimaryDBLibGenericService::class)
-
+ instance(PrimaryDBLibGenericService::class)
class DBLibConstants {
companion object {
const val PREFIX_DB: String = "blueprintsprocessor.db"
- //list of database
+ // list of database
const val MARIA_DB: String = "maria-db"
const val PRIMARY_DB: String = "processor-db"
const val MYSQL_DB: String = "mysql-db"
const val ORACLE_DB: String = "oracle-db"
const val POSTGRES_DB: String = "postgres-db"
- //List of database drivers
+ // List of database drivers
const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver"
const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver"
const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver"
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt
index fc43ce34d..d4d804857 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt
@@ -16,7 +16,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.db
-
open class DBDataSourceProperties {
lateinit var url: String
lateinit var username: String
@@ -24,14 +23,14 @@ open class DBDataSourceProperties {
open lateinit var driverClassName: String
}
-open class PrimaryDataSourceProperties: DBDataSourceProperties() {
+open class PrimaryDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
lateinit var hibernateDialect: String
}
-open class MariaDataSourceProperties: DBDataSourceProperties() {
+open class MariaDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
@@ -40,7 +39,7 @@ open class MariaDataSourceProperties: DBDataSourceProperties() {
override var driverClassName = DBLibConstants.DRIVER_MARIA_DB
}
-open class MySqlDataSourceProperties: DBDataSourceProperties() {
+open class MySqlDataSourceProperties : DBDataSourceProperties() {
lateinit var hibernateHbm2ddlAuto: String
lateinit var hibernateDDLAuto: String
lateinit var hibernateNamingStrategy: String
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt
index 0f6314685..aeb87fd66 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt
@@ -27,8 +27,8 @@ interface BluePrintDBLibGenericService {
fun update(sql: String, params: Map<String, Any>): Int
}
-abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate)
- : BluePrintDBLibGenericService {
+abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) :
+ BluePrintDBLibGenericService {
override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate {
return namedParameterJdbcTemplate
@@ -41,4 +41,4 @@ abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplat
override fun update(sql: String, params: Map<String, Any>): Int {
return namedParameterJdbcTemplate.update(sql, params)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/PrimaryDBLibGenericService.kt
index 896929fbb..006b7ca45 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/PrimaryDBLibGenericService.kt
@@ -1,5 +1,5 @@
/*
- * Copyright © 2017-2018 AT&T Intellectual Property.
+ * Copyright © 2018-2019 AT&T Intellectual Property.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,14 +14,11 @@
* limitations under the License.
*/
-package org.onap.ccsdk.cds.blueprintsprocessor.db.primary
+package org.onap.ccsdk.cds.blueprintsprocessor.db
-import org.onap.ccsdk.cds.blueprintsprocessor.db.AbstractDBLibGenericService
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.stereotype.Service
@Service
-open class PrimaryDBLibGenericService(primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate)
- : AbstractDBLibGenericService(primaryNamedParameterJdbcTemplate) {
-
-} \ No newline at end of file
+open class PrimaryDBLibGenericService(primaryNamedParameterJdbcTemplate: NamedParameterJdbcTemplate) :
+ AbstractDBLibGenericService(primaryNamedParameterJdbcTemplate)
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt
index ff53de89f..35baf9314 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt
@@ -18,13 +18,18 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.db.*
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService
+import org.onap.ccsdk.cds.blueprintsprocessor.db.DBDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.DBLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.stereotype.Service
@Service
-class BluePrintDBLibPropertySevice(private var bluePrintPropertiesService: BluePrintPropertiesService) {
+class BluePrintDBLibPropertyService(private var bluePrintPropertiesService: BluePrintPropertiesService) {
fun JdbcTemplate(jsonNode: JsonNode): BluePrintDBLibGenericService {
val dBConnetionProperties = dBDataSourceProperties(jsonNode)
@@ -101,5 +106,4 @@ class BluePrintDBLibPropertySevice(private var bluePrintPropertiesService: BlueP
private fun primaryDBConnectionProperties(prefix: String): PrimaryDataSourceProperties {
return bluePrintPropertiesService.propertyBeanType(prefix, PrimaryDataSourceProperties::class.java)
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt
index 6a0d4a0c5..82895257a 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt
@@ -25,6 +25,8 @@ import javax.sql.DataSource
class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDataSourceProperties) : BluePrintDBLibGenericService {
+ val log = LoggerFactory.getLogger(MariaDatabaseConfiguration::class.java)!!
+
override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate {
return mariaNamedParameterJdbcTemplate(mariaDataSource())
}
@@ -37,8 +39,6 @@ class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDat
return mariaNamedParameterJdbcTemplate(mariaDataSource()).update(sql, params)
}
- val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!!
-
fun mariaDataSource(): DataSource {
val dataSource = DriverManagerDataSource()
dataSource.setDriverClassName(mariaDataSourceProperties.driverClassName)
@@ -51,4 +51,4 @@ class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDat
fun mariaNamedParameterJdbcTemplate(mariaDataSource: DataSource): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(mariaDataSource)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt
index 3091674f0..49b7ec9eb 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt
@@ -50,6 +50,4 @@ class MySqlDatabaseConfiguration(private val mySqlDataSourceProperties: MySqlDat
fun mySqlNamedParameterJdbcTemplate(mySqlDataSource: DataSource): NamedParameterJdbcTemplate {
return NamedParameterJdbcTemplate(mySqlDataSource)
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt
index 82b77da47..0913a0a58 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt
@@ -18,41 +18,23 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary
import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
import org.slf4j.LoggerFactory
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
-import org.springframework.context.annotation.Bean
-import org.springframework.context.annotation.ComponentScan
-import org.springframework.context.annotation.Configuration
-import org.springframework.data.jpa.repository.config.EnableJpaAuditing
-import org.springframework.data.jpa.repository.config.EnableJpaRepositories
-import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.datasource.DriverManagerDataSource
import org.springframework.orm.jpa.JpaTransactionManager
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
import org.springframework.transaction.PlatformTransactionManager
-import java.util.*
+import java.util.HashMap
import javax.sql.DataSource
-@Configuration
-@ConditionalOnProperty(name = ["blueprintsprocessor.db.primary.defaultConfig"], havingValue = "true",
- matchIfMissing = true)
-@ComponentScan
-@EnableJpaRepositories(
- basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.*",
- "org.onap.ccsdk.cds.controllerblueprints.*"],
- entityManagerFactoryRef = "primaryEntityManager",
- transactionManagerRef = "primaryTransactionManager"
-)
-@EnableJpaAuditing
open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties: PrimaryDataSourceProperties) {
+
private val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!!
- @Bean("primaryEntityManager")
- open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ /** Child class will override with spring bean annotation 'primaryEntityManager' and passing entity [packagesToScan]*/
+ open fun primaryEntityManager(vararg packagesToScan: String): LocalContainerEntityManagerFactoryBean {
val em = LocalContainerEntityManagerFactoryBean()
em.dataSource = primaryDataSource()
- em.setPackagesToScan("org.onap.ccsdk.cds.blueprintsprocessor.*",
- "org.onap.ccsdk.cds.controllerblueprints.*")
+ em.setPackagesToScan(*packagesToScan)
em.jpaVendorAdapter = HibernateJpaVendorAdapter()
val properties = HashMap<String, Any>()
properties["hibernate.hbm2ddl.auto"] = primaryDataSourceProperties.hibernateHbm2ddlAuto
@@ -61,7 +43,7 @@ open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties:
return em
}
- @Bean("primaryDataSource")
+ /** Child class will override with spring bean annotation 'primaryDataSource' */
open fun primaryDataSource(): DataSource {
val dataSource = DriverManagerDataSource()
dataSource.setDriverClassName(primaryDataSourceProperties.driverClassName)
@@ -71,17 +53,11 @@ open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties:
return dataSource
}
- @Bean("primaryTransactionManager")
+ /** Child class will override with spring bean annotation 'primaryTransactionManager' */
open fun primaryTransactionManager(): PlatformTransactionManager {
val transactionManager = JpaTransactionManager()
transactionManager.entityManagerFactory = primaryEntityManager().getObject()
log.info("Initialised Primary Transaction Manager for url ${primaryDataSourceProperties.url}")
return transactionManager
}
-
- @Bean("primaryNamedParameterJdbcTemplate")
- open fun primaryNamedParameterJdbcTemplate(primaryDataSource: DataSource): NamedParameterJdbcTemplate {
- return NamedParameterJdbcTemplate(primaryDataSource)
- }
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModel.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModel.kt
index 74a611fbb..43bcb6741 100755
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModel.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModel.kt
@@ -22,8 +22,19 @@ import org.hibernate.annotations.Proxy
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.CascadeType
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.FetchType
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.OneToOne
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
+import javax.persistence.UniqueConstraint
/**
* Provide BlueprintModel Entity
@@ -37,6 +48,7 @@ import javax.persistence.*
@Table(name = "BLUEPRINT_MODEL", uniqueConstraints = [UniqueConstraint(columnNames = ["artifact_name", "artifact_version"])])
@Proxy(lazy = false)
class BlueprintModel : Serializable {
+
@Id
@Column(name = "blueprint_model_id")
var id: String? = null
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelContent.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelContent.kt
index bed6e4e38..a18ae8b1d 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelContent.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelContent.kt
@@ -21,8 +21,18 @@ import io.swagger.annotations.ApiModelProperty
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import java.util.Objects
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.JoinColumn
+import javax.persistence.Lob
+import javax.persistence.OneToOne
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide Blueprint Model Content Entity
@@ -82,8 +92,8 @@ class BlueprintModelContent : Serializable {
return false
}
val blueprintModelContent = o as BlueprintModelContent?
- return (id == blueprintModelContent!!.id && name == blueprintModelContent.name
- && contentType == blueprintModelContent.contentType)
+ return (id == blueprintModelContent!!.id && name == blueprintModelContent.name &&
+ contentType == blueprintModelContent.contentType)
}
override fun hashCode(): Int {
@@ -94,5 +104,4 @@ class BlueprintModelContent : Serializable {
private const val serialVersionUID = 1L
}
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelSearch.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelSearch.kt
index f47124dd0..b1c006793 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelSearch.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintModelSearch.kt
@@ -21,8 +21,14 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import org.springframework.data.annotation.LastModifiedDate
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Entity
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide Blueprint Model Search Entity
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelContentRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelContentRepository.kt
index 7bbfbce79..59ace723a 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelContentRepository.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelContentRepository.kt
@@ -22,7 +22,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-import java.util.*
+import java.util.Optional
/**
* @param <T> Model
@@ -47,8 +47,8 @@ interface BlueprintModelContentRepository : JpaRepository<BlueprintModelContent,
* @param contentType contentType
* @return B?
*/
- fun findTopByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String)
- : BlueprintModelContent?
+ fun findTopByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String):
+ BlueprintModelContent?
/**
* This is a findByBlueprintModelAndContentType method
@@ -57,8 +57,8 @@ interface BlueprintModelContentRepository : JpaRepository<BlueprintModelContent,
* @param contentType contentType
* @return List<B>
*/
- fun findByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String)
- : List<BlueprintModelContent>
+ fun findByBlueprintModelAndContentType(blueprintModel: BlueprintModel, contentType: String):
+ List<BlueprintModelContent>
/**
* This is a findByBlueprintModel method
@@ -76,8 +76,11 @@ interface BlueprintModelContentRepository : JpaRepository<BlueprintModelContent,
* @param name name
* @return B?
*/
- fun findByBlueprintModelAndContentTypeAndName(blueprintModel: BlueprintModel,
- contentType: String, name: String): BlueprintModelContent?
+ fun findByBlueprintModelAndContentTypeAndName(
+ blueprintModel: BlueprintModel,
+ contentType: String,
+ name: String
+ ): BlueprintModelContent?
/**
* This is a deleteByMdeleteByBlueprintModelodelName method
@@ -92,5 +95,4 @@ interface BlueprintModelContentRepository : JpaRepository<BlueprintModelContent,
* @param id id
*/
override fun deleteById(@NotNull id: String)
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelRepository.kt
index 8ef352852..a7891f6a7 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelRepository.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelRepository.kt
@@ -21,7 +21,7 @@ import org.jetbrains.annotations.NotNull
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-import java.util.*
+import java.util.Optional
import javax.transaction.Transactional
/**
@@ -86,5 +86,4 @@ interface BlueprintModelRepository : JpaRepository<BlueprintModel, String> {
* @param id id
*/
override fun deleteById(@NotNull id: String)
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelSearchRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelSearchRepository.kt
index 5c7a94034..4451283cb 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelSearchRepository.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintModelSearchRepository.kt
@@ -19,7 +19,6 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch
import org.springframework.data.domain.Page
-import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@@ -77,9 +76,13 @@ interface BlueprintModelSearchRepository : JpaRepository<BlueprintModelSearch, L
* @return Optional<BlueprintModelSearch>
</BlueprintModelSearch>
*/
- fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(updatedBy: String, tags: String, artifactName: String, artifactVersion: String,
- artifactType: String): List<BlueprintModelSearch>
-
+ fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ updatedBy: String,
+ tags: String,
+ artifactName: String,
+ artifactVersion: String,
+ artifactType: String
+ ): List<BlueprintModelSearch>
/**
* This is a findby some attributes method
@@ -94,10 +97,12 @@ interface BlueprintModelSearchRepository : JpaRepository<BlueprintModelSearch, L
* @param pageRequest
* @return Page<BlueprintModelSearch>
*/
- fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(updatedBy: String, tags: String, artifactName: String, artifactVersion: String,
- artifactType: String,pageRequest: Pageable): Page<BlueprintModelSearch>
-
-
-
-
+ fun findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ updatedBy: String,
+ tags: String,
+ artifactName: String,
+ artifactVersion: String,
+ artifactType: String,
+ pageRequest: Pageable
+ ): Page<BlueprintModelSearch>
}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt
index 5700c2a46..9d1826395 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintCatalogServiceImpl.kt
@@ -18,10 +18,14 @@
package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.slf4j.LoggerFactory
@@ -31,8 +35,9 @@ import javax.persistence.MappedSuperclass
@MappedSuperclass
abstract class BlueprintCatalogServiceImpl(
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintValidator: BluePrintValidatorService) : BluePrintCatalogService {
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintValidator: BluePrintValidatorService
+) : BluePrintCatalogService {
private val log = LoggerFactory.getLogger(BlueprintCatalogServiceImpl::class.java)!!
@@ -74,14 +79,15 @@ abstract class BlueprintCatalogServiceImpl(
return processingId
}
- override suspend fun getFromDatabase(name: String, version: String, extract: Boolean): Path = get(name, version,
- extract)
- ?: throw BluePrintException("Could not find blueprint $name:$version from database")
+ override suspend fun getFromDatabase(name: String, version: String, extract: Boolean): Path = get(
+ name, version,
+ extract
+ )
+ ?: throw BluePrintException("Could not find blueprint $name:$version from database")
override suspend fun deleteFromDatabase(name: String, version: String) = delete(name, version)
abstract suspend fun save(metadata: MutableMap<String, String>, archiveFile: File)
abstract suspend fun get(name: String, version: String, extract: Boolean): Path?
abstract suspend fun delete(name: String, version: String)
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt
index 3ba25d8de..0c407ecdf 100755
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/service/BlueprintProcessorCatalogServiceImpl.kt
@@ -21,11 +21,18 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.service
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModel
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelContent
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintModelRepository
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.slf4j.LoggerFactory
@@ -33,24 +40,26 @@ import org.springframework.dao.DataIntegrityViolationException
import org.springframework.stereotype.Service
import java.io.File
import java.nio.file.Path
-import java.util.*
+import java.util.UUID
// TODO("Duplicate : Merge BlueprintProcessorCatalogServiceImpl and ControllerBlueprintCatalogServiceImpl")
/**
* Similar/Duplicate implementation in [org.onap.ccsdk.cds.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl]
*/
@Service("blueprintsProcessorCatalogService")
-class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: BluePrintValidatorService,
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintModelRepository: BlueprintModelRepository)
- : BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
+class BlueprintProcessorCatalogServiceImpl(
+ bluePrintRuntimeValidatorService: BluePrintValidatorService,
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintModelRepository: BlueprintModelRepository
+) :
+ BlueprintCatalogServiceImpl(bluePrintLoadConfiguration, bluePrintRuntimeValidatorService) {
private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString())
override suspend fun delete(name: String, version: String) {
// Clean blueprint script cache
val cacheKey = BluePrintFileUtils
- .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
+ .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, name, version))
BluePrintCompileCache.cleanClassLoader(cacheKey)
log.info("removed cba file name($name), version($version) from cache")
// Cleaning Deployed Blueprint
@@ -58,16 +67,17 @@ class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: Blu
log.info("removed cba file name($name), version($version) from deploy location")
// Cleaning Data Base
blueprintModelRepository
- .deleteByArtifactNameAndArtifactVersion(name, version)
+ .deleteByArtifactNameAndArtifactVersion(name, version)
log.info("removed cba file name($name), version($version) from database")
}
-
override suspend fun get(name: String, version: String, extract: Boolean): Path? {
val deployFile = normalizedFile(bluePrintLoadConfiguration.blueprintDeployPath, name, version)
- val cbaFile = normalizedFile(bluePrintLoadConfiguration.blueprintArchivePath,
- UUID.randomUUID().toString(), "cba.zip")
+ val cbaFile = normalizedFile(
+ bluePrintLoadConfiguration.blueprintArchivePath,
+ UUID.randomUUID().toString(), "cba.zip"
+ )
if (extract && deployFile.exists()) {
log.info("cba file name($name), version($version) already present(${deployFile.absolutePath})")
@@ -91,8 +101,10 @@ class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: Blu
}
} catch (e: Exception) {
deleteNBDir(deployFile.absolutePath)
- throw BluePrintProcessorException("failed to get get cba file name($name), version($version) from db" +
- " : ${e.message}")
+ throw BluePrintProcessorException(
+ "failed to get get cba file name($name), version($version) from db" +
+ " : ${e.message}"
+ )
} finally {
deleteNBDir(cbaFile.parentFile.absolutePath)
}
@@ -117,7 +129,7 @@ class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: Blu
log.info("Overwriting blueprint model :$artifactName::$artifactVersion")
blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion)
val deployFile =
- normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
+ normalizedPathName(bluePrintLoadConfiguration.blueprintDeployPath, artifactName, artifactVersion)
val cacheKey = BluePrintFileUtils.compileCacheKey(deployFile)
BluePrintCompileCache.cleanClassLoader(cacheKey)
@@ -132,7 +144,7 @@ class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: Blu
blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID]
blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL
blueprintModel.published = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_VALID]
- ?: BluePrintConstants.FLAG_N
+ ?: BluePrintConstants.FLAG_N
blueprintModel.artifactName = artifactName
blueprintModel.artifactVersion = artifactVersion
blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR]!!
@@ -152,8 +164,10 @@ class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: Blu
try {
blueprintModelRepository.saveAndFlush(blueprintModel)
} catch (ex: DataIntegrityViolationException) {
- throw BluePrintException(ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
- "is already exist in database: ${ex.message}", ex)
+ throw BluePrintException(
+ ErrorCode.CONFLICT_ADDING_RESOURCE.value, "The blueprint entry " +
+ "is already exist in database: ${ex.message}", ex
+ )
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt
index d912d8eae..e86dfab72 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt
@@ -43,8 +43,10 @@ import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
@EnableAutoConfiguration
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor"])
-@ContextConfiguration(classes = [BlueprintProcessorCatalogServiceImpl::class, BluePrintCoreConfiguration::class,
- MockBlueprintProcessorCatalogServiceImpl::class])
+@ContextConfiguration(
+ classes = [BlueprintProcessorCatalogServiceImpl::class, BluePrintCoreConfiguration::class,
+ MockBlueprintProcessorCatalogServiceImpl::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BlueprintProcessorCatalogServiceImplTest {
@@ -61,8 +63,10 @@ class BlueprintProcessorCatalogServiceImplTest {
@BeforeTest
fun setup() {
deleteDir("target", "blueprints")
- bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(blueprintId,
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ blueprintId,
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
}
@AfterTest
@@ -72,9 +76,9 @@ class BlueprintProcessorCatalogServiceImplTest {
@Test
fun `test catalog service`() {
- //TODO: I thing this test function should be remve and replace by the other one.
+ // TODO: I thing this test function should be remve and replace by the other one.
runBlocking {
- //FIXME("Create ZIP from test blueprints")
+ // FIXME("Create ZIP from test blueprints")
val file = normalizedFile("./src/test/resources/test-cba.zip")
assertTrue(file.exists(), "couldn't get file ${file.absolutePath}")
@@ -110,10 +114,14 @@ class BlueprintProcessorCatalogServiceImplTest {
blueprintsProcessorCatalogService.get("baseconfiguration", "1.0.0", true)
}
- assertTrue(File(blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath +
- "/baseconfiguration").deleteRecursively(),"Couldn't get blueprint archive " +
- "${blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath}/baseconfiguration " +
- "from data base.")
+ assertTrue(
+ File(
+ blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath +
+ "/baseconfiguration"
+ ).deleteRecursively(), "Couldn't get blueprint archive " +
+ "${blueprintCoreConfiguration.bluePrintLoadConfiguration().blueprintArchivePath}/baseconfiguration " +
+ "from data base."
+ )
}
@Test
@@ -122,4 +130,4 @@ class BlueprintProcessorCatalogServiceImplTest {
blueprintsProcessorCatalogService.delete("baseconfiguration", "1.0.0")
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt
new file mode 100644
index 000000000..d8192acfa
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/TestDatabaseConfiguration.kt
@@ -0,0 +1,54 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.db
+
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
+import org.springframework.transaction.PlatformTransactionManager
+import javax.sql.DataSource
+
+@Configuration
+@Import(BluePrintDBLibConfiguration::class)
+@EnableJpaRepositories(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.db.primary"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
+)
+@EnableJpaAuditing
+open class TestDatabaseConfiguration(primaryDataSourceProperties: PrimaryDataSourceProperties) :
+ PrimaryDatabaseConfiguration(primaryDataSourceProperties) {
+
+ @Bean("primaryEntityManager")
+ open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ return primaryEntityManager("org.onap.ccsdk.cds.blueprintsprocessor.db.primary.*")
+ }
+
+ @Bean("primaryDataSource")
+ override fun primaryDataSource(): DataSource {
+ return super.primaryDataSource()
+ }
+
+ @Bean("primaryTransactionManager")
+ override fun primaryTransactionManager(): PlatformTransactionManager {
+ return super.primaryTransactionManager()
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt
index b98fc0c44..8dcf42668 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/mock/MockBlueprintProcessorCatalogServiceImpl.kt
@@ -32,4 +32,4 @@ open class MockBlueprintProcessorCatalogServiceImpl {
every { bluePrintValidatorService.validateBluePrints(any<BluePrintRuntimeService<*>>()) } returns true
return bluePrintValidatorService
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt
index 2ab1c5d48..d551fee0d 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt
@@ -18,13 +18,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.db.primary
import org.junit.Test
import org.junit.runner.RunWith
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
-import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.TestDatabaseConfiguration
import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration
-import org.springframework.context.annotation.ComponentScan
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
@@ -32,11 +27,10 @@ import javax.sql.DataSource
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class,
- BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class])
+@ContextConfiguration(
+ classes = [TestDatabaseConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
-@EnableAutoConfiguration
class PrimaryDatabaseConfigurationTest {
@Autowired
@@ -46,4 +40,4 @@ class PrimaryDatabaseConfigurationTest {
fun testPrimaryDatabaseConfiguration() {
assertNotNull(primaryDataSource, " failed to create primary data source")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties
index 124e844cb..4345d6e63 100644
--- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties
+++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/application-test.properties
@@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-blueprintsprocessor.db.primary.defaultConfig=true
blueprintsprocessor.db.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
blueprintsprocessor.db.username=sa
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt
index 2dbea8fc9..8ccd8cd56 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt
@@ -27,16 +27,17 @@ import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher
/**
* Representation of DMAAP client service for AAF auth type.
*/
-class AafAuthDmaapClientService(private val clientProps:
- AafAuthDmaapClientProperties)
- : BluePrintDmaapClientService {
+class AafAuthDmaapClientService(
+ private val clientProps:
+ AafAuthDmaapClientProperties
+) :
+ BluePrintDmaapClientService {
/**
* The constructed DMAAP client.
*/
var clients: MutableList<MRBatchingPublisher> = mutableListOf()
-
/**
* Returns the DMAAP client after constructing it properly with the data
* that is required for AAF auth connection.
@@ -52,12 +53,12 @@ class AafAuthDmaapClientService(private val clientProps:
val client = MRClientFactory.createBatchingPublisher(
clientProps.host, t, clientProps.username,
clientProps.password, 1, 1, false,
- clientProps.type, "")
+ clientProps.type, ""
+ )
val batchPublisher = client as MRSimplerBatchPublisher
batchPublisher.props = clientProps.props
clients.add(client)
}
return clients
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt
index a4cb5a3e6..cbde4d003 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt
@@ -26,7 +26,6 @@ import org.slf4j.LoggerFactory
import java.io.IOException
import java.util.concurrent.TimeUnit
-
/**
* Abstraction of DMAAP client services that could form DMAAP client from the
* properties provided. This abstraction also provides a mechanism to send
@@ -38,14 +37,16 @@ interface BluePrintDmaapClientService {
* Static variable for logging.
*/
companion object {
+
var log = LoggerFactory.getLogger(
- BluePrintDmaapClientService::class.java)!!
+ BluePrintDmaapClientService::class.java
+ )!!
}
/**
* Returns the properly constructed DMAAP client with the type.
*/
- fun getDmaapClient(): MutableList<MRBatchingPublisher>
+ fun getDmaapClient(): MutableList<MRBatchingPublisher>
/**
* Sends messages to the sessions created by the information provided from
@@ -93,8 +94,10 @@ interface BluePrintDmaapClientService {
var ms = client.close(timeout, TimeUnit.SECONDS)
msgs.add(ms)
} catch (e: IOException) {
- log.warn("Unable to cleanly close the connection from the " +
- "client $client", e)
+ log.warn(
+ "Unable to cleanly close the connection from the " +
+ "client $client", e
+ )
}
}
return msgs
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt
index 51cd3bf0a..44ed5316b 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt
@@ -37,10 +37,11 @@ open class BluePrintDmaapLibConfiguration
* Util constants required for DMAAP library to use.
*/
class DmaapLibConstants {
+
companion object {
const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" +
"-dmaap-lib-property-service"
const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH"
const val TYPE_HTTP_AAF_AUTH = "HTTPAAF"
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt
index cde4987ff..a3eed159f 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt
@@ -36,7 +36,7 @@ import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.core.env.Environment
import org.springframework.core.io.support.ResourcePropertySource
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.Properties
/**
* Representation of DMAAP lib property service to load the properties
@@ -52,8 +52,10 @@ open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesServi
* Static variable for logging.
*/
companion object {
+
var log = LoggerFactory.getLogger(
- BluePrintDmaapLibPropertyService::class.java)!!
+ BluePrintDmaapLibPropertyService::class.java
+ )!!
}
/**
@@ -90,25 +92,30 @@ open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesServi
*/
fun dmaapClientProperties(prefix: String): DmaapClientProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
val clientProps: DmaapClientProperties
when (type) {
TYPE_HTTP_NO_AUTH -> {
clientProps = bluePrintPropertiesService.propertyBeanType(
- prefix, HttpNoAuthDmaapClientProperties::class.java)
+ prefix, HttpNoAuthDmaapClientProperties::class.java
+ )
clientProps.props = parseEventProps()
}
TYPE_HTTP_AAF_AUTH -> {
clientProps = bluePrintPropertiesService.propertyBeanType(
- prefix, AafAuthDmaapClientProperties::class.java)
+ prefix, AafAuthDmaapClientProperties::class.java
+ )
clientProps.props = parseEventProps()
}
else -> {
- throw BluePrintProcessorException("DMAAP adaptor($type) is " +
- "not supported")
+ throw BluePrintProcessorException(
+ "DMAAP adaptor($type) is " +
+ "not supported"
+ )
}
}
return clientProps
@@ -124,20 +131,26 @@ open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesServi
when (type) {
TYPE_HTTP_NO_AUTH -> {
- clientProps = JacksonUtils.readValue(jsonNode,
- HttpNoAuthDmaapClientProperties::class.java)!!
+ clientProps = JacksonUtils.readValue(
+ jsonNode,
+ HttpNoAuthDmaapClientProperties::class.java
+ )!!
clientProps.props = parseEventProps()
}
TYPE_HTTP_AAF_AUTH -> {
- clientProps = JacksonUtils.readValue(jsonNode,
- AafAuthDmaapClientProperties::class.java)!!
+ clientProps = JacksonUtils.readValue(
+ jsonNode,
+ AafAuthDmaapClientProperties::class.java
+ )!!
clientProps.props = parseEventProps()
}
else -> {
- throw BluePrintProcessorException("DMAAP adaptor($type) is " +
- "not supported")
+ throw BluePrintProcessorException(
+ "DMAAP adaptor($type) is " +
+ "not supported"
+ )
}
}
return clientProps
@@ -158,8 +171,10 @@ open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesServi
}
else -> {
- throw BluePrintProcessorException("Unable to get the DMAAP " +
- "client")
+ throw BluePrintProcessorException(
+ "Unable to get the DMAAP " +
+ "client"
+ )
}
}
}
@@ -171,7 +186,8 @@ open class BluePrintDmaapLibPropertyService(private var bluePrintPropertiesServi
private fun parseEventProps(): Properties {
val prodProps = Properties()
val proProps = (env as ConfigurableEnvironment).propertySources.get(
- "class path resource [event.properties]")
+ "class path resource [event.properties]"
+ )
if (proProps != null) {
val entries = (proProps as ResourcePropertySource).source.entries
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt
index 9d942943e..aa4c40ae6 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt
@@ -26,6 +26,7 @@ import java.util.Properties
* Representation of data required for all DMAAP client.
*/
open class DmaapClientProperties {
+
lateinit var props: Properties
lateinit var type: String
lateinit var host: String
@@ -41,6 +42,7 @@ open class HttpNoAuthDmaapClientProperties : DmaapClientProperties()
* Representation of data required for AAF auth DMAAP client.
*/
open class AafAuthDmaapClientProperties : DmaapClientProperties() {
+
lateinit var username: String
lateinit var password: String
}
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt
index 8bf50a944..a3e347adc 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt
@@ -27,16 +27,17 @@ import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher
/**
* Representation of DMAAP client service for HTTP no auth type.
*/
-class HttpNoAuthDmaapClientService(private val clientProps:
- HttpNoAuthDmaapClientProperties)
- : BluePrintDmaapClientService {
+class HttpNoAuthDmaapClientService(
+ private val clientProps:
+ HttpNoAuthDmaapClientProperties
+) :
+ BluePrintDmaapClientService {
/**
* The constructed DMAAP client.
*/
var clients: MutableList<MRBatchingPublisher> = mutableListOf()
-
/**
* Returns the DMAAP client after constructing it properly with the data
* that is required for HTTP no auth connection.
@@ -58,5 +59,4 @@ class HttpNoAuthDmaapClientService(private val clientProps:
return clients
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt
index 4e91d59f9..3fb7f6802 100644
--- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt
+++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt
@@ -49,19 +49,23 @@ import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class])
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-@ContextConfiguration(classes = [BluePrintDmaapLibConfiguration::class, TestController::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties = ["server.port=9111",
- "blueprintsprocessor.dmaapclient.aai.topic=cds_aai",
- "blueprintsprocessor.dmaapclient.aai.type=HTTPNOAUTH",
- "blueprintsprocessor.dmaapclient.aai.host=127.0.0.1:9111",
- "blueprintsprocessor.dmaapclient.multi.topic=cds_multi1,cds_multi2",
- "blueprintsprocessor.dmaapclient.multi.type=HTTPNOAUTH",
- "blueprintsprocessor.dmaapclient.multi.host=127.0.0.1:9111"])
+@ContextConfiguration(
+ classes = [BluePrintDmaapLibConfiguration::class, TestController::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties = ["server.port=9111",
+ "blueprintsprocessor.dmaapclient.aai.topic=cds_aai",
+ "blueprintsprocessor.dmaapclient.aai.type=HTTPNOAUTH",
+ "blueprintsprocessor.dmaapclient.aai.host=127.0.0.1:9111",
+ "blueprintsprocessor.dmaapclient.multi.topic=cds_multi1,cds_multi2",
+ "blueprintsprocessor.dmaapclient.multi.type=HTTPNOAUTH",
+ "blueprintsprocessor.dmaapclient.multi.host=127.0.0.1:9111"]
+)
class TestDmaapEventPublisher {
@Autowired
- lateinit var dmaapService : BluePrintDmaapLibPropertyService
+ lateinit var dmaapService: BluePrintDmaapLibPropertyService
/**
* Tests the event properties being set properly and sent as request.
@@ -71,9 +75,11 @@ class TestDmaapEventPublisher {
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 1)
@@ -88,7 +94,7 @@ class TestDmaapEventPublisher {
@Test
fun testEventPropertiesWithSingleMsg() {
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- val str : String = "{\n" +
+ val str: String = "{\n" +
" \"a\" : \"hello\"\n" +
"}"
dmaapClient.sendMessage(str)
@@ -106,9 +112,11 @@ class TestDmaapEventPublisher {
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("multi")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 2)
@@ -118,7 +126,6 @@ class TestDmaapEventPublisher {
assertEquals(topic2!!.size, 0)
}
-
/**
* Tests the event properties with multiple topics with JSON node as input.
*/
@@ -134,9 +141,11 @@ class TestDmaapEventPublisher {
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService(node)
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 2)
@@ -146,7 +155,6 @@ class TestDmaapEventPublisher {
assertEquals(topic2!!.size, 0)
}
-
/**
* Tests the event properties with multiple messages.
*/
@@ -155,12 +163,16 @@ class TestDmaapEventPublisher {
val strList = mutableListOf<String>()
val dmaapClient = dmaapService.blueprintDmaapClientService("aai")
- strList.add("{\n" +
- " \"a\" : \"hello\"\n" +
- "}")
- strList.add("{\n" +
- " \"a\" : \"second\"\n" +
- "}")
+ strList.add(
+ "{\n" +
+ " \"a\" : \"hello\"\n" +
+ "}"
+ )
+ strList.add(
+ "{\n" +
+ " \"a\" : \"second\"\n" +
+ "}"
+ )
dmaapClient.sendMessage(strList)
val msgs = dmaapClient.close(2)
assertEquals(msgs!!.size, 1)
@@ -174,10 +186,13 @@ class TestDmaapEventPublisher {
@Test
fun testDmaapClientProperties() {
val properties = dmaapService.dmaapClientProperties(
- "blueprintsprocessor.dmaapclient.aai")
+ "blueprintsprocessor.dmaapclient.aai"
+ )
assertNotNull(properties, "failed to create property bean")
- assertNotNull(properties.host, "failed to get url property" +
- " in property bean")
+ assertNotNull(
+ properties.host, "failed to get url property" +
+ " in property bean"
+ )
}
/**
@@ -187,10 +202,11 @@ class TestDmaapEventPublisher {
fun testBlueprintDmaapClientService() {
val blueprintDmaapClientService =
dmaapService.blueprintDmaapClientService("aai")
- assertNotNull(blueprintDmaapClientService,
- "failed to create blueprintDmaapClientService")
+ assertNotNull(
+ blueprintDmaapClientService,
+ "failed to create blueprintDmaapClientService"
+ )
}
-
}
/**
@@ -204,7 +220,7 @@ open class TestController {
* Accepts request for a topic and sends a message as response.
*/
@PostMapping(path = ["/{topic}"])
- fun postTopic(@PathVariable(value = "topic") topic : String):
+ fun postTopic(@PathVariable(value = "topic") topic: String):
ResponseEntity<Any> {
var a = "{\n" +
" \"message\" : \"The message is published into $topic " +
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/grpc-lib/pom.xml
index 052b81c29..870e265f6 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/pom.xml
@@ -32,8 +32,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt
index 55cf0941d..97b462a3c 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcExtensions.kt
@@ -24,4 +24,4 @@ fun Metadata.getStringKey(key: String): String? {
fun Metadata.putStringKeyValue(key: String, value: String) {
this.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value)
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt
index c37c6263a..a3823c6ac 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibConfiguration.kt
@@ -32,7 +32,7 @@ open class BluePrintGrpcLibConfiguration
* Exposed Dependency Service by this GRPC Lib Module
*/
fun BluePrintDependencyService.grpcLibPropertyService(): BluePrintGrpcLibPropertyService =
- instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY)
+ instance(GRPCLibConstants.SERVICE_BLUEPRINT_GRPC_LIB_PROPERTY)
fun BluePrintDependencyService.grpcClientService(selector: String): BluePrintGrpcClientService {
return grpcLibPropertyService().blueprintGrpcClientService(selector)
@@ -51,4 +51,4 @@ class GRPCLibConstants {
const val TYPE_BASIC_AUTH = "basic-auth"
const val TYPE_TLS_AUTH = "tls-auth"
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt
index 47d16fbc7..f94d918a2 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/BluePrintGrpcLibData.kt
@@ -19,6 +19,7 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc
/** GRPC Server Properties */
open class GrpcServerProperties {
+
lateinit var type: String
var port: Int = -1
}
@@ -36,6 +37,7 @@ open class TLSAuthGrpcServerProperties : GrpcServerProperties() {
/** GRPC Client Properties */
open class GrpcClientProperties {
+
lateinit var type: String
lateinit var host: String
var port: Int = -1
@@ -55,4 +57,4 @@ open class TLSAuthGrpcClientProperties : GrpcClientProperties() {
open class BasicAuthGrpcClientProperties : GrpcClientProperties() {
lateinit var username: String
lateinit var password: String
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcClientLoggingInterceptor.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcClientLoggingInterceptor.kt
index f3b14b59f..43e56606f 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcClientLoggingInterceptor.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcClientLoggingInterceptor.kt
@@ -16,32 +16,41 @@
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor
-import io.grpc.*
+import io.grpc.CallOptions
+import io.grpc.Channel
+import io.grpc.ClientCall
+import io.grpc.ClientInterceptor
+import io.grpc.ForwardingClientCall
+import io.grpc.ForwardingClientCallListener
+import io.grpc.Metadata
+import io.grpc.MethodDescriptor
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.GrpcLoggerService
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-
class GrpcClientLoggingInterceptor : ClientInterceptor {
val log = logger(GrpcClientLoggingInterceptor::class)
val loggingService = GrpcLoggerService()
- override fun <ReqT, RespT> interceptCall(method: MethodDescriptor<ReqT, RespT>,
- callOptions: CallOptions, channel: Channel): ClientCall<ReqT, RespT> {
+ override fun <ReqT, RespT> interceptCall(
+ method: MethodDescriptor<ReqT, RespT>,
+ callOptions: CallOptions,
+ channel: Channel
+ ): ClientCall<ReqT, RespT> {
return object : ForwardingClientCall
.SimpleForwardingClientCall<ReqT, RespT>(channel.newCall(method, callOptions)) {
override fun start(responseListener: Listener<RespT>, headers: Metadata) {
- val listener = object : ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
- override fun onMessage(message: RespT) {
- loggingService.grpcInvoking(headers)
- super.onMessage(message)
+ val listener =
+ object : ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
+ override fun onMessage(message: RespT) {
+ loggingService.grpcInvoking(headers)
+ super.onMessage(message)
+ }
}
- }
super.start(listener, headers)
}
}
-
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt
index e21d5d3ce..a49b96743 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/interceptor/GrpcServerLoggingInterceptor.kt
@@ -16,7 +16,12 @@
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor
-import io.grpc.*
+import io.grpc.ForwardingServerCall
+import io.grpc.ForwardingServerCallListener
+import io.grpc.Metadata
+import io.grpc.ServerCall
+import io.grpc.ServerCallHandler
+import io.grpc.ServerInterceptor
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.GrpcLoggerService
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.logger
@@ -30,9 +35,12 @@ class GrpcServerLoggingInterceptor : ServerInterceptor {
val log = logger(GrpcServerLoggingInterceptor::class)
val loggingService = GrpcLoggerService()
- override fun <ReqT : Any, RespT : Any> interceptCall(call: ServerCall<ReqT, RespT>,
- requestHeaders: Metadata, next: ServerCallHandler<ReqT, RespT>)
- : ServerCall.Listener<ReqT> {
+ override fun <ReqT : Any, RespT : Any> interceptCall(
+ call: ServerCall<ReqT, RespT>,
+ requestHeaders: Metadata,
+ next: ServerCallHandler<ReqT, RespT>
+ ):
+ ServerCall.Listener<ReqT> {
val forwardingServerCall = object : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
override fun sendHeaders(responseHeaders: Metadata) {
@@ -41,9 +49,10 @@ class GrpcServerLoggingInterceptor : ServerInterceptor {
}
}
- return object
- : ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
- next.startCall(forwardingServerCall, requestHeaders)) {
+ return object :
+ ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(
+ next.startCall(forwardingServerCall, requestHeaders)
+ ) {
override fun onMessage(message: ReqT) {
/** Get the requestId, SubRequestId and Originator Id and set in MDS context
@@ -52,22 +61,22 @@ class GrpcServerLoggingInterceptor : ServerInterceptor {
when (message) {
is ExecutionServiceInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintUploadInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintDownloadInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
is BluePrintRemoveInput -> {
val commonHeader = message.commonHeader
- ?: throw BluePrintProcessorException("missing common header in request")
+ ?: throw BluePrintProcessorException("missing common header in request")
loggingService.grpcRequesting(call, commonHeader, next)
}
else -> {
@@ -86,7 +95,6 @@ class GrpcServerLoggingInterceptor : ServerInterceptor {
MDC.clear()
super.onCancel()
}
-
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt
index a175d8b3a..f7be8c66d 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BasicAuthGrpcClientService.kt
@@ -18,23 +18,18 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service
import io.grpc.ManagedChannel
import io.grpc.internal.DnsNameResolverProvider
-import io.grpc.internal.PickFirstLoadBalancerProvider
import io.grpc.netty.NettyChannelBuilder
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
-
-open class BasicAuthGrpcClientService(private val basicAuthGrpcClientProperties: BasicAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+open class BasicAuthGrpcClientService(private val basicAuthGrpcClientProperties: BasicAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
val managedChannel = NettyChannelBuilder
- .forAddress(basicAuthGrpcClientProperties.host, basicAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- // .intercept(BasicAuthClientInterceptor(basicAuthGrpcClientProperties)).usePlaintext()
- .build()
+ .forAddress(basicAuthGrpcClientProperties.host, basicAuthGrpcClientProperties.port)
+ .nameResolverFactory(DnsNameResolverProvider())
+ // .intercept(BasicAuthClientInterceptor(basicAuthGrpcClientProperties)).usePlaintext()
+ .build()
return managedChannel
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt
index 02d5cc695..79da447a1 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyService.kt
@@ -19,7 +19,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.grpc.*
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GRPCLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcServerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@@ -39,7 +46,6 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
return blueprintGrpcServerService(grpcServerProperties)
}
-
/** GRPC Server Lib Property Service */
fun grpcServerProperties(jsonNode: JsonNode): GrpcServerProperties {
return when (val type = jsonNode.get("type").textValue()) {
@@ -57,7 +63,8 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
fun grpcServerProperties(prefix: String): GrpcServerProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
tokenAuthGrpcServerProperties(prefix)
@@ -79,8 +86,8 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
return bluePrintPropertiesService.propertyBeanType(prefix, TLSAuthGrpcServerProperties::class.java)
}
- private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties)
- : BluePrintGrpcServerService {
+ private fun blueprintGrpcServerService(grpcServerProperties: GrpcServerProperties):
+ BluePrintGrpcServerService {
when (grpcServerProperties) {
is TLSAuthGrpcServerProperties -> {
return TLSAuthGrpcServerService(grpcServerProperties)
@@ -91,7 +98,6 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
}
}
-
/** GRPC Client Lib Property Service */
fun blueprintGrpcClientService(jsonNode: JsonNode): BluePrintGrpcClientService {
@@ -105,10 +111,9 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
return blueprintGrpcClientService(restClientProperties)
}
-
fun grpcClientProperties(jsonNode: JsonNode): GrpcClientProperties {
val type = jsonNode.get("type").returnNullIfMissing()?.textValue()
- ?: BluePrintProcessorException("missing type property")
+ ?: BluePrintProcessorException("missing type property")
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
JacksonUtils.readValue(jsonNode, TokenAuthGrpcClientProperties::class.java)!!
@@ -127,7 +132,8 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
fun grpcClientProperties(prefix: String): GrpcClientProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
return when (type) {
GRPCLibConstants.TYPE_TOKEN_AUTH -> {
tokenAuthGrpcClientProperties(prefix)
@@ -140,13 +146,12 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
}
else -> {
throw BluePrintProcessorException("Grpc type($type) not supported")
-
}
}
}
fun blueprintGrpcClientService(grpcClientProperties: GrpcClientProperties):
- BluePrintGrpcClientService {
+ BluePrintGrpcClientService {
return when (grpcClientProperties) {
is TokenAuthGrpcClientProperties -> {
TokenAuthGrpcClientService(grpcClientProperties)
@@ -174,4 +179,4 @@ open class BluePrintGrpcLibPropertyService(private var bluePrintPropertiesServic
private fun basicAuthGrpcClientProperties(prefix: String): BasicAuthGrpcClientProperties {
return bluePrintPropertiesService.propertyBeanType(prefix, BasicAuthGrpcClientProperties::class.java)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt
index 0d9291615..e71525f0a 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcService.kt
@@ -26,4 +26,4 @@ interface BluePrintGrpcServerService {
interface BluePrintGrpcClientService {
suspend fun channel(): ManagedChannel
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt
index 6d2ba43cc..732f4fecf 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/GrpcLoggerService.kt
@@ -23,6 +23,7 @@ import io.grpc.ServerCallHandler
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.getStringKey
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.putStringKeyValue
import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_INVOCATION_ID
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_PARTNER_NAME
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_REQUEST_ID
@@ -36,35 +37,45 @@ import java.net.InetSocketAddress
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
-import java.util.*
+import java.util.UUID
class GrpcLoggerService {
private val log = logger(GrpcLoggerService::class)
/** Used when server receives request */
- fun <ReqT : Any, RespT : Any> grpcRequesting(call: ServerCall<ReqT, RespT>,
- headers: Metadata, next: ServerCallHandler<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ call: ServerCall<ReqT, RespT>,
+ headers: Metadata,
+ next: ServerCallHandler<ReqT, RespT>
+ ) {
val requestID = headers.getStringKey(ONAP_REQUEST_ID).defaultToUUID()
val invocationID = headers.getStringKey(ONAP_INVOCATION_ID).defaultToUUID()
val partnerName = headers.getStringKey(ONAP_PARTNER_NAME) ?: "UNKNOWN"
grpcRequesting(requestID, invocationID, partnerName, call)
}
- fun <ReqT : Any, RespT : Any> grpcRequesting(call: ServerCall<ReqT, RespT>,
- headers: CommonHeader, next: ServerCallHandler<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ call: ServerCall<ReqT, RespT>,
+ headers: CommonHeader,
+ next: ServerCallHandler<ReqT, RespT>
+ ) {
val requestID = headers.requestId.defaultToUUID()
val invocationID = headers.subRequestId.defaultToUUID()
val partnerName = headers.originatorId ?: "UNKNOWN"
grpcRequesting(requestID, invocationID, partnerName, call)
}
- fun <ReqT : Any, RespT : Any> grpcRequesting(requestID: String, invocationID: String, partnerName: String,
- call: ServerCall<ReqT, RespT>) {
+ fun <ReqT : Any, RespT : Any> grpcRequesting(
+ requestID: String,
+ invocationID: String,
+ partnerName: String,
+ call: ServerCall<ReqT, RespT>
+ ) {
val localhost = InetAddress.getLocalHost()
val clientSocketAddress = call.attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) as? InetSocketAddress
- ?: throw BluePrintProcessorException("failed to get client address")
+ ?: throw BluePrintProcessorException("failed to get client address")
val serviceName = call.methodDescriptor.fullMethodName
MDC.put("InvokeTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT))
@@ -77,15 +88,13 @@ class GrpcLoggerService {
log.trace("MDC Properties : ${MDC.getCopyOfContextMap()}")
}
-
/** Used before invoking any GRPC outbound request, Inbound Invocation ID is used as request Id
* for outbound Request, If invocation Id is missing then default Request Id will be generated.
*/
fun grpcInvoking(requestHeader: Metadata) {
requestHeader.putStringKeyValue(ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID())
requestHeader.putStringKeyValue(ONAP_INVOCATION_ID, UUID.randomUUID().toString())
- val partnerName = System.getProperty("APPNAME") ?: "BlueprintsProcessor"
- requestHeader.putStringKeyValue(ONAP_PARTNER_NAME, partnerName)
+ requestHeader.putStringKeyValue(ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME)
}
/** Used when server returns response */
@@ -98,4 +107,4 @@ class GrpcLoggerService {
log.warn("couldn't set grpc response headers", e)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt
index a70cbbce0..44df5fbe5 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcClientService.kt
@@ -18,7 +18,6 @@ package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service
import io.grpc.ManagedChannel
import io.grpc.internal.DnsNameResolverProvider
-import io.grpc.internal.PickFirstLoadBalancerProvider
import io.grpc.netty.GrpcSslContexts
import io.grpc.netty.NettyChannelBuilder
import io.netty.handler.ssl.SslContext
@@ -26,17 +25,21 @@ import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLoggingInterceptor
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
+
+ val target =
+ if (tlsAuthGrpcClientProperties.port == -1) tlsAuthGrpcClientProperties.host
+ else "${tlsAuthGrpcClientProperties.host}:${tlsAuthGrpcClientProperties.port}"
+
return NettyChannelBuilder
- .forAddress(tlsAuthGrpcClientProperties.host, tlsAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- .intercept(GrpcClientLoggingInterceptor())
- .sslContext(sslContext())
- .build()
+ .forTarget(target)
+ .nameResolverFactory(DnsNameResolverProvider())
+ .intercept(GrpcClientLoggingInterceptor())
+ .sslContext(sslContext())
+ .build()
}
fun sslContext(): SslContext {
@@ -44,11 +47,14 @@ class TLSAuthGrpcClientService(private val tlsAuthGrpcClientProperties: TLSAuthG
if (tlsAuthGrpcClientProperties.trustCertCollection != null) {
builder.trustManager(normalizedFile(tlsAuthGrpcClientProperties.trustCertCollection!!))
}
- if (tlsAuthGrpcClientProperties.clientCertChain != null
- && tlsAuthGrpcClientProperties.clientPrivateKey != null) {
- builder.keyManager(normalizedFile(tlsAuthGrpcClientProperties.clientCertChain!!),
- normalizedFile(tlsAuthGrpcClientProperties.clientPrivateKey!!))
+ if (tlsAuthGrpcClientProperties.clientCertChain != null &&
+ tlsAuthGrpcClientProperties.clientPrivateKey != null
+ ) {
+ builder.keyManager(
+ normalizedFile(tlsAuthGrpcClientProperties.clientCertChain!!),
+ normalizedFile(tlsAuthGrpcClientProperties.clientPrivateKey!!)
+ )
}
return builder.build()
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt
index fc73d43f9..915ea1730 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TLSAuthGrpcServerService.kt
@@ -24,20 +24,21 @@ import io.netty.handler.ssl.SslContextBuilder
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-
-class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthGrpcServerProperties)
- : BluePrintGrpcServerService {
+class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthGrpcServerProperties) :
+ BluePrintGrpcServerService {
override fun serverBuilder(): NettyServerBuilder {
return NettyServerBuilder
- .forPort(tlsAuthGrpcServerProperties.port)
- .sslContext(sslContext())
+ .forPort(tlsAuthGrpcServerProperties.port)
+ .sslContext(sslContext())
}
fun sslContext(): SslContext {
val sslClientContextBuilder = SslContextBuilder
- .forServer(normalizedFile(tlsAuthGrpcServerProperties.certChain),
- normalizedFile(tlsAuthGrpcServerProperties.privateKey))
+ .forServer(
+ normalizedFile(tlsAuthGrpcServerProperties.certChain),
+ normalizedFile(tlsAuthGrpcServerProperties.privateKey)
+ )
tlsAuthGrpcServerProperties.trustCertCollection?.let { trustCertFile ->
sslClientContextBuilder.trustManager(normalizedFile(trustCertFile))
@@ -45,5 +46,4 @@ class TLSAuthGrpcServerService(private val tlsAuthGrpcServerProperties: TLSAuthG
}
return GrpcSslContexts.configure(sslClientContextBuilder).build()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt
index 601dc0e33..4c991df1f 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/TokenAuthGrpcClientService.kt
@@ -16,31 +16,44 @@
package org.onap.ccsdk.cds.blueprintsprocessor.grpc.service
-import io.grpc.*
+import io.grpc.CallOptions
+import io.grpc.Channel
+import io.grpc.ClientCall
+import io.grpc.ClientInterceptor
+import io.grpc.ForwardingClientCall
+import io.grpc.ManagedChannel
+import io.grpc.Metadata
+import io.grpc.MethodDescriptor
import io.grpc.internal.DnsNameResolverProvider
-import io.grpc.internal.PickFirstLoadBalancerProvider
import io.grpc.netty.NettyChannelBuilder
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.interceptor.GrpcClientLoggingInterceptor
-class TokenAuthGrpcClientService(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties)
- : BluePrintGrpcClientService {
+class TokenAuthGrpcClientService(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) :
+ BluePrintGrpcClientService {
override suspend fun channel(): ManagedChannel {
+ val target =
+ if (tokenAuthGrpcClientProperties.port == -1) tokenAuthGrpcClientProperties.host
+ else "${tokenAuthGrpcClientProperties.host}:${tokenAuthGrpcClientProperties.port}"
+
val managedChannel = NettyChannelBuilder
- .forAddress(tokenAuthGrpcClientProperties.host, tokenAuthGrpcClientProperties.port)
- .nameResolverFactory(DnsNameResolverProvider())
- .loadBalancerFactory(PickFirstLoadBalancerProvider())
- .intercept(GrpcClientLoggingInterceptor())
- .intercept(TokenAuthClientInterceptor(tokenAuthGrpcClientProperties)).usePlaintext().build()
+ .forTarget(target)
+ .nameResolverFactory(DnsNameResolverProvider())
+ .intercept(GrpcClientLoggingInterceptor())
+ .intercept(TokenAuthClientInterceptor(tokenAuthGrpcClientProperties)).usePlaintext().build()
return managedChannel
}
}
-class TokenAuthClientInterceptor(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) : ClientInterceptor {
+class TokenAuthClientInterceptor(private val tokenAuthGrpcClientProperties: TokenAuthGrpcClientProperties) :
+ ClientInterceptor {
- override fun <ReqT, RespT> interceptCall(method: MethodDescriptor<ReqT, RespT>,
- callOptions: CallOptions, channel: Channel): ClientCall<ReqT, RespT> {
+ override fun <ReqT, RespT> interceptCall(
+ method: MethodDescriptor<ReqT, RespT>,
+ callOptions: CallOptions,
+ channel: Channel
+ ): ClientCall<ReqT, RespT> {
val authHeader = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt
index 13432c043..d9a8082d4 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcLibPropertyServiceTest.kt
@@ -24,7 +24,11 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.grpc.*
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BasicAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.BluePrintGrpcLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TLSAuthGrpcServerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.grpc.TokenAuthGrpcClientProperties
import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
@@ -35,34 +39,38 @@ import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintGrpcLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.grpcclient.sample.type=basic-auth",
- "blueprintsprocessor.grpcclient.sample.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.sample.port=50505",
- "blueprintsprocessor.grpcclient.sample.username=sampleuser",
- "blueprintsprocessor.grpcclient.sample.password=sampleuser",
-
- "blueprintsprocessor.grpcclient.token.type=token-auth",
- "blueprintsprocessor.grpcclient.token.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.token.port=50505",
- "blueprintsprocessor.grpcclient.token.username=sampleuser",
- "blueprintsprocessor.grpcclient.token.password=sampleuser",
-
- "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth",
- "blueprintsprocessor.grpcserver.tls-sample.port=50505",
- "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem",
- "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key",
- "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem",
-
- "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth",
- "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1",
- "blueprintsprocessor.grpcclient.tls-sample.port=50505",
- "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem",
- "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem",
- "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key"
-])
+@ContextConfiguration(
+ classes = [BluePrintGrpcLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.grpcclient.sample.type=basic-auth",
+ "blueprintsprocessor.grpcclient.sample.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.sample.port=50505",
+ "blueprintsprocessor.grpcclient.sample.username=sampleuser",
+ "blueprintsprocessor.grpcclient.sample.password=sampleuser",
+
+ "blueprintsprocessor.grpcclient.token.type=token-auth",
+ "blueprintsprocessor.grpcclient.token.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.token.port=50505",
+ "blueprintsprocessor.grpcclient.token.username=sampleuser",
+ "blueprintsprocessor.grpcclient.token.password=sampleuser",
+
+ "blueprintsprocessor.grpcserver.tls-sample.type=tls-auth",
+ "blueprintsprocessor.grpcserver.tls-sample.port=50505",
+ "blueprintsprocessor.grpcserver.tls-sample.certChain=server1.pem",
+ "blueprintsprocessor.grpcserver.tls-sample.privateKey=server1.key",
+ "blueprintsprocessor.grpcserver.tls-sample.trustCertCollection=ca.pem",
+
+ "blueprintsprocessor.grpcclient.tls-sample.type=tls-auth",
+ "blueprintsprocessor.grpcclient.tls-sample.host=127.0.0.1",
+ "blueprintsprocessor.grpcclient.tls-sample.port=50505",
+ "blueprintsprocessor.grpcclient.tls-sample.trustCertCollection=ca.pem",
+ "blueprintsprocessor.grpcclient.tls-sample.clientCertChain=client.pem",
+ "blueprintsprocessor.grpcclient.tls-sample.clientPrivateKey=client.key"
+ ]
+)
class BluePrintGrpcLibPropertyServiceTest {
@Autowired
@@ -74,17 +82,22 @@ class BluePrintGrpcLibPropertyServiceTest {
@Test
fun testGrpcClientProperties() {
val properties = bluePrintGrpcLibPropertyService.grpcClientProperties(
- "blueprintsprocessor.grpcclient.sample")
- as BasicAuthGrpcClientProperties
+ "blueprintsprocessor.grpcclient.sample"
+ )
+ as BasicAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
- assertNotNull(properties.host, "failed to get host property" +
- " in property bean")
- assertNotNull(properties.port, "failed to get host property" +
- " in property bean")
- assertNotNull(properties.username, "failed to get host pro" +
- "perty in property bean")
- assertNotNull(properties.password, "failed to get host pr" +
- "operty in property bean")
+ assertNotNull(
+ properties.host, "failed to get host property in property bean"
+ )
+ assertNotNull(
+ properties.port, "failed to get host property in property bean"
+ )
+ assertNotNull(
+ properties.username, "failed to get host property in property bean"
+ )
+ assertNotNull(
+ properties.password, "failed to get host property in property bean"
+ )
}
/**
@@ -93,14 +106,15 @@ class BluePrintGrpcLibPropertyServiceTest {
@Test
fun testGrpcClientPropertiesWithJson() {
val json: String = "{\n" +
- " \"type\" : \"token-auth\",\n" +
- " \"host\" : \"127.0.0.1\",\n" +
- " \"port\" : \"50505\"\n" +
- "}"
+ " \"type\" : \"token-auth\",\n" +
+ " \"host\" : \"127.0.0.1\",\n" +
+ " \"port\" : \"50505\"\n" +
+ "}"
val mapper = ObjectMapper()
val actualObj: JsonNode = mapper.readTree(json)
val properties = bluePrintGrpcLibPropertyService.grpcClientProperties(
- actualObj) as TokenAuthGrpcClientProperties
+ actualObj
+ ) as TokenAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
assertEquals(properties.host, "127.0.0.1")
assertNotNull(properties.port, "50505")
@@ -112,7 +126,8 @@ class BluePrintGrpcLibPropertyServiceTest {
@Test
fun testGrpcClientServiceBasic() {
val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(
- "sample")
+ "sample"
+ )
assertTrue(svc is BasicAuthGrpcClientService)
}
@@ -122,7 +137,8 @@ class BluePrintGrpcLibPropertyServiceTest {
@Test
fun testGrpcClientServiceToken() {
val svc = bluePrintGrpcLibPropertyService.blueprintGrpcClientService(
- "token")
+ "token"
+ )
assertTrue(svc is TokenAuthGrpcClientService)
}
@@ -132,23 +148,23 @@ class BluePrintGrpcLibPropertyServiceTest {
@Test
fun testGrpcClientServiceWithJson() {
val json: String = "{\n" +
- " \"type\" : \"basic-auth\",\n" +
- " \"host\" : \"127.0.0.1\",\n" +
- " \"port\" : \"50505\",\n" +
- " \"username\" : \"sampleuser\",\n" +
- " \"password\" : \"samplepwd\"\n" +
- "}"
+ " \"type\" : \"basic-auth\",\n" +
+ " \"host\" : \"127.0.0.1\",\n" +
+ " \"port\" : \"50505\",\n" +
+ " \"username\" : \"sampleuser\",\n" +
+ " \"password\" : \"samplepwd\"\n" +
+ "}"
val mapper = ObjectMapper()
val actualObj: JsonNode = mapper.readTree(json)
val svc = bluePrintGrpcLibPropertyService
- .blueprintGrpcClientService(actualObj)
+ .blueprintGrpcClientService(actualObj)
assertTrue(svc is BasicAuthGrpcClientService)
}
@Test
fun testGrpcClientTLSProperties() {
val properties = bluePrintGrpcLibPropertyService
- .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties
+ .grpcClientProperties("blueprintsprocessor.grpcclient.tls-sample") as TLSAuthGrpcClientProperties
assertNotNull(properties, "failed to create property bean")
assertNotNull(properties.host, "failed to get host property in property bean")
assertNotNull(properties.port, "failed to get host property in property bean")
@@ -166,14 +182,14 @@ class BluePrintGrpcLibPropertyServiceTest {
}
""".trimIndent()
val jsonProperties = bluePrintGrpcLibPropertyService
- .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties
+ .grpcClientProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcClientProperties
assertNotNull(jsonProperties, "failed to create property bean from json")
}
@Test
fun testGrpcServerTLSProperties() {
val properties = bluePrintGrpcLibPropertyService
- .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties
+ .grpcServerProperties("blueprintsprocessor.grpcserver.tls-sample") as TLSAuthGrpcServerProperties
assertNotNull(properties, "failed to create property bean")
assertNotNull(properties.port, "failed to get host property in property bean")
assertNotNull(properties.trustCertCollection, "failed to get trustCertCollection property in property bean")
@@ -189,11 +205,11 @@ class BluePrintGrpcLibPropertyServiceTest {
}
""".trimIndent()
val jsonProperties = bluePrintGrpcLibPropertyService
- .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties
+ .grpcServerProperties(configDsl.jsonAsJsonType()) as TLSAuthGrpcServerProperties
assertNotNull(jsonProperties, "failed to create property bean from json")
val grpcServerService = bluePrintGrpcLibPropertyService.blueprintGrpcServerService("tls-sample")
assertNotNull(grpcServerService, "failed to get grpc server service")
Assert.assertEquals(TLSAuthGrpcServerService::class.java, grpcServerService.javaClass)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt
index 8154d3747..026fe5af5 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/BluePrintGrpcServerTest.kt
@@ -30,7 +30,7 @@ import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
-import java.util.*
+import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertNotNull
@@ -62,14 +62,16 @@ class BluePrintGrpcServerTest {
}
/** TLS Client Integration testing, GRPC TLS Junit testing is not supported. */
- //@Test
+ // @Test
fun testGrpcTLSServerIntegration() {
runBlocking {
val tlsAuthGrpcClientService = TLSAuthGrpcClientService(tlsAuthGrpcClientProperties)
val grpcChannel = tlsAuthGrpcClientService.channel()
/** Get Send and Receive Channel for bidirectional process method*/
- val (reqChannel, resChannel) = clientCallBidiStreaming(BluePrintProcessingServiceGrpc.getProcessMethod(),
- grpcChannel)
+ val (reqChannel, resChannel) = clientCallBidiStreaming(
+ BluePrintProcessingServiceGrpc.getProcessMethod(),
+ grpcChannel
+ )
launch {
resChannel.consumeEach {
log.info("Received Response")
@@ -85,25 +87,24 @@ class BluePrintGrpcServerTest {
private fun getRequest(requestId: String): ExecutionServiceInput {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(requestId)
- .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(requestId)
+ .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .setMode(ACTION_MODE_SYNC)
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .setMode(ACTION_MODE_SYNC)
+ .build()
val jsonContent = """{ "key1" : "value1" }"""
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
return ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt
index d5bc70c48..fb7282f75 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/grpc/service/MockTLSBluePrintProcessingServer.kt
@@ -27,7 +27,6 @@ import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessin
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
-
val log = logger(MockTLSBluePrintProcessingServer::class)
/** For Integration testing stat this server, Set the working path to run this method */
@@ -40,16 +39,15 @@ fun main() {
privateKey = "src/test/resources/tls-manual/py-executor-key.pem"
}
val server = TLSAuthGrpcServerService(tlsAuthGrpcServerProperties).serverBuilder()
- .intercept(GrpcServerLoggingInterceptor())
- .addService(MockTLSBluePrintProcessingServer())
- .build()
+ .intercept(GrpcServerLoggingInterceptor())
+ .addService(MockTLSBluePrintProcessingServer())
+ .build()
server.start()
log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...")
server.awaitTermination()
} catch (e: Exception) {
log.error("Failed to start tls grpc integration server", e)
}
-
}
class MockTLSBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
@@ -57,17 +55,21 @@ class MockTLSBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrin
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
- log.info("Received requestId(${executionServiceInput.commonHeader.requestId}) " +
- "subRequestId(${executionServiceInput.commonHeader.subRequestId})")
+ log.info(
+ "Received requestId(${executionServiceInput.commonHeader.requestId}) " +
+ "subRequestId(${executionServiceInput.commonHeader.subRequestId})"
+ )
responseObserver.onNext(buildResponse(executionServiceInput))
responseObserver.onCompleted()
}
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
@@ -78,13 +80,12 @@ class MockTLSBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrin
private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder().setCode(200)
- .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
-
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-chain.pem b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-chain.pem
index 30f09dfea..98c4f39ba 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-chain.pem
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-chain.pem
@@ -1,27 +1,37 @@
-----BEGIN CERTIFICATE-----
-MIIEpDCCAowCCQDyhR+GR2RUiTANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls
-b2NhbGhvc3QwHhcNMTkxMDIzMDAwMTA0WhcNMjkxMDIwMDAwMTA0WjAUMRIwEAYD
-VQQDDAlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCs
-c4d6qfbW+GSMp+XURoLXtSAbbehoBXL2beSzqQNW6e+Q9IVtSPZst8VRjUXelFzM
-m7VpS9jhiXOPZ5KKUOD0GVuNQc54VpwtHt7t9L5wS9OvdnLijnMIkc0iUvC6+Rcq
-HSfbNC2Tb+a8jLwojmtRCeY/MyCnmqYpD+U3b6Eue89VpMOIfmDuTqSRRBYNVO72
-hq7FI3UD8+zREg7htfzjJjG14Ec5iVMDxJA1FlwtXFnZxDHgbLjEVjTTR/9Wm1eU
-aJ4oWRt3gG/vnJNa+GwN4w/My+j/5/n/YpNh6GeQrHxBl/SL/SAFBshlwozr4K4K
-av5MqRKyhCACV4SsdhKJUEDtvrtukJvh/ZDW8jdNbFJAljm8UucZGbJrZl6G7XB3
-WteI7rezo0mL0NMBZIT3nQSMEpefKUFZFiE5lYvIk3UuChqIM0xdgV4INwLRHZdc
-1TtiGaBJV05y3Klo5gaUgNGbHP26zfub5TydiMrOA5W2mUvMkG2oit9aqnbaZBLD
-t17cCKzpzcVF5uNUng3j6sQvpTt3S4L28TvKUMAfpecQqvxMoxG0/9HZuv2z+U+L
-LVVsS07yJPIGMLcq1LMM++8LwD1MupcoShjNOq/lUOL6hIMfLOIfxt8Kv8WykVzv
-6yjKEIurjkwMipq4kvr9J7FFi54kGr7uvXWQRHDFJwIDAQABMA0GCSqGSIb3DQEB
-CwUAA4ICAQB7gJzvaOIP3/S2jrObz67g0jiz1cfb4I9KQwpwb6JUWbYm1QjBcGm4
-IhNbdPMD6dpwBc/A4JctA5E+/fArvl14UtK1jkaaE/GCumL0VUSZeAM6CK/63brt
-LplqCunv8ePHmiwjJBnhu+ewe1+mDMVDMw0iot/q+pOM3vqNS1Fipja+xFK1JQZx
-JmkjW/Ug3NHk/SSTfO+VNmlI5bBBApMqKmd9picsyDZ7dTBtZvbqV5eQsPZvv14G
-oEvWnvvom+D5GojroSO+OMHNDR3bzK6p0Cu8AiTy9Ls6J2e4GXJz3Cg/kuF9tNlR
-3X62zDT+CUipuYyTvmjbSyNMGwU7BIZTKFPuTtjh7EwT2g6S8RV9PmT98CQW6kTT
-RJbL7nMIOF0WusysAT5wj1HJ0QKBQCXK+L6WTKTTovaEE7JSVrYe7wVF8Q9SyBIM
-4CPVZt+GMyQKJ9SRnVgTDEMb7sj9HPaoVeDc6LQTv8Q//wFeTdZIWXQhpVJCQCEG
-qkRk9r3isF60ISOXXIYhqE+hx3QXY9M2UyHDtKXPZ7X370vADi2ebBMF8MpIZYl5
-628dME9JhOhLhD5qPJeva2Nq4gLpK+rO6t7ML0Us4edoKyoScowXAh80q1GW3EO3
-IxTK123651C/S0kDqLqZ9rknEdpwSujrT2UW95jUlfo5OKDrPpdOBw==
+MIIGXTCCBEWgAwIBAgIJALA8s9WVhurtMA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNV
+BAYTAlVTMRMwEQYDVQQIDApOZXcgSmVyc2V5MRMwEQYDVQQHDApNaWRkbGV0b3du
+MRcwFQYDVQQKDA5PTkFQIENvbW11bml0eTEOMAwGA1UEAwwFQ0NTREsxHTAbBgkq
+hkiG9w0BCQEWDmJzMjc5NkBhdHQuY29tMB4XDTE5MTEyOTIwNTUzNFoXDTI5MTEy
+NjIwNTUzNFowfzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCk5ldyBKZXJzZXkxEzAR
+BgNVBAcMCk1pZGRsZXRvd24xFzAVBgNVBAoMDk9OQVAgQ29tbXVuaXR5MQ4wDAYD
+VQQDDAVDQ1NESzEdMBsGCSqGSIb3DQEJARYOYnMyNzk2QGF0dC5jb20wggIiMA0G
+CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDMb8yqD/lu3IHffa1H+LnCTKCijZDC
+85sPta8nH9cQxqRLJyjkOZs+K1z5i6Qn1AH8jOYqG1dRO0Y3pTqu0q5s5Q5Qg2ZF
+xZPW0772HL2Id1WAL62ymPcAp4/JPgeFqcVtRcxx+MPKTohjSY9l+cAPuAQ3izmz
+ValxYVvI8s3qRnvp9sjaOTm4vz/9/7mci9hDKn4B8K7u8fUPKkqYQOOaiv31rYVG
+sw7CIGvHGQMz89loWtB7A4ioZmveZdRdRs5kXbGwvuZQOnc6e8wYO211wkPEJ/go
+sulWwMqcwN9L6712g6ZnoFD+gtut+OLIlrZGS/5MEzMnvmX9NzXiKOP9Zp+Qj4jM
+3pa1pt33LxoBYux7r9154wi9kCXLI2XUTA5TbaufXv6/tn3R9fzMYEUeUdLeEEtr
+NBTEpviTaAxgkpLhGbrSd6F3wbvnBh/gPrBW/0HrAnpMuV5V8JFP1SrT2EbguaW5
+G4keckBMkcOPpz/qvYuXW2FD/XO5yz1keJqXs4HSSM0/ZYcNk89wn50I4GLUY0Q5
+hnk9Twdf8zglSRUDHLCrsA88wJXHBL6W6xVQjQFikY94YOVyvcqXvnmlhOhLamr2
+72bbjrVPvZw4nUYZeg/WpdalmpJb4M9MVLLFo11O150PRRUqnHTHHKGXv7C2mCAO
+MIEPr/WJpS50WwIDAQABo4HbMIHYMB0GA1UdDgQWBBT+kmcpEJ/kS/kW9rGc0uom
+T0VqBDAfBgNVHSMEGDAWgBT+kmcpEJ/kS/kW9rGc0uomT0VqBDAJBgNVHRMEAjAA
+MAsGA1UdDwQEAwIF4DATBgNVHSUEDDAKBggrBgEFBQcDATA7BgNVHREENDAyghBj
+ZHMtY29udHJvbGxlci0qgg1weS1leGVjdXRvci0qgglsb2NhbGhvc3SHBH8AAAEw
+LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMA0G
+CSqGSIb3DQEBCwUAA4ICAQCdquyIETbOWFtXpzL/SQ8jB0yzBmErA3vQPm847qSz
+r8QNXsEyPq7lo06xJTfhlmfpOBzCVdpP+/3pvJfKJ8/wC/D3B8E88Ozzz/yCZPuG
+SNcv+SSnki729ptc1bx6It0FQFahXGywm2ASHGMz4zfmMtnjIfBEuMBCD+V4liwr
+oCEw8E1d+fxArv72LMbNYxPQ+HfrasYhINgVnYSpftqIGpi0PGaEoCVrosQnB0Gk
+5kHWvTXqMC+G9Q1MSQk8vs3lnp9Y4gXbdeaMu3YSmM9nVAY1uZiZRBHVbMadIDFO
+NQmDBKfyN6uK3uBV1S84woC0o5iqIR5EF3u4NeCX5jRWR1Uu4zAG70TpcLmyP1do
+Kt49m9sVrxoCgzjzRd1yZ50BZ1/5550OeF55swQv/ncGriD8uxaQu49NbUo2Rw8R
+Af5TMMW9+0KN6zDOUIVfK5a6NGqnylN3drB2jIjGyTOVycm5paL+iuKEg7euxvZ8
+51Z6QWe3F3+wVYVWtDeN3/9FUm3FzonmZvoChYkz7NTifQpS7/46BpBa5DoblcUu
+MMXWMYieVv3wLIvtFFi2CoNh0tyD7TcNsAB4hLbbBxtXmAB82tgjQhOdkQErm+qi
+Gq5AwlI8k3hhkLDcWH4hUx4YTLJLdTeQGKyM6dB+NBZATyzOrY5j86j7vITLeG8t
+3w==
-----END CERTIFICATE-----
diff --git a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-key.pem b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-key.pem
index 830a3ae21..9407765b5 100644
--- a/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-key.pem
+++ b/ms/blueprintsprocessor/modules/commons/grpc-lib/src/test/resources/tls-manual/py-executor-key.pem
@@ -1,52 +1,52 @@
-----BEGIN PRIVATE KEY-----
-MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCsc4d6qfbW+GSM
-p+XURoLXtSAbbehoBXL2beSzqQNW6e+Q9IVtSPZst8VRjUXelFzMm7VpS9jhiXOP
-Z5KKUOD0GVuNQc54VpwtHt7t9L5wS9OvdnLijnMIkc0iUvC6+RcqHSfbNC2Tb+a8
-jLwojmtRCeY/MyCnmqYpD+U3b6Eue89VpMOIfmDuTqSRRBYNVO72hq7FI3UD8+zR
-Eg7htfzjJjG14Ec5iVMDxJA1FlwtXFnZxDHgbLjEVjTTR/9Wm1eUaJ4oWRt3gG/v
-nJNa+GwN4w/My+j/5/n/YpNh6GeQrHxBl/SL/SAFBshlwozr4K4Kav5MqRKyhCAC
-V4SsdhKJUEDtvrtukJvh/ZDW8jdNbFJAljm8UucZGbJrZl6G7XB3WteI7rezo0mL
-0NMBZIT3nQSMEpefKUFZFiE5lYvIk3UuChqIM0xdgV4INwLRHZdc1TtiGaBJV05y
-3Klo5gaUgNGbHP26zfub5TydiMrOA5W2mUvMkG2oit9aqnbaZBLDt17cCKzpzcVF
-5uNUng3j6sQvpTt3S4L28TvKUMAfpecQqvxMoxG0/9HZuv2z+U+LLVVsS07yJPIG
-MLcq1LMM++8LwD1MupcoShjNOq/lUOL6hIMfLOIfxt8Kv8WykVzv6yjKEIurjkwM
-ipq4kvr9J7FFi54kGr7uvXWQRHDFJwIDAQABAoICADepPmRAMbTnDYU8t/jRHXBE
-PO29htL0V0vk4nl+pt5JuZJe6iYA89DZa+3LnG6gEmfUJjSrT4BUXiE+O9U7D7CZ
-8qvgPqUmx1fk6+2AHmuefd/XanNnqQduD/jxLlQbC/gC2xdsev1ok9/tyNmKRmcs
-u81QUkzmpJUCVWiUNkELozswaBBJQj4I0iM1B60b6dlWVVi5/g3dkGVW38jIdaxX
-apoansKaaVoA+s63vd7CPRoFsleOoAB3FqvPREIO97CmJ848HJpwsTB0qDcnkbDV
-xgbDFhxrIozko09ptOvEUILXag45EDmvG8WEivmjVml0aUoTFD7cWHyJBQCpR4fU
-5W9mYd4Rrzbmpb+LGYdNyrp3wo3C7dJ7/ffBMQxmXTdMZkcxorxj4BRG3oACRQ1u
-Ff1iUruZzIIDtEkrC9hc5QpLlDf9b1obm8L9sxf1QmTt59o5oFG40GPwPP19GXwE
-l2faHwho2jYLM9rhuSsK/5sSmUshPNQYmfMnbWzTtghMPE/g0Cfpt8qbspq+G1bk
-z3M97JlFMF83ccRotDElX9E/ttjU7Lehoz+1sOyHiVW1E4oqKer4t+nI2bp6VYZm
-W94qptW7kb4o0DsvPCaoTPBxLJ1ag2WBlqoFkVI0YaxZiZ8OTR55Ovi4z5xWBO1q
-NkCKgdAUQvQVzVtASVGBAoIBAQDSw2nvPFN4gGZ6OI+8j2gWtPcsrhSHS9ykxBeB
-mB/HExYIe8k3EvClf2rnfwzuKgKyVMp7Ev7nH2jS/PGZq37QyXrw0NBGRnvJY0Ez
-YB1KTgf9xaHMGMut5efNvv/cPwYriqosgJ0pdt0vvUAIQ6EBv+iDXXqJ1lQUSRYk
-wKjFABi6TeJY4t9vC474KoXTDaHlwn9+TwnuRBk85wrZzlhK90J0iVa9/Eqeddsc
-Z3CuTlc+NmcP3qvniYODq8nyVc0pKw+28AVYYEd3aJfgm+dpcB21L0oz7CaxH/Rz
-FNONuQRaOzJrcuJsde/KG2X+MHs6hVMXXXWciPrJ2l+Cq7dnAoIBAQDRdwZDcgem
-tJHLihCRzUl9PKip4ZA5757ZyTy6WMLR3wMS2cNTK8+bTrUa0SSC4WSI28pybFA7
-QdSR08c5Nd7jXcIrtqspgZKhb0E60i8VQHhh6ba/kyQjsEz9c/G1WquPK13j2vZ0
-79bomDwFJPsFzABU+sC0/F42ZVQzy9qXkjngjtmaGfrCc7X+pV28nEGtyxHci3L4
-XXfE2dOb+GBVZPLBVXwcthdRYsFuU9GMy2GH0zVtWPOcGRnlpx53Tqg7NIeR0Nm1
-K35EaK8PH92PsAr0Xza7vQHY4cPRz+RhDzjyGQtnhKf96U6gzzt4ZVbQ/UuzDBcL
-PQ2DvUH+sqxBAoIBAEW5kiUsDu0xhTVv2tVll+jTK2ZjnLT5ut/jY2djHTgtrz9V
-PEb1BBmsIoC9PljYGxZGCMpYiW2KrZIHTiIpYwXNcdeTLSPik3cXV+2YIXiAghJJ
-PHKZzWAVS+97/YcubmsfL5cTYWrjQN9XO4TAYtaCV3iGB1DsT9p6J1I3Tl4F3yhb
-NcN0IrjI2R5uauFchC/PfYAaw81ISBUm1iciJYF/dUO6X7DwcvsjQD6QVe3ESwZw
-1v2gC7zIeHKp9WAvVHUHIubBVvNavqnZN01+JjtydNGI+IJe4Jn+WU9tF2OuTqtP
-JCn50sBQ7+gr0j0aatn8W3XCXHNRua3niWtgRYcCggEAT7OzfWxhPuyMYV9qiKAN
-a4ruPp3mjDUCQ6pP4jQuBT+PYtfbe8U63MSpIsgb1XVAFNdVBA70xGd7I/XqY3l9
-ExS08n8yR7vW+Hhl4KTjZ3m9lLwiXmj1omLOGM7KVRBoITUGJ9JEXyB3rM9oXyjA
-H2eNZMh5FSTGEHqj/IV/6paoUSrp37os8VqoEHoJ3d+zGhcf98RT/e9KyGt+GmX6
-+eNMf4YwkJg07THfmkRoguNMfCtAtBfZsjbW5MyfShRy7PxC7ZgDju06wXr3yZB9
-dNQuhufH4s27azQUl7w8ETaCm5QuA7i1V2c0FPpljZ052JHZAQsDpbIYd11HREvm
-QQKCAQEA0W7xNYoFvnyikdG0t266LLv1EkWDFdgkelGx/eGe/JZ+au3uTM94EssC
-ni64XX2P8vK/te+c3jItYO4MRgnDJ7GW+bRnJFu2kBE0W4chx7vga0XApVCP+Ugg
-owv5yf9cOAHFulvPefsU0snYStD3gNq77XDg0CwoyUkpeq+GiupoQ8tquMSsrEwp
-ve5DtDip3cLHz2oVLB3mR4kKVwVwmOgO5RKq6N/H6Jxtf/Zk1I260dKr+Dv2MnDh
-dysO4zH5YEt2ML3oY4zY8lu+I5bHCBR1updSny0B31WrXAJyfZpMx+HOwETFKa3B
-v9AGKz0Jc2GOIRKHrCQ/WkZePetaYQ==
+MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQDMb8yqD/lu3IHf
+fa1H+LnCTKCijZDC85sPta8nH9cQxqRLJyjkOZs+K1z5i6Qn1AH8jOYqG1dRO0Y3
+pTqu0q5s5Q5Qg2ZFxZPW0772HL2Id1WAL62ymPcAp4/JPgeFqcVtRcxx+MPKTohj
+SY9l+cAPuAQ3izmzValxYVvI8s3qRnvp9sjaOTm4vz/9/7mci9hDKn4B8K7u8fUP
+KkqYQOOaiv31rYVGsw7CIGvHGQMz89loWtB7A4ioZmveZdRdRs5kXbGwvuZQOnc6
+e8wYO211wkPEJ/gosulWwMqcwN9L6712g6ZnoFD+gtut+OLIlrZGS/5MEzMnvmX9
+NzXiKOP9Zp+Qj4jM3pa1pt33LxoBYux7r9154wi9kCXLI2XUTA5TbaufXv6/tn3R
+9fzMYEUeUdLeEEtrNBTEpviTaAxgkpLhGbrSd6F3wbvnBh/gPrBW/0HrAnpMuV5V
+8JFP1SrT2EbguaW5G4keckBMkcOPpz/qvYuXW2FD/XO5yz1keJqXs4HSSM0/ZYcN
+k89wn50I4GLUY0Q5hnk9Twdf8zglSRUDHLCrsA88wJXHBL6W6xVQjQFikY94YOVy
+vcqXvnmlhOhLamr272bbjrVPvZw4nUYZeg/WpdalmpJb4M9MVLLFo11O150PRRUq
+nHTHHKGXv7C2mCAOMIEPr/WJpS50WwIDAQABAoICAE70ksfPeZc+ZI5LPIRCZIPN
+EnEVWaZhbS6pDad/nZEmFsfLrPhP40wkdTkPnGuhbs76H959RsDhsqHFF5/zUFhQ
+MrIXvYUO5KUgjG0C9pRg+k2SnHQQrby7+kVPxpnx0oT8YxRVblCQ+g3WmCJbTbkE
+aeSFydggKlvWrRsz4yEq7aqTnEjjtw5KFs3jWO1D+VcfbyESso0oN2wO+lZJIV5L
+df/Pb1y5xOZmnRl86IbFE99Ay6nm2H2paNmw3E7WDNoocXsAj3TGz8tvioiFUyYa
+zA9THH2jc4kE1nup5dOtjTPbboYxHXbeVTegmv27b1RA/0qkU6py13LvQslA36QK
+jl7my7AM165FtzpuAJqcvalgrfMZOOOFPi4MB20C2rT+xze3CJ9Vn6A3zrSj27Hv
+krZK74hWk2m7UwtWmvb1ykJATj2MsnaGv0HwKDcikm5dKcejaRy4yFgYj74nrR64
+qDyYXNhu9NewIBTSK8Liq0SsvMkGDarfdfs3+foORPUzyAnfaeReSn+CkmalpjIy
+YX/za74G1gp39Ls2NOqy+vknkzYVyJZg0OBoa348OsB3igo6hmF3YRT1/48Vl58h
+TwZy8e07aZGlE6iDZUlDt6vM1RQH9ZB5L8D4SiaJP9pk2AtsfbnDlwPkdnyRTVzr
+ePKchCjMVhhF8iJFIF0RAoIBAQDtMIZ231lzMzPIJxbq62WbfQZdWmHaPObOePCq
+BYQ01K5nkhIQo+dnCBrsSjEHKDHQEkHpzt1d8IWYXU/F5dpyiTzQvpNEb8oDwKRO
+30UdTer5ziQZuNv3TKfhdtP1TXeT7PhRr2Xtuhb3znf7lzysYUWKWLJTmL/PieI2
+OW2ZPBiLnJzZwlKfUxzKvfPOja6vjcVasDipw7h0erz2ZWhWKBM/ANwsm4nAaBV7
+t1XHIQGKxPzoETsovcKbytfR9DryMrT/GVwVeYtrdqUG1SiE4gWg4FHxw74sZzcz
+eAOevNUr7DAuSvuOCGHFK4MfiSwmy8O4PcetJ4/43HvL5VU5AoIBAQDcplGkcaw3
+IacYpLB0S30HSI7WQY5mHBuNRtQpJ+fZ5UilZ/ZURKvD2q0kTxGTwGlag08sxOsR
+YgKwLDQsIAPJRBIo6x1rU99ZnE1AKAaLjrE/MVGXyLYSVaNo4373FYU7Tz60T0f8
+C02e1nonNva0NeMB9+vZV5JwZTptq1qLl96i5szWpQRB679gf6tSNaLTMCn1UFCT
+ha0BzOuy9UI8EIHWn5St6iJ3CaoeWub3GRtp0fpiqEiryO9YepXod+V9zT9BaXPM
+CDnuNoyfrcfmdTdAxroLk2FMcg/z5XDKCyRqgvLH2pNNXn37KEhuUHDEar+UsoiI
+jzq3RARWvEozAoIBAQCKfqoVIQc+/+e9eC2mkDqtFsyvl8XJQ4RVjUKhVEVE/+ay
+LRWFR98nRxFJZWzJTAwB/ZclKZgScQ3g0KNy32q1NDMhhBXDgS7JECQgtbfKi6On
+p1lm94zhEo54VQUgl9I5usWoFK2EqQMeQR3H9yADW2zagj3mGCvvyAghN1kqf2+p
+nZHsiM3roAEQ1OdWdV5JvZM+B+WeIt1CjiRmDwJkRFQwlpT5Kvy9L0lUCtH4Sup2
+l91AuEb93AeVJlTskBoXL8qFpc4h7+2bmxRzL+XP6ZX1wOW4MF6L2NzfnbUnbAVg
+9zGO5lOKNJS6J1USBeuU36fxnYlJLu+fFUbn4InpAoIBADwtmEKzRfbbVMlh0UZG
+eFkOLva8dmve6pzDXoXC/nbtE70Y95PQDtChyWsHrZGQfqtS+LsLEdlx063cwHXw
+XVf9Gr7SMPnerCGygVcoE3Dof+ruNoShFxc1CBZJRY157xZX7JAct1NEee0CLdqY
+IPzRXZJh3Y8vVR8WXLMgctdzmiLvs5ou81RPSai16THIsxnKHwdq2i8B3EeLbhUm
+0uOy1NaGO3SbUL8Kgb05qZhm3pUj0ZgqsXc4nB6TgGMgoBSJb+EVM6HH9JTFh+Dc
+8pImEeW2zXLuxTCmQzePsg1IsKvj/vcG4/nL9awUNnzvr3HCc3HIp3gnKCpngI9v
+VwUCggEAW+m7BDMuVQhGfbk62Pe+w54532JMsUdlmgI43wOXBi8NbxMaZiv/pyeF
+nAnxL6Ar+DhR0OG45ZFtEXU5KqGvS9e/nf+Y8dpbEhSpSa7XIEXV57aChgxwTBVl
+k1go0u9Kh12bl0X6aD42+nEIa/aL/8nycCzyvf+oU3CgJS8iRbmsz0BaKGrBVIU9
+IpsQIeosSH592o3n16jFtIkzIjWu16HC2Dny9uUdjLTjHPCqv34mW2EH0xD+VevW
+wh+ezl41sqniYR0U2/a90HyWz1DRASUMLGAiyqghUc9DANjh072tU58yzuott0L7
+lZqnHGyRAFqP6UxZgtwu30KuKIZBlg==
-----END PRIVATE KEY-----
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/message-lib/pom.xml
index 8d08ae838..4d5aedbaa 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/pom.xml
@@ -30,8 +30,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt
index a817c0c74..509689eca 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageExtensions.kt
@@ -20,7 +20,6 @@ import org.apache.kafka.common.header.Headers
import org.apache.kafka.common.header.internals.RecordHeader
import java.nio.charset.Charset
-
fun <T : Headers> T?.toMap(): MutableMap<String, String> {
val map: MutableMap<String, String> = hashMapOf()
this?.forEach { map[it.key()] = String(it.value(), Charset.defaultCharset()) }
@@ -29,4 +28,4 @@ fun <T : Headers> T?.toMap(): MutableMap<String, String> {
fun Headers.addHeader(key: String, value: String) {
this.add(RecordHeader(key, value.toByteArray()))
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt
index ecffa280f..cc4c7fa4a 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibConfiguration.kt
@@ -17,7 +17,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.message
-
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BluePrintMessageLibPropertyService
import org.onap.ccsdk.cds.blueprintsprocessor.message.service.BlueprintMessageConsumerService
@@ -36,14 +35,13 @@ open class BluePrintMessageLibConfiguration
* Exposed Dependency Service by this Message Lib Module
*/
fun BluePrintDependencyService.messageLibPropertyService(): BluePrintMessageLibPropertyService =
- instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY)
+ instance(MessageLibConstants.SERVICE_BLUEPRINT_MESSAGE_LIB_PROPERTY)
/** Extension functions for message producer service **/
fun BluePrintDependencyService.messageProducerService(selector: String): BlueprintMessageProducerService {
return messageLibPropertyService().blueprintMessageProducerService(selector)
}
-
fun BluePrintDependencyService.messageProducerService(jsonNode: JsonNode): BlueprintMessageProducerService {
return messageLibPropertyService().blueprintMessageProducerService(jsonNode)
}
@@ -65,4 +63,4 @@ class MessageLibConstants {
const val TYPE_KAFKA_BASIC_AUTH = "kafka-basic-auth"
const val TYPE_KAFKA_STREAMS_BASIC_AUTH = "kafka-streams-basic-auth"
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt
index d0c3d5ae1..59e3606ea 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/BluePrintMessageLibData.kt
@@ -22,7 +22,6 @@ import org.apache.kafka.streams.StreamsConfig
/** Producer Properties **/
open class MessageProducerProperties
-
open class KafkaBasicAuthMessageProducerProperties : MessageProducerProperties() {
lateinit var bootstrapServers: String
var topic: String? = null
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt
index 4c6c0acdd..72a70893a 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/kafka/AbstractKafkaTopologyComponents.kt
@@ -30,7 +30,6 @@ abstract class AbstractBluePrintMessageProcessor<K, V> : Processor<K, V> {
lateinit var processorContext: ProcessorContext
-
override fun process(key: K, value: V) = runBlocking(Dispatchers.IO) {
try {
processNB(key, value)
@@ -42,7 +41,6 @@ abstract class AbstractBluePrintMessageProcessor<K, V> : Processor<K, V> {
override fun init(context: ProcessorContext) {
log.info("initializing processor (${this.javaClass.simpleName})")
this.processorContext = context
-
}
override fun close() {
@@ -54,12 +52,12 @@ abstract class AbstractBluePrintMessageProcessor<K, V> : Processor<K, V> {
/** CDS Kafka Stream Punctuator abstract class to implement */
abstract class AbstractBluePrintMessagePunctuator : Punctuator {
- lateinit var processorContext: ProcessorContext
+ lateinit var processorContext: ProcessorContext
override fun punctuate(timestamp: Long) = runBlocking(Dispatchers.IO) {
punctuateNB(timestamp)
}
abstract suspend fun punctuateNB(timestamp: Long)
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt
index 853b88bc9..44b50af44 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BluePrintMessageLibPropertyService.kt
@@ -19,7 +19,12 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message.service
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.message.*
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaBasicAuthMessageProducerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageConsumerProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.message.MessageProducerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.stereotype.Service
@@ -62,8 +67,8 @@ open class BluePrintMessageLibPropertyService(private var bluePrintPropertiesSer
}
}
- private fun blueprintMessageProducerService(MessageProducerProperties: MessageProducerProperties)
- : BlueprintMessageProducerService {
+ private fun blueprintMessageProducerService(MessageProducerProperties: MessageProducerProperties):
+ BlueprintMessageProducerService {
when (MessageProducerProperties) {
is KafkaBasicAuthMessageProducerProperties -> {
@@ -77,7 +82,8 @@ open class BluePrintMessageLibPropertyService(private var bluePrintPropertiesSer
private fun kafkaBasicAuthMessageProducerProperties(prefix: String): KafkaBasicAuthMessageProducerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaBasicAuthMessageProducerProperties::class.java)
+ prefix, KafkaBasicAuthMessageProducerProperties::class.java
+ )
}
/** Consumer Property Lib Service Implementation **/
@@ -126,8 +132,8 @@ open class BluePrintMessageLibPropertyService(private var bluePrintPropertiesSer
}
}
- private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties)
- : BlueprintMessageConsumerService {
+ private fun blueprintMessageConsumerService(messageConsumerProperties: MessageConsumerProperties):
+ BlueprintMessageConsumerService {
when (messageConsumerProperties) {
is KafkaBasicAuthMessageConsumerProperties -> {
@@ -144,12 +150,13 @@ open class BluePrintMessageLibPropertyService(private var bluePrintPropertiesSer
private fun kafkaBasicAuthMessageConsumerProperties(prefix: String): KafkaBasicAuthMessageConsumerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaBasicAuthMessageConsumerProperties::class.java)
+ prefix, KafkaBasicAuthMessageConsumerProperties::class.java
+ )
}
private fun kafkaStreamsBasicAuthMessageConsumerProperties(prefix: String): KafkaStreamsBasicAuthConsumerProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, KafkaStreamsBasicAuthConsumerProperties::class.java)
+ prefix, KafkaStreamsBasicAuthConsumerProperties::class.java
+ )
}
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt
index 716fda609..f74abcdb7 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerService.kt
@@ -50,21 +50,31 @@ interface BlueprintMessageConsumerService {
}
/** Consume the [topics] with [additionalConfig], so that we can execute dynamic function [consumerFunction] */
- suspend fun consume(topics: List<String>, additionalConfig: Map<String, Any>?,
- consumerFunction: ConsumerFunction) {
+ suspend fun consume(
+ topics: List<String>,
+ additionalConfig: Map<String, Any>?,
+ consumerFunction: ConsumerFunction
+ ) {
throw BluePrintProcessorException("Not Implemented")
}
/** close the channel, consumer and other resources */
suspend fun shutDown()
}
+
/** Consumer dynamic implementation interface */
interface KafkaConsumerRecordsFunction : ConsumerFunction {
- suspend fun invoke(messageConsumerProperties: MessageConsumerProperties, consumer: Consumer<*, *>,
- consumerRecords: ConsumerRecords<*, *>)
+
+ suspend fun invoke(
+ messageConsumerProperties: MessageConsumerProperties,
+ consumer: Consumer<*, *>,
+ consumerRecords: ConsumerRecords<*, *>
+ )
}
interface KafkaStreamConsumerFunction : ConsumerFunction {
- suspend fun createTopology(messageConsumerProperties: MessageConsumerProperties,
- additionalConfig: Map<String, Any>?): Topology
-} \ No newline at end of file
+ suspend fun createTopology(
+ messageConsumerProperties: MessageConsumerProperties,
+ additionalConfig: Map<String, Any>?
+ ): Topology
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerService.kt
index 7d8138639..cdc65a1c6 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerService.kt
@@ -47,4 +47,4 @@ interface BlueprintMessageProducerService {
}
suspend fun sendMessageNB(topic: String, message: Any, headers: MutableMap<String, String>?): Boolean
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageConsumerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageConsumerService.kt
index 757846c81..3415c8d0d 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageConsumerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageConsumerService.kt
@@ -34,8 +34,9 @@ import java.time.Duration
import kotlin.concurrent.thread
open class KafkaBasicAuthMessageConsumerService(
- private val messageConsumerProperties: KafkaBasicAuthMessageConsumerProperties)
- : BlueprintMessageConsumerService {
+ private val messageConsumerProperties: KafkaBasicAuthMessageConsumerProperties
+) :
+ BlueprintMessageConsumerService {
val log = logger(KafkaBasicAuthMessageConsumerService::class)
val channel = Channel<String>()
@@ -76,7 +77,6 @@ open class KafkaBasicAuthMessageConsumerService(
return subscribe(consumerTopic, additionalConfig)
}
-
override suspend fun subscribe(topics: List<String>, additionalConfig: Map<String, Any>?): Channel<String> {
/** Create Kafka consumer */
kafkaConsumer = kafkaConsumer(additionalConfig)
@@ -124,8 +124,11 @@ open class KafkaBasicAuthMessageConsumerService(
return consume(topics = consumerTopic, additionalConfig = additionalConfig, consumerFunction = consumerFunction)
}
- override suspend fun consume(topics: List<String>, additionalConfig: Map<String, Any>?,
- consumerFunction: ConsumerFunction) {
+ override suspend fun consume(
+ topics: List<String>,
+ additionalConfig: Map<String, Any>?,
+ consumerFunction: ConsumerFunction
+ ) {
val kafkaConsumerFunction = consumerFunction as KafkaConsumerRecordsFunction
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageProducerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageProducerService.kt
index ad9a594b0..8416282af 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageProducerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaBasicAuthMessageProducerService.kt
@@ -20,7 +20,12 @@ package org.onap.ccsdk.cds.blueprintsprocessor.message.service
import org.apache.commons.lang.builder.ToStringBuilder
import org.apache.kafka.clients.producer.Callback
import org.apache.kafka.clients.producer.KafkaProducer
-import org.apache.kafka.clients.producer.ProducerConfig.*
+import org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.CLIENT_ID_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG
+import org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.header.internals.RecordHeader
import org.apache.kafka.common.serialization.ByteArraySerializer
@@ -32,8 +37,9 @@ import org.slf4j.LoggerFactory
import java.nio.charset.Charset
class KafkaBasicAuthMessageProducerService(
- private val messageProducerProperties: KafkaBasicAuthMessageProducerProperties)
- : BlueprintMessageProducerService {
+ private val messageProducerProperties: KafkaBasicAuthMessageProducerProperties
+) :
+ BlueprintMessageProducerService {
private val log = LoggerFactory.getLogger(KafkaBasicAuthMessageProducerService::class.java)!!
@@ -51,8 +57,11 @@ class KafkaBasicAuthMessageProducerService(
return sendMessageNB(messageProducerProperties.topic!!, message, headers)
}
- override suspend fun sendMessageNB(topic: String, message: Any,
- headers: MutableMap<String, String>?): Boolean {
+ override suspend fun sendMessageNB(
+ topic: String,
+ message: Any,
+ headers: MutableMap<String, String>?
+ ): Boolean {
val byteArrayMessage = when (message) {
is String -> message.toByteArray(Charset.defaultCharset())
else -> message.asJsonString().toByteArray(Charset.defaultCharset())
@@ -95,4 +104,3 @@ class KafkaBasicAuthMessageProducerService(
return kafkaProducer!!
}
}
-
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerService.kt
index d0297df4c..0b353d58b 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerService.kt
@@ -23,10 +23,10 @@ import org.apache.kafka.streams.StreamsConfig
import org.onap.ccsdk.cds.blueprintsprocessor.message.KafkaStreamsBasicAuthConsumerProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.logger
-import java.util.*
+import java.util.Properties
-open class KafkaStreamsBasicAuthConsumerService(private val messageConsumerProperties: KafkaStreamsBasicAuthConsumerProperties)
- : BlueprintMessageConsumerService {
+open class KafkaStreamsBasicAuthConsumerService(private val messageConsumerProperties: KafkaStreamsBasicAuthConsumerProperties) :
+ BlueprintMessageConsumerService {
val log = logger(KafkaStreamsBasicAuthConsumerService::class)
lateinit var kafkaStreams: KafkaStreams
@@ -68,4 +68,4 @@ open class KafkaStreamsBasicAuthConsumerService(private val messageConsumerPrope
kafkaStreams.close()
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt
index 21bf1b76c..04b754b13 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerService.kt
@@ -31,15 +31,17 @@ import java.time.Instant
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
-import java.util.*
+import java.util.UUID
class MessageLoggerService {
private val log = logger(MessageLoggerService::class)
fun messageConsuming(headers: CommonHeader, consumerRecord: ConsumerRecord<*, *>) {
- messageConsuming(headers.requestId, headers.subRequestId,
- headers.originatorId, consumerRecord)
+ messageConsuming(
+ headers.requestId, headers.subRequestId,
+ headers.originatorId, consumerRecord
+ )
}
fun messageConsuming(consumerRecord: ConsumerRecord<*, *>) {
@@ -50,14 +52,19 @@ class MessageLoggerService {
messageConsuming(requestID, invocationID, partnerName, consumerRecord)
}
-
- fun messageConsuming(requestID: String, invocationID: String, partnerName: String,
- consumerRecord: ConsumerRecord<*, *>) {
+ fun messageConsuming(
+ requestID: String,
+ invocationID: String,
+ partnerName: String,
+ consumerRecord: ConsumerRecord<*, *>
+ ) {
val headers = consumerRecord.headers().toMap()
val localhost = InetAddress.getLocalHost()
- MDC.put("InvokeTimestamp", ZonedDateTime
+ MDC.put(
+ "InvokeTimestamp", ZonedDateTime
.ofInstant(Instant.ofEpochMilli(consumerRecord.timestamp()), ZoneOffset.UTC)
- .format(DateTimeFormatter.ISO_INSTANT))
+ .format(DateTimeFormatter.ISO_INSTANT)
+ )
MDC.put("RequestID", requestID)
MDC.put("InvocationID", invocationID)
MDC.put("PartnerName", partnerName)
@@ -77,12 +84,11 @@ class MessageLoggerService {
val localhost = InetAddress.getLocalHost()
requestHeader.addHeader(BluePrintConstants.ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID())
requestHeader.addHeader(BluePrintConstants.ONAP_INVOCATION_ID, UUID.randomUUID().toString())
- val partnerName = System.getProperty("APPNAME") ?: "BlueprintsProcessor"
- requestHeader.addHeader(BluePrintConstants.ONAP_PARTNER_NAME, partnerName)
+ requestHeader.addHeader(BluePrintConstants.ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME)
requestHeader.addHeader("ClientIPAddress", localhost.hostAddress)
}
fun messageConsumingExisting() {
MDC.clear()
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt
index b2accfb4d..823ba7dee 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageConsumerServiceTest.kt
@@ -23,7 +23,11 @@ import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
-import org.apache.kafka.clients.consumer.*
+import org.apache.kafka.clients.consumer.Consumer
+import org.apache.kafka.clients.consumer.ConsumerRecord
+import org.apache.kafka.clients.consumer.ConsumerRecords
+import org.apache.kafka.clients.consumer.MockConsumer
+import org.apache.kafka.clients.consumer.OffsetResetStrategy
import org.apache.kafka.common.TopicPartition
import org.junit.Test
import org.junit.runner.RunWith
@@ -40,26 +44,30 @@ import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.messageconsumer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageconsumer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageconsumer.sample.groupId=sample-group",
- "blueprintsprocessor.messageconsumer.sample.topic=default-topic",
- "blueprintsprocessor.messageconsumer.sample.clientId=default-client-id",
- "blueprintsprocessor.messageconsumer.sample.pollMillSec=10",
- "blueprintsprocessor.messageconsumer.sample.pollRecords=1",
-
- "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
-])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.messageconsumer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageconsumer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageconsumer.sample.groupId=sample-group",
+ "blueprintsprocessor.messageconsumer.sample.topic=default-topic",
+ "blueprintsprocessor.messageconsumer.sample.clientId=default-client-id",
+ "blueprintsprocessor.messageconsumer.sample.pollMillSec=10",
+ "blueprintsprocessor.messageconsumer.sample.pollRecords=1",
+
+ "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
+ ]
+)
open class BlueprintMessageConsumerServiceTest {
+
val log = logger(BlueprintMessageConsumerServiceTest::class)
@Autowired
@@ -69,7 +77,7 @@ open class BlueprintMessageConsumerServiceTest {
fun testKafkaBasicAuthConsumerService() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val spyBlueprintMessageConsumerService = spyk(blueprintMessageConsumerService, recordPrivateCalls = true)
@@ -93,8 +101,10 @@ open class BlueprintMessageConsumerServiceTest {
mockKafkaConsumer.updateBeginningOffsets(partitionsBeginningMap)
mockKafkaConsumer.updateEndOffsets(partitionsEndMap)
for (i in 1..10) {
- val record = ConsumerRecord<String, ByteArray>(topic, 1, i.toLong(), "key_$i",
- "I am message $i".toByteArray())
+ val record = ConsumerRecord<String, ByteArray>(
+ topic, 1, i.toLong(), "key_$i",
+ "I am message $i".toByteArray()
+ )
mockKafkaConsumer.addRecord(record)
}
@@ -114,7 +124,7 @@ open class BlueprintMessageConsumerServiceTest {
fun testKafkaBasicAuthConsumerWithDynamicFunction() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val spyBlueprintMessageConsumerService = spyk(blueprintMessageConsumerService, recordPrivateCalls = true)
@@ -138,16 +148,21 @@ open class BlueprintMessageConsumerServiceTest {
mockKafkaConsumer.updateBeginningOffsets(partitionsBeginningMap)
mockKafkaConsumer.updateEndOffsets(partitionsEndMap)
for (i in 1..10) {
- val record = ConsumerRecord<String, ByteArray>(topic, 1, i.toLong(), "key_$i",
- "I am message $i".toByteArray())
+ val record = ConsumerRecord<String, ByteArray>(
+ topic, 1, i.toLong(), "key_$i",
+ "I am message $i".toByteArray()
+ )
mockKafkaConsumer.addRecord(record)
}
every { spyBlueprintMessageConsumerService.kafkaConsumer(any()) } returns mockKafkaConsumer
/** Test Consumer Function implementation */
val consumerFunction = object : KafkaConsumerRecordsFunction {
- override suspend fun invoke(messageConsumerProperties: MessageConsumerProperties,
- consumer: Consumer<*, *>, consumerRecords: ConsumerRecords<*, *>) {
+ override suspend fun invoke(
+ messageConsumerProperties: MessageConsumerProperties,
+ consumer: Consumer<*, *>,
+ consumerRecords: ConsumerRecords<*, *>
+ ) {
val count = consumerRecords.count()
log.trace("Received Message count($count)")
}
@@ -159,11 +174,11 @@ open class BlueprintMessageConsumerServiceTest {
}
/** Integration Kafka Testing, Enable and use this test case only for local desktop testing with real kafka broker */
- //@Test
+ // @Test
fun testKafkaIntegration() {
runBlocking {
val blueprintMessageConsumerService = bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
+ .blueprintMessageConsumerService("sample") as KafkaBasicAuthMessageConsumerService
assertNotNull(blueprintMessageConsumerService, "failed to get blueprintMessageConsumerService")
val channel = blueprintMessageConsumerService.subscribe(null)
@@ -175,18 +190,20 @@ open class BlueprintMessageConsumerServiceTest {
/** Send message with every 1 sec */
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
launch {
repeat(5) {
delay(100)
val headers: MutableMap<String, String> = hashMapOf()
headers["id"] = it.toString()
- blueprintMessageProducerService.sendMessageNB(message = "this is my message($it)",
- headers = headers)
+ blueprintMessageProducerService.sendMessageNB(
+ message = "this is my message($it)",
+ headers = headers
+ )
}
}
delay(5000)
blueprintMessageConsumerService.shutDown()
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt
index 4fe5f5dd1..b824189d2 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/BlueprintMessageProducerServiceTest.kt
@@ -35,17 +35,20 @@ import java.util.concurrent.Future
import kotlin.test.Test
import kotlin.test.assertTrue
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
-])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id"
+ ]
+)
open class BlueprintMessageProducerServiceTest {
@Autowired
@@ -55,7 +58,7 @@ open class BlueprintMessageProducerServiceTest {
fun testKafkaBasicAuthProducertService() {
runBlocking {
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
val mockKafkaTemplate = mockk<KafkaProducer<String, ByteArray>>()
@@ -72,8 +75,4 @@ open class BlueprintMessageProducerServiceTest {
assertTrue(response, "failed to get command response")
}
}
-
}
-
-
-
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerServiceTest.kt
index 9cd974622..1657d70b4 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/KafkaStreamsBasicAuthConsumerServiceTest.kt
@@ -38,25 +38,29 @@ import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
@DirtiesContext
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-[
- "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
- "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageproducer.sample.topic=default-stream-topic",
- "blueprintsprocessor.messageproducer.sample.clientId=default-client-id",
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ [
+ "blueprintsprocessor.messageproducer.sample.type=kafka-basic-auth",
+ "blueprintsprocessor.messageproducer.sample.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageproducer.sample.topic=default-stream-topic",
+ "blueprintsprocessor.messageproducer.sample.clientId=default-client-id",
- "blueprintsprocessor.messageconsumer.stream-consumer.type=kafka-streams-basic-auth",
- "blueprintsprocessor.messageconsumer.stream-consumer.bootstrapServers=127.0.0.1:9092",
- "blueprintsprocessor.messageconsumer.stream-consumer.applicationId=test-streams-application",
- "blueprintsprocessor.messageconsumer.stream-consumer.topic=default-stream-topic"
+ "blueprintsprocessor.messageconsumer.stream-consumer.type=kafka-streams-basic-auth",
+ "blueprintsprocessor.messageconsumer.stream-consumer.bootstrapServers=127.0.0.1:9092",
+ "blueprintsprocessor.messageconsumer.stream-consumer.applicationId=test-streams-application",
+ "blueprintsprocessor.messageconsumer.stream-consumer.topic=default-stream-topic"
-])
+ ]
+)
class KafkaStreamsBasicAuthConsumerServiceTest {
+
@Autowired
lateinit var bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService
@@ -67,15 +71,17 @@ class KafkaStreamsBasicAuthConsumerServiceTest {
}
/** Integration Kafka Testing, Enable and use this test case only for local desktop testing with real kafka broker */
- //@Test
+ // @Test
fun testKafkaStreamingMessageConsumer() {
runBlocking {
val streamingConsumerService = bluePrintMessageLibPropertyService.blueprintMessageConsumerService("stream-consumer")
// Dynamic Consumer Function to create Topology
val consumerFunction = object : KafkaStreamConsumerFunction {
- override suspend fun createTopology(messageConsumerProperties: MessageConsumerProperties,
- additionalConfig: Map<String, Any>?): Topology {
+ override suspend fun createTopology(
+ messageConsumerProperties: MessageConsumerProperties,
+ additionalConfig: Map<String, Any>?
+ ): Topology {
val topology = Topology()
val kafkaStreamsBasicAuthConsumerProperties = messageConsumerProperties
as KafkaStreamsBasicAuthConsumerProperties
@@ -93,29 +99,34 @@ class KafkaStreamsBasicAuthConsumerServiceTest {
// Store Buolder
val countStoreSupplier = Stores.keyValueStoreBuilder(
- Stores.persistentKeyValueStore("PriorityMessageState"),
- Serdes.String(),
- PriorityMessageSerde())
- .withLoggingEnabled(changelogConfig)
+ Stores.persistentKeyValueStore("PriorityMessageState"),
+ Serdes.String(),
+ PriorityMessageSerde()
+ )
+ .withLoggingEnabled(changelogConfig)
topology.addProcessor("FirstProcessor", firstProcessorSupplier, "Source")
topology.addStateStore(countStoreSupplier, "FirstProcessor")
- topology.addSink("SINK", "default-stream-topic-out", Serdes.String().serializer(),
- PriorityMessageSerde().serializer(), "FirstProcessor")
+ topology.addSink(
+ "SINK", "default-stream-topic-out", Serdes.String().serializer(),
+ PriorityMessageSerde().serializer(), "FirstProcessor"
+ )
return topology
}
}
/** Send message with every 1 sec */
val blueprintMessageProducerService = bluePrintMessageLibPropertyService
- .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
+ .blueprintMessageProducerService("sample") as KafkaBasicAuthMessageProducerService
launch {
repeat(5) {
delay(1000)
val headers: MutableMap<String, String> = hashMapOf()
headers["id"] = it.toString()
- blueprintMessageProducerService.sendMessageNB(message = "this is my message($it)",
- headers = headers)
+ blueprintMessageProducerService.sendMessageNB(
+ message = "this is my message($it)",
+ headers = headers
+ )
}
}
streamingConsumerService.consume(null, consumerFunction)
@@ -123,4 +134,4 @@ class KafkaStreamsBasicAuthConsumerServiceTest {
streamingConsumerService.shutDown()
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt
index 82e40efd1..3dce3344f 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MessageLoggerServiceTest.kt
@@ -29,7 +29,6 @@ import kotlin.test.assertEquals
class MessageLoggerServiceTest {
-
@Test
fun testMessagingHeaders() {
val messageLoggerService = MessageLoggerService()
@@ -55,7 +54,5 @@ class MessageLoggerServiceTest {
assertEquals("1234-12", map[BluePrintConstants.ONAP_REQUEST_ID])
messageLoggerService.messageConsumingExisting()
-
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt
index 4db9c772e..5d77c3746 100644
--- a/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt
+++ b/ms/blueprintsprocessor/modules/commons/message-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/message/service/MockKafkaTopologyComponents.kt
@@ -28,7 +28,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import java.io.Serializable
import java.nio.charset.Charset
-import java.util.*
+import java.util.UUID
class PriorityMessage : Serializable {
lateinit var id: String
@@ -47,7 +47,7 @@ open class PriorityMessageSerde : Serde<PriorityMessage> {
return object : Deserializer<PriorityMessage> {
override fun deserialize(topic: String, data: ByteArray): PriorityMessage {
return JacksonUtils.readValue(String(data), PriorityMessage::class.java)
- ?: throw BluePrintProcessorException("failed to convert")
+ ?: throw BluePrintProcessorException("failed to convert")
}
override fun configure(configs: MutableMap<String, *>?, isKey: Boolean) {
@@ -73,7 +73,6 @@ open class PriorityMessageSerde : Serde<PriorityMessage> {
}
}
-
class FirstProcessor : Processor<ByteArray, ByteArray> {
private val log = logger(FirstProcessor::class)
@@ -100,4 +99,4 @@ class FirstProcessor : Processor<ByteArray, ByteArray> {
override fun close() {
log.info("Close...")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/pom.xml b/ms/blueprintsprocessor/modules/commons/pom.xml
index 33255ac46..30c34ab52 100755
--- a/ms/blueprintsprocessor/modules/commons/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/pom.xml
@@ -44,8 +44,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>resource-dict</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>resource-dict</artifactId>
</dependency>
<!-- Test Dependencies -->
<dependency>
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml b/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml
index a79e8d6df..2f5ae6624 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml
@@ -33,8 +33,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-proto</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-proto</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/ApiDataExtensions.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/ApiDataExtensions.kt
index 47b55b018..8e1b5b2ce 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/ApiDataExtensions.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/ApiDataExtensions.kt
@@ -1,5 +1,6 @@
/*
* Copyright © 2019 IBM.
+ * Modifications Copyright © 2018-2019 AT&T Intellectual Property.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +17,39 @@
package org.onap.ccsdk.cds.blueprintsprocessor.core
+import com.fasterxml.jackson.databind.JsonNode
+import com.google.protobuf.Struct
+import com.google.protobuf.util.JsonFormat
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
import org.onap.ccsdk.cds.controllerblueprints.core.asType
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
import kotlin.reflect.KClass
-
fun <T : Any> ExecutionServiceInput.payloadAsType(clazzType: KClass<T>): T {
val actionName = this.actionIdentifiers.actionName
val requestJsonNode = this.payload.get("$actionName-request")
return requestJsonNode.asType(clazzType.java)
-} \ No newline at end of file
+}
+
+/** Convert Proto Struct to Json string */
+fun Struct.asJson(): String {
+ return JsonFormat.printer().print(this)
+}
+
+/** Convert Proto Struct to Json node */
+fun Struct.asJsonType(): JsonNode {
+ return this.asJson().jsonAsJsonType()
+}
+
+/** Convert Json node to Proto Struct */
+fun JsonNode.asProtoStruct(): Struct {
+ return this.asJsonString(false).asProtoStruct()
+}
+
+/** Convert Json string to Proto Struct */
+fun String.asProtoStruct(): Struct {
+ val struct = Struct.newBuilder()
+ JsonFormat.parser().merge(this, struct)
+ return struct.build()
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt
index 62dc933f1..76b37a5b4 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt
@@ -41,12 +41,13 @@ open class BluePrintCoreConfiguration(private val bluePrintPropertiesService: Bl
@Bean
open fun bluePrintLoadConfiguration(): BluePrintLoadConfiguration {
return bluePrintPropertiesService
- .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BluePrintLoadConfiguration::class.java)
+ .propertyBeanType(PREFIX_BLUEPRINT_PROCESSOR, BluePrintLoadConfiguration::class.java)
}
}
@Configuration
open class BluePrintPropertyConfiguration {
+
@Autowired
lateinit var environment: Environment
@@ -59,6 +60,7 @@ open class BluePrintPropertyConfiguration {
@Service
open class BluePrintPropertiesService(private var bluePrintPropertyBinder: Binder) {
+
fun <T> propertyBeanType(prefix: String, type: Class<T>): T {
return bluePrintPropertyBinder.bind(prefix, Bindable.of(type)).get()
}
@@ -74,5 +76,4 @@ open class BlueprintDependencyConfiguration : ApplicationContextAware {
BluePrintDependencyService.inject(applicationContext)
log.info("Dependency Management module created...")
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt
index dae6eea85..d94985400 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt
@@ -24,7 +24,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode
import io.swagger.annotations.ApiModelProperty
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
-import java.util.*
+import java.util.Date
/**
* BlueprintProcessorData
@@ -33,14 +33,17 @@ import java.util.*
*/
open class ExecutionServiceInput {
+
@get:ApiModelProperty(required = true, value = "Headers providing request context.")
lateinit var commonHeader: CommonHeader
@get:ApiModelProperty(required = true, value = "Provide information about the action to execute.")
lateinit var actionIdentifiers: ActionIdentifiers
- @get:ApiModelProperty(required = true,
- value = "Contain the information to be passed as input to the action." +
- "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
- " and the input for resource resolution located within the xxx-request block, contained within xxx-properties")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Contain the information to be passed as input to the action." +
+ "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
+ " and the input for resource resolution located within the xxx-request block, contained within xxx-properties"
+ )
lateinit var payload: ObjectNode
@get:ApiModelProperty(hidden = true)
@get:JsonIgnore
@@ -54,10 +57,12 @@ open class ExecutionServiceOutput {
lateinit var actionIdentifiers: ActionIdentifiers
@get:ApiModelProperty(required = true, value = "Status of the request.")
lateinit var status: Status
- @get:ApiModelProperty(required = true,
- value = "Contain the information to be passed as input to the action." +
- "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
- " and the input for resource resolution located within the xxx-request block, contained within xxx-properties")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Contain the information to be passed as input to the action." +
+ "The payload is constituted of two section: the workflow input which is the higher level block (xxx-request)" +
+ " and the input for resource resolution located within the xxx-request block, contained within xxx-properties"
+ )
lateinit var payload: ObjectNode
@get:ApiModelProperty(hidden = true)
@get:JsonIgnore
@@ -74,9 +79,11 @@ open class ActionIdentifiers {
lateinit var blueprintVersion: String
@get:ApiModelProperty(required = true, value = "Name of the workflow to execute.")
lateinit var actionName: String
- @get:ApiModelProperty(required = true,
- value = "Async processing is only supported for gRPC client.",
- allowableValues = "sync, async")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Async processing is only supported for gRPC client.",
+ allowableValues = "sync, async"
+ )
lateinit var mode: String
}
@@ -106,9 +113,11 @@ open class Status {
var code: Int = 200
@get:ApiModelProperty(required = true, value = "Type of the event being emitted by CDS.")
var eventType: String = EventType.EVENT_COMPONENT_EXECUTED.name
- @get:ApiModelProperty(required = true,
- value = "Time when the execution ended.",
- example = "2012-04-23T18:25:43.511Z")
+ @get:ApiModelProperty(
+ required = true,
+ value = "Time when the execution ended.",
+ example = "2012-04-23T18:25:43.511Z"
+ )
@get:JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp: Date = Date()
@get:ApiModelProperty(required = false, value = "Error message when system failed")
@@ -120,4 +129,4 @@ open class Status {
open class StepData {
lateinit var name: String
var properties: MutableMap<String, JsonNode> = mutableMapOf()
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt
index d63f34ced..628b65ea4 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintRemoteProcessorData.kt
@@ -17,34 +17,39 @@
package org.onap.ccsdk.cds.blueprintsprocessor.core.api.data
import com.fasterxml.jackson.databind.JsonNode
-import java.util.*
+import java.util.Date
enum class StatusType {
SUCCESS, FAILURE
}
-data class RemoteIdentifier(var blueprintName: String,
- var blueprintVersion: String)
-
-
-data class RemoteScriptExecutionInput(var requestId: String,
- var correlationId: String? = null,
- var remoteIdentifier: RemoteIdentifier? = null,
- var command: String,
- var timeOut: Long = 30,
- var properties: MutableMap<String, JsonNode> = hashMapOf()
+data class RemoteIdentifier(
+ var blueprintName: String,
+ var blueprintVersion: String
)
+data class RemoteScriptExecutionInput(
+ var requestId: String,
+ var correlationId: String? = null,
+ var remoteIdentifier: RemoteIdentifier? = null,
+ var command: String,
+ var timeOut: Long = 30,
+ var properties: MutableMap<String, JsonNode> = hashMapOf()
+)
-data class RemoteScriptExecutionOutput(var requestId: String,
- var response: List<String>,
- var status: StatusType = StatusType.SUCCESS,
- var timestamp: Date = Date(),
- var payload: JsonNode)
+data class RemoteScriptExecutionOutput(
+ var requestId: String,
+ var response: List<String>,
+ var status: StatusType = StatusType.SUCCESS,
+ var timestamp: Date = Date(),
+ var payload: JsonNode
+)
-data class PrepareRemoteEnvInput(var requestId: String,
- var correlationId: String? = null,
- var remoteIdentifier: RemoteIdentifier? = null,
- var packages: JsonNode,
- var timeOut: Long = 120,
- var properties: MutableMap<String, JsonNode> = hashMapOf())
+data class PrepareRemoteEnvInput(
+ var requestId: String,
+ var correlationId: String? = null,
+ var remoteIdentifier: RemoteIdentifier? = null,
+ var packages: JsonNode,
+ var timeOut: Long = 120,
+ var properties: MutableMap<String, JsonNode> = hashMapOf()
+)
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt
index bb2c040f7..2f925dc5b 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt
@@ -48,6 +48,7 @@ interface ComponentNode {
* @author Brinda Santh
*/
open class ComponentNodeFactory : ApplicationContextAware {
+
private val log = LoggerFactory.getLogger(ComponentNodeFactory::class.java)
var componentNodes: MutableMap<String, ComponentNode> = hashMapOf()
@@ -65,4 +66,4 @@ open class ComponentNodeFactory : ApplicationContextAware {
componentNodes = context.getBeansOfType(ComponentNode::class.java)
log.info("Injected Component Nodes : {}", componentNodes)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappings.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/ApiDataUtils.kt
index 9cd00a3ba..24ed45c52 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappings.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/ApiDataUtils.kt
@@ -1,5 +1,6 @@
/*
* Copyright (C) 2019 Bell Canada.
+ * Modifications Copyright © 2018-2019 AT&T Intellectual Property.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,20 +14,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.onap.ccsdk.cds.blueprintsprocessor.core.utils
import com.fasterxml.jackson.databind.node.ObjectNode
-import com.google.common.base.Strings
import com.google.protobuf.Struct
import com.google.protobuf.util.JsonFormat
-import org.onap.ccsdk.cds.controllerblueprints.common.api.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
+import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers
+import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
+import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
+import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag
+import org.onap.ccsdk.cds.controllerblueprints.common.api.Status
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.controllerDate
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.toControllerDate
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
-import java.text.SimpleDateFormat
-import java.util.*
-
-private val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
// ACTION IDENTIFIER
@@ -55,8 +60,10 @@ fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader.toProto():
commonHeader.originatorId = this.originatorId
commonHeader.requestId = this.requestId
commonHeader.subRequestId = this.subRequestId
- commonHeader.timestamp = this.timestamp.toString()
- commonHeader.flag = this.flags?.toProto()
+ commonHeader.timestamp = this.timestamp.currentTimestamp()
+ if (this.flags != null) {
+ commonHeader.flag = this.flags!!.toProto()
+ }
return commonHeader.build()
}
@@ -65,10 +72,10 @@ fun CommonHeader.toJava(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.
commonHeader.originatorId = this.originatorId
commonHeader.requestId = this.requestId
commonHeader.subRequestId = this.subRequestId
- commonHeader.timestamp = if (!Strings.isNullOrEmpty(this.timestamp)) {
- formatter.parse(this.timestamp)
+ commonHeader.timestamp = if (!this.timestamp.isNullOrEmpty()) {
+ this.timestamp!!.toControllerDate()
} else {
- Date()
+ controllerDate()
}
commonHeader.flags = this.flag?.toJava()
return commonHeader
@@ -123,4 +130,75 @@ fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput.
JsonFormat.parser().merge(JacksonUtils.getJson(this.payload), struct)
executionServiceOuput.payload = struct.build()
return executionServiceOuput.build()
-} \ No newline at end of file
+}
+
+/** Create proto common header with [requestId] [subRequestId] and [originator] */
+fun createCommonHeaderProto(
+ requestId: String,
+ subRequestId: String,
+ originator: String
+) = CommonHeader.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setOriginatorId(originator)
+ .setRequestId(requestId)
+ .setSubRequestId(subRequestId).build()!!
+
+/** Create proto action identifiers with [name] [version] and [action] */
+fun createActionIdentifiersProto(
+ name: String,
+ version: String,
+ action: String
+) = ActionIdentifiers.newBuilder()
+ .setBlueprintName(name)
+ .setBlueprintVersion(version)
+ .setActionName(action)
+ .setMode(ACTION_MODE_SYNC)
+ .build()!!
+
+/** Create proto status with [message] and [code] */
+fun createStatus(
+ message: String,
+ code: Int
+) = Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(message)
+ .setCode(code)
+ .build()!!
+
+/** Create ExecutionServiceInput using [commonHeader], [actionIdentifier] and response payload [jsonContent] */
+fun createExecutionServiceInputProto(
+ commonHeader: CommonHeader,
+ actionIdentifier: ActionIdentifiers,
+ jsonContent: String
+): ExecutionServiceInput {
+
+ val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
+ JsonFormat.parser().merge(jsonContent, payloadBuilder)
+
+ return ExecutionServiceInput.newBuilder()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
+}
+
+/** Create ExecutionServiceOutput using [commonHeader], [actionIdentifier] [status]and
+ * response payload [jsonContent]
+ * */
+fun createExecutionServiceOutputProto(
+ commonHeader: CommonHeader,
+ actionIdentifier: ActionIdentifiers,
+ status: Status,
+ jsonContent: String
+): ExecutionServiceOutput {
+
+ val payloadBuilder = ExecutionServiceOutput.newBuilder().payloadBuilder
+ JsonFormat.parser().merge(jsonContent, payloadBuilder)
+
+ return ExecutionServiceOutput.newBuilder()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setStatus(status)
+ .setPayload(payloadBuilder.build())
+ .build()
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt
index 9eb95e679..426e43cda 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt
@@ -18,30 +18,56 @@ package org.onap.ccsdk.cds.blueprintsprocessor.core.utils
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
+import org.onap.ccsdk.cds.controllerblueprints.core.returnNullIfMissing
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
+object PayloadUtils {
-class PayloadUtils {
+ fun prepareRequestPayloadStr(workflowName: String, jsonNode: JsonNode): String {
+ return prepareRequestPayload(workflowName, jsonNode).asJsonString(false)
+ }
- companion object {
+ fun prepareRequestPayload(workflowName: String, jsonNode: JsonNode): JsonNode {
+ val objectNode = JacksonUtils.objectMapper.createObjectNode()
+ objectNode["$workflowName-request"] = jsonNode
+ return objectNode
+ }
- fun prepareInputsFromWorkflowPayload(bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode, workflowName: String) {
- val input = payload.get("$workflowName-request")
- bluePrintRuntimeService.assignWorkflowInputs(workflowName, input)
- }
+ fun getResponseDataFromPayload(workflowName: String, responsePayload: JsonNode): JsonNode {
+ return responsePayload.get("$workflowName-response").returnNullIfMissing()
+ ?: throw BluePrintProcessorException("failed to get property($workflowName-response)")
+ }
- fun prepareDynamicInputsFromWorkflowPayload(bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode, workflowName: String) {
- val input = payload.get("$workflowName-request")
- val propertyFields = input.get("$workflowName-properties")
- prepareDynamicInputsFromComponentPayload(bluePrintRuntimeService, propertyFields)
- }
+ fun prepareInputsFromWorkflowPayload(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ payload: JsonNode,
+ workflowName: String
+ ) {
+ val input = payload.get("$workflowName-request")
+ bluePrintRuntimeService.assignWorkflowInputs(workflowName, input)
+ }
+
+ fun prepareDynamicInputsFromWorkflowPayload(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ payload: JsonNode,
+ workflowName: String
+ ) {
+ val input = payload.get("$workflowName-request")
+ val propertyFields = input.get("$workflowName-properties")
+ prepareDynamicInputsFromComponentPayload(bluePrintRuntimeService, propertyFields)
+ }
- fun prepareDynamicInputsFromComponentPayload(bluePrintRuntimeService: BluePrintRuntimeService<*>, payload: JsonNode) {
- payload.fields().forEach { property ->
- val path = StringBuilder(BluePrintConstants.PATH_INPUTS)
- .append(BluePrintConstants.PATH_DIVIDER).append(property.key).toString()
- bluePrintRuntimeService.put(path, property.value)
- }
+ fun prepareDynamicInputsFromComponentPayload(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ payload: JsonNode
+ ) {
+ payload.fields().forEach { property ->
+ val path = StringBuilder(BluePrintConstants.PATH_INPUTS)
+ .append(BluePrintConstants.PATH_DIVIDER).append(property.key).toString()
+ bluePrintRuntimeService.put(path, property.value)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt
index 3dd629c13..c27285020 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt
@@ -17,4 +17,4 @@
package org.onap.ccsdk.cds.blueprintsprocessor.core
// TODO
-open class BluePrintPropertiesTest \ No newline at end of file
+open class BluePrintPropertiesTest
diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingTests.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt
index b1d7d144c..e8bdbf9ef 100644
--- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingTests.kt
+++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/BluePrintMappingsTest.kt
@@ -8,6 +8,7 @@ import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers
import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag
+import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp
import org.springframework.test.context.junit4.SpringRunner
import java.text.SimpleDateFormat
@@ -70,7 +71,9 @@ class BluePrintMappingsTest {
fun commonHeaderToJavaTest() {
val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build()
- val commonHeader = CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString).setFlag(flag).build()
+ val commonHeader =
+ CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString)
+ .setFlag(flag).build()
val commonHeader2 = commonHeader.toJava()
Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId)
@@ -96,12 +99,14 @@ class BluePrintMappingsTest {
Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId)
Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId)
Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId)
- Assert.assertEquals(commonHeader.timestamp.toString(), commonHeader2.timestamp)
+ Assert.assertEquals(commonHeader.timestamp.currentTimestamp(), commonHeader2.timestamp)
}
@Test
fun actionIdentifierToJavaTest() {
- val actionIdentifiers = ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0").setMode("Execution").build()
+ val actionIdentifiers =
+ ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0")
+ .setMode("Execution").build()
val actionIdentifiers2 = actionIdentifiers.toJava()
Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName)
@@ -129,4 +134,4 @@ class BluePrintMappingsTest {
Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion)
Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml
index a7d49c5ed..20835f0b2 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml
@@ -33,8 +33,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt
index 182d5defa..9e1be36a7 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt
@@ -35,19 +35,16 @@ open class BluePrintRestLibConfiguration
* Exposed Dependency Service by this Rest Lib Module
*/
fun BluePrintDependencyService.restLibPropertyService(): BluePrintRestLibPropertyService =
- instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY)
-
+ instance(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY)
fun BluePrintDependencyService.restClientService(selector: String): BlueprintWebClientService {
return restLibPropertyService().blueprintWebClientService(selector)
}
-
fun BluePrintDependencyService.restClientService(jsonNode: JsonNode): BlueprintWebClientService {
return restLibPropertyService().blueprintWebClientService(jsonNode)
}
-
class RestLibConstants {
companion object {
const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service"
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt
index ea32a1635..4c18f81ab 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt
@@ -35,11 +35,13 @@ open class SSLRestClientProperties : RestClientProperties() {
// FIXME("Define basic auth userName and password properties")
open class SSLBasicAuthRestClientProperties : SSLRestClientProperties() {
+
var basicAuth: BasicAuthRestClientProperties? = null
}
// FIXME("Define token properties")
open class SSLTokenAuthRestClientProperties : SSLRestClientProperties() {
+
var tokenAuth: TokenAuthRestClientProperties? = null
}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt
index a3da44f61..429931377 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/RestClientPropertiesDSL.kt
@@ -129,9 +129,9 @@ open class SSLRestClientPropertiesBuilder : RestClientPropertiesBuilder() {
}
open class SSLBasicAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() {
- //TODO()
+ // TODO()
}
open class SSLTokenAuthRestClientPropertiesBuilder : SSLRestClientPropertiesBuilder() {
- //TODO()
-} \ No newline at end of file
+ // TODO()
+}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt
index 5aaee24de..5b6691eff 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/filters/RestServerLoggingWebFilter.kt
@@ -24,15 +24,15 @@ import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
import reactor.util.context.Context
-
open class RestServerLoggingWebFilter : WebFilter {
override fun filter(serverWebExchange: ServerWebExchange, webFilterChain: WebFilterChain): Mono<Void> {
val loggingService = RestLoggerService()
loggingService.entering(serverWebExchange.request)
val filterChain = webFilterChain.filter(serverWebExchange).subscriberContext(
- Context.of(MDCContext, MDCContext()))
+ Context.of(MDCContext, MDCContext())
+ )
loggingService.exiting(serverWebExchange.request, serverWebExchange.response)
return filterChain
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt
index 9ce3beab6..540b3d9ad 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt
@@ -21,37 +21,42 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import java.nio.charset.Charset
-import java.util.*
+import java.util.Base64
-class BasicAuthRestClientService(private val restClientProperties:
- BasicAuthRestClientProperties) :
+class BasicAuthRestClientService(
+ private val restClientProperties:
+ BasicAuthRestClientProperties
+) :
BlueprintWebClientService {
override fun defaultHeaders(): Map<String, String> {
- val encodedCredentials = setBasicAuth(restClientProperties.username,
- restClientProperties.password)
+ val encodedCredentials = setBasicAuth(
+ restClientProperties.username,
+ restClientProperties.password
+ )
return mapOf(
HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials")
+ HttpHeaders.AUTHORIZATION to "Basic $encodedCredentials"
+ )
}
override fun host(uri: String): String {
return restClientProperties.url + uri
}
-
override fun convertToBasicHeaders(headers: Map<String, String>):
- Array<BasicHeader> {
+ Array<BasicHeader> {
val customHeaders: MutableMap<String, String> = headers.toMutableMap()
- //inject additionalHeaders
+ // inject additionalHeaders
customHeaders.putAll(verifyAdditionalHeaders(restClientProperties))
if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
val encodedCredentials = setBasicAuth(
restClientProperties.username,
- restClientProperties.password)
+ restClientProperties.password
+ )
customHeaders[HttpHeaders.AUTHORIZATION] =
"Basic $encodedCredentials"
}
@@ -61,7 +66,7 @@ class BasicAuthRestClientService(private val restClientProperties:
private fun setBasicAuth(username: String, password: String): String {
val credentialsString = "$username:$password"
return Base64.getEncoder().encodeToString(
- credentialsString.toByteArray(Charset.defaultCharset()))
+ credentialsString.toByteArray(Charset.defaultCharset())
+ )
}
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt
index 84ba7d414..8f528a2ef 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt
@@ -20,7 +20,14 @@ package org.onap.ccsdk.cds.blueprintsprocessor.rest.service
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.rest.*
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.PolicyManagerRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLTokenAuthRestClientProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.stereotype.Service
@@ -43,7 +50,7 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
open fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService {
val service = preInterceptor?.getInstance(jsonNode)
- ?: blueprintWebClientService(restClientProperties(jsonNode))
+ ?: blueprintWebClientService(restClientProperties(jsonNode))
return postInterceptor?.getInstance(jsonNode, service) ?: service
}
@@ -58,7 +65,8 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
fun restClientProperties(prefix: String): RestClientProperties {
val type = bluePrintPropertiesService.propertyBeanType(
- "$prefix.type", String::class.java)
+ "$prefix.type", String::class.java
+ )
return when (type) {
RestLibConstants.TYPE_BASIC_AUTH -> {
basicAuthRestClientProperties(prefix)
@@ -80,8 +88,10 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
policyManagerRestClientProperties(prefix)
}
else -> {
- throw BluePrintProcessorException("Rest adaptor($type) is" +
- " not supported")
+ throw BluePrintProcessorException(
+ "Rest adaptor($type) is" +
+ " not supported"
+ )
}
}
}
@@ -111,7 +121,8 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
}
else -> {
throw BluePrintProcessorException(
- "Rest adaptor($type) is not supported")
+ "Rest adaptor($type) is not supported"
+ )
}
}
}
@@ -138,24 +149,28 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
private fun tokenRestClientProperties(prefix: String):
TokenAuthRestClientProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, TokenAuthRestClientProperties::class.java)
+ prefix, TokenAuthRestClientProperties::class.java
+ )
}
private fun basicAuthRestClientProperties(prefix: String):
BasicAuthRestClientProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, BasicAuthRestClientProperties::class.java)
+ prefix, BasicAuthRestClientProperties::class.java
+ )
}
private fun sslBasicAuthRestClientProperties(prefix: String):
SSLRestClientProperties {
val sslProps: SSLBasicAuthRestClientProperties =
- bluePrintPropertiesService.propertyBeanType(
- prefix, SSLBasicAuthRestClientProperties::class.java)
+ bluePrintPropertiesService.propertyBeanType(
+ prefix, SSLBasicAuthRestClientProperties::class.java
+ )
val basicProps: BasicAuthRestClientProperties =
- bluePrintPropertiesService.propertyBeanType(
- prefix, BasicAuthRestClientProperties::class.java)
+ bluePrintPropertiesService.propertyBeanType(
+ prefix, BasicAuthRestClientProperties::class.java
+ )
sslProps.basicAuth = basicProps
return sslProps
}
@@ -164,11 +179,15 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
SSLRestClientProperties {
val sslProps: SSLTokenAuthRestClientProperties =
- bluePrintPropertiesService.propertyBeanType(prefix,
- SSLTokenAuthRestClientProperties::class.java)
+ bluePrintPropertiesService.propertyBeanType(
+ prefix,
+ SSLTokenAuthRestClientProperties::class.java
+ )
val basicProps: TokenAuthRestClientProperties =
- bluePrintPropertiesService.propertyBeanType(prefix,
- TokenAuthRestClientProperties::class.java)
+ bluePrintPropertiesService.propertyBeanType(
+ prefix,
+ TokenAuthRestClientProperties::class.java
+ )
sslProps.tokenAuth = basicProps
return sslProps
}
@@ -176,13 +195,15 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
private fun sslNoAuthRestClientProperties(prefix: String):
SSLRestClientProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, SSLRestClientProperties::class.java)
+ prefix, SSLRestClientProperties::class.java
+ )
}
private fun policyManagerRestClientProperties(prefix: String):
PolicyManagerRestClientProperties {
return bluePrintPropertiesService.propertyBeanType(
- prefix, PolicyManagerRestClientProperties::class.java)
+ prefix, PolicyManagerRestClientProperties::class.java
+ )
}
interface PreInterceptor {
@@ -197,5 +218,3 @@ open class BluePrintRestLibPropertyService(private var bluePrintPropertiesServic
fun getInstance(selector: String, service: BlueprintWebClientService): BlueprintWebClientService
}
}
-
-
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt
index 3e31bf9ec..3c8d92c26 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt
@@ -23,7 +23,12 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.io.IOUtils
import org.apache.http.client.ClientProtocolException
-import org.apache.http.client.methods.*
+import org.apache.http.client.methods.HttpDelete
+import org.apache.http.client.methods.HttpGet
+import org.apache.http.client.methods.HttpPatch
+import org.apache.http.client.methods.HttpPost
+import org.apache.http.client.methods.HttpPut
+import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
@@ -57,8 +62,12 @@ interface BlueprintWebClientService {
/** High performance non blocking Retry function, If execution block [block] throws BluePrintRetryException
* exception then this will perform wait and retrigger accoring to times [times] with delay [delay]
*/
- suspend fun <T> retry(times: Int = 1, initialDelay: Long = 0, delay: Long = 1000,
- block: suspend (Int) -> T): T {
+ suspend fun <T> retry(
+ times: Int = 1,
+ initialDelay: Long = 0,
+ delay: Long = 1000,
+ block: suspend (Int) -> T
+ ): T {
val exceptionBlock = { e: Exception ->
if (e !is BluePrintRetryException) {
throw e
@@ -71,8 +80,12 @@ interface BlueprintWebClientService {
return this.exchangeResource(methodType, path, request, defaultHeaders())
}
- fun exchangeResource(methodType: String, path: String, request: String,
- headers: Map<String, String>): WebClientResponse<String> {
+ fun exchangeResource(
+ methodType: String,
+ path: String,
+ request: String,
+ headers: Map<String, String>
+ ): WebClientResponse<String> {
/**
* TODO: Basic headers in the implementations of this client do not get added
* in blocking version, whereas in NB version defaultHeaders get added.
@@ -86,11 +99,12 @@ interface BlueprintWebClientService {
HttpMethod.PUT -> put(path, request, convertedHeaders, String::class.java)
HttpMethod.PATCH -> patch(path, request, convertedHeaders, String::class.java)
else -> throw BluePrintProcessorException(
- "Unsupported methodType($methodType) attempted on path($path)")
+ "Unsupported methodType($methodType) attempted on path($path)"
+ )
}
}
- //TODO: convert to multi-map
+ // TODO: convert to multi-map
fun convertToBasicHeaders(headers: Map<String, String>): Array<BasicHeader> {
return headers.map { BasicHeader(it.key, it.value) }.toTypedArray()
}
@@ -145,8 +159,10 @@ interface BlueprintWebClientService {
@Throws(IOException::class, ClientProtocolException::class)
private fun <T> performCallAndExtractTypedWebClientResponse(
- httpUriRequest: HttpUriRequest, responseType: Class<T>):
- WebClientResponse<T> {
+ httpUriRequest: HttpUriRequest,
+ responseType: Class<T>
+ ):
+ WebClientResponse<T> {
val httpResponse = httpClient().execute(httpUriRequest)
val statusCode = httpResponse.statusLine.statusCode
httpResponse.entity.content.use {
@@ -164,7 +180,7 @@ interface BlueprintWebClientService {
}
suspend fun <T> getNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>):
- WebClientResponse<T> = withContext(Dispatchers.IO) {
+ WebClientResponse<T> = withContext(Dispatchers.IO) {
get(path, additionalHeaders!!, responseType)
}
@@ -176,8 +192,12 @@ interface BlueprintWebClientService {
return postNB(path, request, additionalHeaders, String::class.java)
}
- suspend fun <T> postNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?,
- responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) {
+ suspend fun <T> postNB(
+ path: String,
+ request: Any,
+ additionalHeaders: Array<BasicHeader>?,
+ responseType: Class<T>
+ ): WebClientResponse<T> = withContext(Dispatchers.IO) {
post(path, request, additionalHeaders!!, responseType)
}
@@ -185,14 +205,20 @@ interface BlueprintWebClientService {
return putNB(path, request, null, String::class.java)
}
- suspend fun putNB(path: String, request: Any,
- additionalHeaders: Array<BasicHeader>?): WebClientResponse<String> {
+ suspend fun putNB(
+ path: String,
+ request: Any,
+ additionalHeaders: Array<BasicHeader>?
+ ): WebClientResponse<String> {
return putNB(path, request, additionalHeaders, String::class.java)
}
- suspend fun <T> putNB(path: String, request: Any,
- additionalHeaders: Array<BasicHeader>?,
- responseType: Class<T>): WebClientResponse<T> = withContext(Dispatchers.IO) {
+ suspend fun <T> putNB(
+ path: String,
+ request: Any,
+ additionalHeaders: Array<BasicHeader>?,
+ responseType: Class<T>
+ ): WebClientResponse<T> = withContext(Dispatchers.IO) {
put(path, request, additionalHeaders!!, responseType)
}
@@ -201,36 +227,42 @@ interface BlueprintWebClientService {
}
suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?):
- WebClientResponse<String> {
+ WebClientResponse<String> {
return deleteNB(path, additionalHeaders, String::class.java)
}
suspend fun <T> deleteNB(path: String, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>):
- WebClientResponse<T> = withContext(Dispatchers.IO) {
+ WebClientResponse<T> = withContext(Dispatchers.IO) {
delete(path, additionalHeaders!!, responseType)
}
suspend fun <T> patchNB(path: String, request: Any, additionalHeaders: Array<BasicHeader>?, responseType: Class<T>):
- WebClientResponse<T> = withContext(Dispatchers.IO) {
+ WebClientResponse<T> = withContext(Dispatchers.IO) {
patch(path, request, additionalHeaders!!, responseType)
}
suspend fun exchangeNB(methodType: String, path: String, request: Any): WebClientResponse<String> {
- return exchangeNB(methodType, path, request, hashMapOf(),
- String::class.java)
+ return exchangeNB(
+ methodType, path, request, hashMapOf(),
+ String::class.java
+ )
}
suspend fun exchangeNB(methodType: String, path: String, request: Any, additionalHeaders: Map<String, String>?):
- WebClientResponse<String> {
+ WebClientResponse<String> {
return exchangeNB(methodType, path, request, additionalHeaders, String::class.java)
}
- suspend fun <T> exchangeNB(methodType: String, path: String, request: Any,
- additionalHeaders: Map<String, String>?,
- responseType: Class<T>): WebClientResponse<T> {
+ suspend fun <T> exchangeNB(
+ methodType: String,
+ path: String,
+ request: Any,
+ additionalHeaders: Map<String, String>?,
+ responseType: Class<T>
+ ): WebClientResponse<T> {
- //TODO: possible inconsistency
- //NOTE: this basic headers function is different from non-blocking
+ // TODO: possible inconsistency
+ // NOTE: this basic headers function is different from non-blocking
val convertedHeaders: Array<BasicHeader> = basicHeaders(additionalHeaders!!)
return when (HttpMethod.resolve(methodType)) {
HttpMethod.GET -> getNB(path, convertedHeaders, responseType)
@@ -259,7 +291,7 @@ interface BlueprintWebClientService {
}
private fun basicHeaders(headers: Map<String, String>?):
- Array<BasicHeader> {
+ Array<BasicHeader> {
val basicHeaders = mutableListOf<BasicHeader>()
defaultHeaders().forEach { (name, value) ->
basicHeaders.add(BasicHeader(name, value))
@@ -278,18 +310,18 @@ interface BlueprintWebClientService {
.build()
}
- //TODO maybe there could be cases where we care about return headers?
+ // TODO maybe there could be cases where we care about return headers?
data class WebClientResponse<T>(val status: Int, val body: T)
fun verifyAdditionalHeaders(restClientProperties: RestClientProperties): Map<String, String> {
val customHeaders: MutableMap<String, String> = mutableMapOf()
- //Extract additionalHeaders from the requestProperties and
- //throw an error if HttpHeaders.AUTHORIZATION key (headers are case-insensitive)
+ // Extract additionalHeaders from the requestProperties and
+ // throw an error if HttpHeaders.AUTHORIZATION key (headers are case-insensitive)
restClientProperties.additionalHeaders?.let {
if (it.keys.map { k -> k.toLowerCase().trim() }.contains(HttpHeaders.AUTHORIZATION.toLowerCase())) {
val errMsg = "Error in definition of endpoint ${restClientProperties.url}." +
- " User-supplied \"additionalHeaders\" cannot contain AUTHORIZATION header with" +
- " auth-type \"${RestLibConstants.TYPE_BASIC_AUTH}\""
+ " User-supplied \"additionalHeaders\" cannot contain AUTHORIZATION header with" +
+ " auth-type \"${RestLibConstants.TYPE_BASIC_AUTH}\""
WebClientUtils.log.error(errMsg)
throw BluePrintProcessorException(errMsg)
} else {
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt
index 969de836c..313710745 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestLoggerService.kt
@@ -16,10 +16,17 @@
package org.onap.ccsdk.cds.blueprintsprocessor.rest.service
-import kotlinx.coroutines.*
+import kotlinx.coroutines.AbstractCoroutine
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.GlobalScope
+import kotlinx.coroutines.InternalCoroutinesApi
+import kotlinx.coroutines.handleCoroutineException
+import kotlinx.coroutines.newCoroutineContext
import kotlinx.coroutines.reactor.ReactorContext
import kotlinx.coroutines.reactor.asCoroutineContext
import org.apache.http.message.BasicHeader
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_INVOCATION_ID
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_PARTNER_NAME
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.ONAP_REQUEST_ID
@@ -37,7 +44,7 @@ import java.net.InetAddress
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
-import java.util.*
+import java.util.UUID
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
@@ -51,8 +58,7 @@ class RestLoggerService {
fun httpInvoking(headers: Array<BasicHeader>) {
headers.plusElement(BasicHeader(ONAP_REQUEST_ID, MDC.get("InvocationID").defaultToUUID()))
headers.plusElement(BasicHeader(ONAP_INVOCATION_ID, UUID.randomUUID().toString()))
- val partnerName = System.getProperty("APPNAME") ?: "BlueprintsProcessor"
- headers.plusElement(BasicHeader(ONAP_PARTNER_NAME, partnerName))
+ headers.plusElement(BasicHeader(ONAP_PARTNER_NAME, BluePrintConstants.APP_NAME))
}
}
@@ -79,8 +85,7 @@ class RestLoggerService {
val resHeaders = response.headers
resHeaders[ONAP_REQUEST_ID] = MDC.get("RequestID")
resHeaders[ONAP_INVOCATION_ID] = MDC.get("InvocationID")
- val partnerName = System.getProperty("APPNAME") ?: "BlueprintsProcessor"
- resHeaders[ONAP_PARTNER_NAME] = partnerName
+ resHeaders[ONAP_PARTNER_NAME] = BluePrintConstants.APP_NAME
} catch (e: Exception) {
log.warn("couldn't set response headers", e)
} finally {
@@ -89,17 +94,19 @@ class RestLoggerService {
}
}
-
/** Used in Rest controller API methods to populate MDC context to nested coroutines from reactor web filter context. */
@UseExperimental(InternalCoroutinesApi::class)
-fun <T> monoMdc(context: CoroutineContext = EmptyCoroutineContext,
- block: suspend CoroutineScope.() -> T?): Mono<T> = Mono.create { sink ->
+fun <T> monoMdc(
+ context: CoroutineContext = EmptyCoroutineContext,
+ block: suspend CoroutineScope.() -> T?
+): Mono<T> = Mono.create { sink ->
val reactorContext = (context[ReactorContext]?.context?.putAll(sink.currentContext())
- ?: sink.currentContext()).asCoroutineContext()
+ ?: sink.currentContext()).asCoroutineContext()
/** Populate MDC context only if present in Reactor Context */
- val newContext = if (!reactorContext.context.isEmpty
- && reactorContext.context.hasKey(MDCContext)) {
+ val newContext = if (!reactorContext.context.isEmpty &&
+ reactorContext.context.hasKey(MDCContext)
+ ) {
val mdcContext = reactorContext.context.get<MDCContext>(MDCContext)
GlobalScope.newCoroutineContext(context + reactorContext + mdcContext)
} else GlobalScope.newCoroutineContext(context + reactorContext)
@@ -111,9 +118,10 @@ fun <T> monoMdc(context: CoroutineContext = EmptyCoroutineContext,
@InternalCoroutinesApi
class MonoMDCCoroutine<in T>(
- parentContext: CoroutineContext,
- private val sink: MonoSink<T>
+ parentContext: CoroutineContext,
+ private val sink: MonoSink<T>
) : AbstractCoroutine<T>(parentContext, true), Disposable {
+
private var disposed = false
override fun onCompleted(value: T) {
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt
index 0ef1757e2..86e3ced06 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLRestClientService.kt
@@ -17,6 +17,7 @@
package org.onap.ccsdk.cds.blueprintsprocessor.rest.service
+import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
@@ -32,7 +33,6 @@ import java.io.File
import java.io.FileInputStream
import java.security.KeyStore
import java.security.cert.X509Certificate
-import org.apache.http.conn.ssl.NoopHostnameVerifier
class SSLRestClientService(private val restClientProperties: SSLRestClientProperties) :
BlueprintWebClientService {
@@ -44,8 +44,8 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper
}
private fun getAuthService(): BlueprintWebClientService? {
- //type,url and additional headers don't get carried over to TokenAuthRestClientProperties from SSLTokenAuthRestClientProperties
- //set them in auth obj to be consistent. TODO: refactor
+ // type,url and additional headers don't get carried over to TokenAuthRestClientProperties from SSLTokenAuthRestClientProperties
+ // set them in auth obj to be consistent. TODO: refactor
return when (restClientProperties) {
is SSLBasicAuthRestClientProperties -> {
val basicAuthProps = restClientProperties.basicAuth!!
@@ -62,7 +62,7 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper
TokenAuthRestClientService(token)
}
else -> {
- //Returns null for No auth
+ // Returns null for No auth
null
}
}
@@ -74,7 +74,8 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper
}
return mapOf(
HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE)
+ HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE
+ )
}
override fun host(uri: String): String {
@@ -104,7 +105,7 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper
}
sslContext.loadTrustMaterial(File(sslTrust), sslTrustPwd.toCharArray(), acceptingTrustStrategy)
- var csf : SSLConnectionSocketFactory
+ var csf: SSLConnectionSocketFactory
if (sslTrustIgnoreHostname) {
csf = SSLConnectionSocketFactory(sslContext.build(), NoopHostnameVerifier())
} else {
@@ -123,14 +124,16 @@ class SSLRestClientService(private val restClientProperties: SSLRestClientProper
override fun convertToBasicHeaders(headers: Map<String, String>): Array<BasicHeader> {
val mergedDefaultAndSuppliedHeaders = defaultHeaders().plus(headers)
- //During the initialization, getAuthService() sets the auth variable.
- //If it's not null, then we have an authentication mechanism.
- //If null - indicates no-auth used
+ // During the initialization, getAuthService() sets the auth variable.
+ // If it's not null, then we have an authentication mechanism.
+ // If null - indicates no-auth used
if (auth != null) {
return auth!!.convertToBasicHeaders(mergedDefaultAndSuppliedHeaders)
}
- //inject additionalHeaders
- return super.convertToBasicHeaders(mergedDefaultAndSuppliedHeaders
- .plus(verifyAdditionalHeaders(restClientProperties)))
+ // inject additionalHeaders
+ return super.convertToBasicHeaders(
+ mergedDefaultAndSuppliedHeaders
+ .plus(verifyAdditionalHeaders(restClientProperties))
+ )
}
}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt
index 73b534143..57702f8ac 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt
@@ -21,21 +21,24 @@ import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
-class TokenAuthRestClientService(private val restClientProperties:
- TokenAuthRestClientProperties) :
+class TokenAuthRestClientService(
+ private val restClientProperties:
+ TokenAuthRestClientProperties
+) :
BlueprintWebClientService {
override fun defaultHeaders(): Map<String, String> {
return mapOf(
HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE,
HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE,
- HttpHeaders.AUTHORIZATION to restClientProperties.token!!)
+ HttpHeaders.AUTHORIZATION to restClientProperties.token!!
+ )
}
override fun convertToBasicHeaders(headers: Map<String, String>):
- Array<BasicHeader> {
+ Array<BasicHeader> {
val customHeaders: MutableMap<String, String> = headers.toMutableMap()
- //inject additionalHeaders
+ // inject additionalHeaders
customHeaders.putAll(verifyAdditionalHeaders(restClientProperties))
if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
customHeaders[HttpHeaders.AUTHORIZATION] = restClientProperties.token!!
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt
index 42006569f..ff4d54730 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt
@@ -32,4 +32,4 @@ class WebClientUtils {
fun logResponse(): HttpResponseInterceptor =
HttpResponseInterceptor { response, _ -> log.info("Response status(${response.statusLine.statusCode} - ${response.statusLine.reasonPhrase})") }
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt
index 1e4518a8c..53047d4a8 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt
@@ -41,50 +41,59 @@ import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, BluePrintPropertyConfiguration::class,
- BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.restclient.sample.type=basic-auth",
- "blueprintsprocessor.restclient.sample.url=http://localhost:8080",
- "blueprintsprocessor.restclient.sample.userId=sampleuser",
- "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth",
- "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443",
- "blueprintsprocessor.restclient.sslbasic.username=admin",
- "blueprintsprocessor.restclient.sslbasic.password=cds",
- "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12",
- "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12",
- "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit",
- "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth",
- "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443",
- "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908",
- "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12",
- "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12",
- "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit",
- "blueprintsprocessor.restclient.ssl.type=ssl-no-auth",
- "blueprintsprocessor.restclient.ssl.url=https://localhost:8443",
- "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12",
- "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12",
- "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit",
- "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12",
- "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit"
-])
+@ContextConfiguration(
+ classes = [BluePrintRestLibConfiguration::class, BluePrintPropertyConfiguration::class,
+ BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.restclient.sample.type=basic-auth",
+ "blueprintsprocessor.restclient.sample.url=http://localhost:8080",
+ "blueprintsprocessor.restclient.sample.userId=sampleuser",
+ "blueprintsprocessor.restclient.sslbasic.type=ssl-basic-auth",
+ "blueprintsprocessor.restclient.sslbasic.url=https://localhost:8443",
+ "blueprintsprocessor.restclient.sslbasic.username=admin",
+ "blueprintsprocessor.restclient.sslbasic.password=cds",
+ "blueprintsprocessor.restclient.sslbasic.keyStoreInstance=PKCS12",
+ "blueprintsprocessor.restclient.sslbasic.sslTrust=src/test/resources/keystore.p12",
+ "blueprintsprocessor.restclient.sslbasic.sslTrustPassword=changeit",
+ "blueprintsprocessor.restclient.ssltoken.type=ssl-token-auth",
+ "blueprintsprocessor.restclient.ssltoken.url=https://localhost:8443",
+ "blueprintsprocessor.restclient.ssltoken.token=72178473kjshdkjgvbsdkjv903274908",
+ "blueprintsprocessor.restclient.ssltoken.keyStoreInstance=PKCS12",
+ "blueprintsprocessor.restclient.ssltoken.sslTrust=src/test/resources/keystore.p12",
+ "blueprintsprocessor.restclient.ssltoken.sslTrustPassword=changeit",
+ "blueprintsprocessor.restclient.ssl.type=ssl-no-auth",
+ "blueprintsprocessor.restclient.ssl.url=https://localhost:8443",
+ "blueprintsprocessor.restclient.ssl.keyStoreInstance=PKCS12",
+ "blueprintsprocessor.restclient.ssl.sslTrust=src/test/resources/keystore.p12",
+ "blueprintsprocessor.restclient.ssl.sslTrustPassword=changeit",
+ "blueprintsprocessor.restclient.ssl.sslKey=src/test/resources/keystore.p12",
+ "blueprintsprocessor.restclient.ssl.sslKeyPassword=changeit"
+ ]
+)
class BluePrintRestLibPropertyServiceTest {
+
@Autowired
lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService
@Test
fun testRestClientProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.sample")
+ "blueprintsprocessor.restclient.sample"
+ )
assertNotNull(properties, "failed to create property bean")
- assertNotNull(properties.url, "failed to get url property in" +
- " property bean")
+ assertNotNull(
+ properties.url, "failed to get url property in" +
+ " property bean"
+ )
}
@Test
fun testSSLBasicProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.sslbasic")
+ "blueprintsprocessor.restclient.sslbasic"
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLBasicAuthRestClientProperties =
properties as SSLBasicAuthRestClientProperties
@@ -99,7 +108,8 @@ class BluePrintRestLibPropertyServiceTest {
@Test
fun testSSLTokenProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.ssltoken")
+ "blueprintsprocessor.restclient.ssltoken"
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLTokenAuthRestClientProperties =
@@ -114,7 +124,8 @@ class BluePrintRestLibPropertyServiceTest {
@Test
fun testSSLNoAuthProperties() {
val properties = bluePrintRestLibPropertyService.restClientProperties(
- "blueprintsprocessor.restclient.ssl")
+ "blueprintsprocessor.restclient.ssl"
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLRestClientProperties =
@@ -127,12 +138,12 @@ class BluePrintRestLibPropertyServiceTest {
assertEquals(p.sslKeyPassword, "changeit")
}
-
@Test
fun testSSLBasicPropertiesAsJson() {
val actualObj: JsonNode = defaultMapper.readTree(sslBasicAuthEndpointWithHeadersField())
val properties = bluePrintRestLibPropertyService.restClientProperties(
- actualObj)
+ actualObj
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLBasicAuthRestClientProperties = properties as SSLBasicAuthRestClientProperties
@@ -166,7 +177,8 @@ class BluePrintRestLibPropertyServiceTest {
fun testSSLNoAuthPropertiesAsJson() {
val actualObj: JsonNode = defaultMapper.readTree(sslNoAuthEndpointWithHeadersField())
val properties = bluePrintRestLibPropertyService.restClientProperties(
- actualObj)
+ actualObj
+ )
assertNotNull(properties, "failed to create property bean")
val p: SSLRestClientProperties =
@@ -185,8 +197,10 @@ class BluePrintRestLibPropertyServiceTest {
fun testBlueprintWebClientService() {
val blueprintWebClientService = bluePrintRestLibPropertyService
.blueprintWebClientService("sample")
- assertNotNull(blueprintWebClientService,
- "failed to create blueprintWebClientService")
+ assertNotNull(
+ blueprintWebClientService,
+ "failed to create blueprintWebClientService"
+ )
}
@Test
@@ -197,7 +211,7 @@ class BluePrintRestLibPropertyServiceTest {
assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService")
}
- //pass the result of $typeEndpointWithHeadersField() output with and without headers to compare.
+ // pass the result of $typeEndpointWithHeadersField() output with and without headers to compare.
private fun validateHeadersDidNotChangeWithEmptyAdditionalHeaders(noHeaders: String, withHeaders: String) {
val parsedObj: JsonNode = defaultMapper.readTree(noHeaders)
val bpWebClientService =
@@ -208,7 +222,7 @@ class BluePrintRestLibPropertyServiceTest {
val bpWebClientServiceWithHeaders =
bluePrintRestLibPropertyService.blueprintWebClientService(parsedObjWithHeaders)
val extractedHeadersWithAdditionalHeaders = bpWebClientServiceWithHeaders.convertToBasicHeaders(mapOf())
- //Array<BasicHeader<>> -> Map<String,String>
+ // Array<BasicHeader<>> -> Map<String,String>
val headersMap = extractedHeaders.map { it.name to it.value }.toMap()
val additionalHeadersMap = extractedHeadersWithAdditionalHeaders.map { it.name to it.value }.toMap()
assertEquals(headersMap, additionalHeadersMap)
@@ -256,18 +270,20 @@ class BluePrintRestLibPropertyServiceTest {
val bpWebClientService =
bluePrintRestLibPropertyService.blueprintWebClientService(parsedObj)
val extractedHeaders = bpWebClientService.convertToBasicHeaders(mapOf())
- assertEquals(MediaType.APPLICATION_XML.toString(),
- extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!!)
+ assertEquals(
+ MediaType.APPLICATION_XML.toString(),
+ extractedHeaders.filter { it.name == HttpHeaders.CONTENT_TYPE }[0].value!!
+ )
}
@Test
fun `BasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() {
- //default content type is application/json
+ // default content type is application/json
val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(contentTypeAdditionalHeader)
additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson)
}
- //called from within "assertFailsWith(exceptionClass = BluePrintProcessorException::class) {"
+ // called from within "assertFailsWith(exceptionClass = BluePrintProcessorException::class) {"
private fun attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson: String) {
val parsedObj: JsonNode = defaultMapper.readTree(endPointWithHeadersJson)
val bpWebClientService =
@@ -281,7 +297,7 @@ class BluePrintRestLibPropertyServiceTest {
val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuth)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
- //spec says headers are case insensitive...
+ // spec says headers are case insensitive...
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
val endPointWithHeadersJson = basicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
@@ -309,7 +325,7 @@ class BluePrintRestLibPropertyServiceTest {
@Test
fun `TokenAuth WebClientService additionalHeaders can overwrite default Content-Type`() {
- //default content type is application/json
+ // default content type is application/json
val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(contentTypeAdditionalHeader)
additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson)
}
@@ -320,14 +336,14 @@ class BluePrintRestLibPropertyServiceTest {
val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuth)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
- //spec says headers are case insensitive...
+ // spec says headers are case insensitive...
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
val endPointWithHeadersJson = sslTokenAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
}
- //TESTS FOR SSL BASIC AUTH headers
+ // TESTS FOR SSL BASIC AUTH headers
@Test
fun `SSLBasicAuth WebClientService with empty additionalHeaders does not modify headers`() {
val endPointJson = sslBasicAuthEndpointWithHeadersField()
@@ -349,7 +365,7 @@ class BluePrintRestLibPropertyServiceTest {
@Test
fun `SSLBasicAuth WebClientService additionalHeaders can overwrite default Content-Type`() {
- //default content type is application/json
+ // default content type is application/json
val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(contentTypeAdditionalHeader)
additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson)
}
@@ -360,14 +376,14 @@ class BluePrintRestLibPropertyServiceTest {
val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuth)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
- //spec says headers are case insensitive...
+ // spec says headers are case insensitive...
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
val endPointWithHeadersJson = sslBasicAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
}
- //SSL-NO-AUTH headers tests
+ // SSL-NO-AUTH headers tests
@Test
fun `SSLNoAuth WebClientService with empty additionalHeaders does not modify headers`() {
val endPointJson = sslNoAuthEndpointWithHeadersField()
@@ -389,7 +405,7 @@ class BluePrintRestLibPropertyServiceTest {
@Test
fun `SSLNoAuth WebClientService additionalHeaders can overwrite default Content-Type`() {
- //default content type is application/json
+ // default content type is application/json
val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(contentTypeAdditionalHeader)
additionalHeadersChangedContentTypeToAPPLICATION_XML(endPointWithHeadersJson)
}
@@ -400,7 +416,7 @@ class BluePrintRestLibPropertyServiceTest {
val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuth)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
}
- //spec says headers are case insensitive...
+ // spec says headers are case insensitive...
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
val endPointWithHeadersJson = sslNoAuthEndpointWithHeadersField(additionalHeadersWithAuthLowercased)
attemptToPutAuthorizationHeaderIntoAdditionalHeaders(endPointWithHeadersJson)
@@ -412,12 +428,15 @@ class BluePrintRestLibPropertyServiceTest {
val expectedTokenAuthDefaultHeaders = mapOf<String, String>(
"Content-Type" to "application/json",
"Accept" to "application/json",
- "Authorization" to "72178473kjshdkjgvbsdkjv903274908")
+ "Authorization" to "72178473kjshdkjgvbsdkjv903274908"
+ )
- val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField(""",
+ val endPointWithHeadersJsonWithBasicAuthHeader = basicAuthEndpointWithHeadersField(
+ """,
"additionalHeaders" : {
"authorization": "Basic aGF2ZTphbmljZWRheQo="
- }""".trimIndent())
+ }""".trimIndent()
+ )
private fun sslTokenAuthEndpointWithHeadersField(headers: String = ""): String =
"""{
@@ -455,7 +474,7 @@ class BluePrintRestLibPropertyServiceTest {
"sslKeyPassword" : "changeit"$headers
}""".trimIndent()
- //Don't forget to supply "," as the first char to make valid JSON
+ // Don't forget to supply "," as the first char to make valid JSON
private fun basicAuthEndpointWithHeadersField(headers: String = ""): String =
"""{
"type": "basic-auth",
@@ -496,4 +515,3 @@ class BluePrintRestLibPropertyServiceTest {
}""".trimIndent()
}
}
-
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt
index 15133fa8a..f82fc6124 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientPropertiesDSLTest.kt
@@ -24,7 +24,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import kotlin.test.assertNotNull
class RestClientPropertiesDSLTest {
-
+
@Test
fun testBasicAuthRestClientProperties() {
val properties = BluePrintTypes.dslBasicAuthRestClientProperties {
@@ -56,4 +56,4 @@ class RestClientPropertiesDSLTest {
}
assertNotNull(properties, "failed to get dslSSLRestClientProperties")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt
index 05f32904a..fa357e1fe 100644
--- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt
@@ -48,45 +48,56 @@ import org.springframework.security.web.server.SecurityWebFilterChain
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.DeleteMapping
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.PatchMapping
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.PutMapping
+import org.springframework.web.bind.annotation.RequestHeader
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RestController
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class])
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
-@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, SampleController::class,
- SecurityConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-[
- "server.port=8443",
- "server.ssl.enabled=true",
- "server.ssl.key-store=classpath:keystore.p12",
- "server.ssl.key-store-password=changeit",
- "server.ssl.keyStoreType=PKCS12",
- "server.ssl.keyAlias=tomcat",
- "blueprintsprocessor.restclient.sample.type=basic-auth",
- "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8081",
- "blueprintsprocessor.restclient.sample.username=admin",
- "blueprintsprocessor.restclient.sample.password=jans",
- "blueprintsprocessor.restclient.test.type=ssl-basic-auth",
- "blueprintsprocessor.restclient.test.url=https://localhost:8443",
- "blueprintsprocessor.restclient.test.username=admin",
- "blueprintsprocessor.restclient.test.password=jans",
- "blueprintsprocessor.restclient.test.keyStoreInstance=PKCS12",
- "blueprintsprocessor.restclient.test.sslTrust=src/test/resources/keystore.p12",
- "blueprintsprocessor.restclient.test.sslTrustPassword=changeit"
-])
+@ContextConfiguration(
+ classes = [BluePrintRestLibConfiguration::class, SampleController::class,
+ SecurityConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ [
+ "server.port=8443",
+ "server.ssl.enabled=true",
+ "server.ssl.key-store=classpath:keystore.p12",
+ "server.ssl.key-store-password=changeit",
+ "server.ssl.keyStoreType=PKCS12",
+ "server.ssl.keyAlias=tomcat",
+ "blueprintsprocessor.restclient.sample.type=basic-auth",
+ "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8081",
+ "blueprintsprocessor.restclient.sample.username=admin",
+ "blueprintsprocessor.restclient.sample.password=jans",
+ "blueprintsprocessor.restclient.test.type=ssl-basic-auth",
+ "blueprintsprocessor.restclient.test.url=https://localhost:8443",
+ "blueprintsprocessor.restclient.test.username=admin",
+ "blueprintsprocessor.restclient.test.password=jans",
+ "blueprintsprocessor.restclient.test.keyStoreInstance=PKCS12",
+ "blueprintsprocessor.restclient.test.sslTrust=src/test/resources/keystore.p12",
+ "blueprintsprocessor.restclient.test.sslTrustPassword=changeit"
+ ]
+)
class RestClientServiceTest {
@Autowired
lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService
@Autowired
- lateinit var httpHandler : HttpHandler
+ lateinit var httpHandler: HttpHandler
- lateinit var http : WebServer
+ lateinit var http: WebServer
fun localPort() = http.port
@@ -106,21 +117,26 @@ class RestClientServiceTest {
@Test
fun testPatch() {
val restClientService = bluePrintRestLibPropertyService
- .blueprintWebClientService("sample")
+ .blueprintWebClientService("sample")
val response = restClientService.exchangeResource(
- HttpMethod.PATCH.name, "/sample/name", "")
- assertEquals("Patch request successful", response.body,
- "failed to get patch response")
+ HttpMethod.PATCH.name, "/sample/name", ""
+ )
+ assertEquals(
+ "Patch request successful", response.body,
+ "failed to get patch response"
+ )
}
@Test
fun testBaseAuth() {
val restClientService = bluePrintRestLibPropertyService
- .blueprintWebClientService("sample")
+ .blueprintWebClientService("sample")
val headers = mutableMapOf<String, String>()
headers["X-Transaction-Id"] = "1234"
- val response = restClientService.exchangeResource(HttpMethod.GET.name,
- "/sample/name", "")
+ val response = restClientService.exchangeResource(
+ HttpMethod.GET.name,
+ "/sample/name", ""
+ )
assertNotNull(response.body, "failed to get response")
}
@@ -135,12 +151,15 @@ class RestClientServiceTest {
val mapper = ObjectMapper()
val actualObj: JsonNode = mapper.readTree(json)
val restClientService = bluePrintRestLibPropertyService
- .blueprintWebClientService(actualObj)
- lateinit var res:String
+ .blueprintWebClientService(actualObj)
+ lateinit var res: String
runBlocking {
val get = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.GET.name,
- "/sample/basic", "").body}
+ restClientService.exchangeNB(
+ HttpMethod.GET.name,
+ "/sample/basic", ""
+ ).body
+ }
get.start()
res = get.await()
}
@@ -151,7 +170,7 @@ class RestClientServiceTest {
@Test
fun testSampleAaiReq() {
val restClientService = bluePrintRestLibPropertyService
- .blueprintWebClientService("test")
+ .blueprintWebClientService("test")
val headers = mutableMapOf<String, String>()
headers["X-TransactionId"] = "9999"
headers["X-FromAppId"] = "AAI"
@@ -171,34 +190,52 @@ class RestClientServiceTest {
lateinit var res6: String
runBlocking {
val get1 = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.GET.name,
- "/sample/aai/v14/business/customers", "", headers,
- Customer::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.GET.name,
+ "/sample/aai/v14/business/customers", "", headers,
+ Customer::class.java
+ ).body
+ }
val get2 = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.GET.name,
- "/sample/aai/v14/business/customers", "", headers,
- Customer::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.GET.name,
+ "/sample/aai/v14/business/customers", "", headers,
+ Customer::class.java
+ ).body
+ }
val post = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.POST.name,
- "/sample/aai/v14/business/customers", post1, headers,
- String::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.POST.name,
+ "/sample/aai/v14/business/customers", post1, headers,
+ String::class.java
+ ).body
+ }
val put = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.PUT.name,
- "/sample/aai/v14/business/customers", post1, headers,
- String::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.PUT.name,
+ "/sample/aai/v14/business/customers", post1, headers,
+ String::class.java
+ ).body
+ }
val patch = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.PATCH.name,
- "/sample/aai/v14/business/customers", post1, headers,
- String::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.PATCH.name,
+ "/sample/aai/v14/business/customers", post1, headers,
+ String::class.java
+ ).body
+ }
val delete = async(start = CoroutineStart.LAZY) {
- restClientService.exchangeNB(HttpMethod.DELETE.name,
- "/sample/aai/v14/business/customers", "", headers,
- String::class.java).body}
+ restClientService.exchangeNB(
+ HttpMethod.DELETE.name,
+ "/sample/aai/v14/business/customers", "", headers,
+ String::class.java
+ ).body
+ }
get1.start()
get2.start()
@@ -246,13 +283,13 @@ open class SampleController {
@GetMapping("/basic")
fun getBasic(): String = "Basic request arrived successfully"
-
@GetMapping("/aai/v14/business/customers")
fun getAaiCustomers(
- @RequestHeader(name = "X-TransactionId", required = true)
- transId: String,
- @RequestHeader(name = "X-FromAppId", required = true)
- appId: String) : String {
+ @RequestHeader(name = "X-TransactionId", required = true)
+ transId: String,
+ @RequestHeader(name = "X-FromAppId", required = true)
+ appId: String
+ ): String {
if (transId != "9999" || appId != "AAI") {
return ""
}
@@ -266,23 +303,24 @@ open class SampleController {
@PostMapping("/aai/v14/business/customers")
fun postAaiCustomers(
- @RequestHeader(name = "X-TransactionId", required = true)
- transId: String,
- @RequestHeader(name = "X-FromAppId", required = true)
- appId: String) : String {
+ @RequestHeader(name = "X-TransactionId", required = true)
+ transId: String,
+ @RequestHeader(name = "X-FromAppId", required = true)
+ appId: String
+ ): String {
if (transId != "9999" || appId != "AAI") {
return ""
}
return "The message is successfully posted"
}
-
@PutMapping("/aai/v14/business/customers")
fun putAaiCustomers(
- @RequestHeader(name = "X-TransactionId", required = true)
- transId: String,
- @RequestHeader(name = "X-FromAppId", required = true)
- appId: String) : String {
+ @RequestHeader(name = "X-TransactionId", required = true)
+ transId: String,
+ @RequestHeader(name = "X-FromAppId", required = true)
+ appId: String
+ ): String {
if (transId != "9999" || appId != "AAI") {
return ""
}
@@ -291,10 +329,11 @@ open class SampleController {
@PatchMapping("/aai/v14/business/customers")
fun patchAaiCustomers(
- @RequestHeader(name = "X-TransactionId", required = true)
- transId: String,
- @RequestHeader(name = "X-FromAppId", required = true)
- appId: String) : String {
+ @RequestHeader(name = "X-TransactionId", required = true)
+ transId: String,
+ @RequestHeader(name = "X-FromAppId", required = true)
+ appId: String
+ ): String {
if (transId != "9999" || appId != "AAI") {
return ""
}
@@ -303,10 +342,11 @@ open class SampleController {
@DeleteMapping("/aai/v14/business/customers")
fun deleteAaiCustomers(
- @RequestHeader(name = "X-TransactionId", required = true)
- transId: String,
- @RequestHeader(name = "X-FromAppId", required = true)
- appId: String) : String {
+ @RequestHeader(name = "X-TransactionId", required = true)
+ transId: String,
+ @RequestHeader(name = "X-FromAppId", required = true)
+ appId: String
+ ): String {
if (transId != "9999" || appId != "AAI") {
return ""
}
@@ -323,20 +363,20 @@ open class SecurityConfiguration {
@Bean
open fun userDetailsService(): MapReactiveUserDetailsService {
val user: UserDetails = User.withDefaultPasswordEncoder()
- .username("admin")
- .password("jans")
- .roles("USER")
- .build()
+ .username("admin")
+ .password("jans")
+ .roles("USER")
+ .build()
return MapReactiveUserDetailsService(user)
}
@Bean
open fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http
- .csrf().disable()
- .authorizeExchange().anyExchange().authenticated()
- .and().httpBasic()
- .and().build()
+ .csrf().disable()
+ .authorizeExchange().anyExchange().authenticated()
+ .and().httpBasic()
+ .and().build()
}
}
@@ -344,7 +384,8 @@ open class SecurityConfiguration {
* Data class required for response
*/
data class Customer(
- val id: String,
- val name: String,
- val type: String,
- val resource: String)
+ val id: String,
+ val name: String,
+ val type: String,
+ val resource: String
+)
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/ssh-lib/pom.xml
index 0e6a0bf1f..b67e0f416 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/pom.xml
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/pom.xml
@@ -31,8 +31,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt
index 3c625a6d3..382c9b7d7 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibConfiguration.kt
@@ -33,16 +33,13 @@ open class BluePrintSshLibConfiguration
* Exposed Dependency Service by this SSH Lib Module
*/
fun BluePrintDependencyService.sshLibPropertyService(): BluePrintSshLibPropertyService =
- instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY)
-
+ instance(SshLibConstants.SERVICE_BLUEPRINT_SSH_LIB_PROPERTY)
fun BluePrintDependencyService.sshClientService(selector: String): BlueprintSshClientService =
- sshLibPropertyService().blueprintSshClientService(selector)
-
+ sshLibPropertyService().blueprintSshClientService(selector)
fun BluePrintDependencyService.sshClientService(jsonNode: JsonNode): BlueprintSshClientService =
- sshLibPropertyService().blueprintSshClientService(jsonNode)
-
+ sshLibPropertyService().blueprintSshClientService(jsonNode)
class SshLibConstants {
companion object {
@@ -50,4 +47,4 @@ class SshLibConstants {
const val PROPERTY_SSH_CLIENT_PREFIX = "blueprintsprocessor.sshclient."
const val TYPE_BASIC_AUTH = "basic-auth"
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt
index a70ea5588..c7d5105b4 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/BluePrintSshLibData.kt
@@ -26,4 +26,4 @@ open class SshClientProperties {
open class BasicAuthSshClientProperties : SshClientProperties() {
lateinit var password: String
lateinit var username: String
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt
index adbde0f87..61baaa1ef 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BasicAuthSshClientService.kt
@@ -26,11 +26,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.ssh.BasicAuthSshClientProperties
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream
-import java.util.*
+import java.util.Collections
+import java.util.EnumSet
-
-open class BasicAuthSshClientService(private val basicAuthSshClientProperties: BasicAuthSshClientProperties)
- : BlueprintSshClientService {
+open class BasicAuthSshClientService(private val basicAuthSshClientProperties: BasicAuthSshClientProperties) :
+ BlueprintSshClientService {
private val log = LoggerFactory.getLogger(BasicAuthSshClientService::class.java)!!
@@ -43,10 +43,12 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B
sshClient.serverKeyVerifier = AcceptAllServerKeyVerifier.INSTANCE
sshClient.start()
log.debug("SSH Client Service started successfully")
- clientSession = sshClient.connect(basicAuthSshClientProperties.username, basicAuthSshClientProperties.host,
- basicAuthSshClientProperties.port)
- .verify(basicAuthSshClientProperties.connectionTimeOut)
- .session
+ clientSession = sshClient.connect(
+ basicAuthSshClientProperties.username, basicAuthSshClientProperties.host,
+ basicAuthSshClientProperties.port
+ )
+ .verify(basicAuthSshClientProperties.connectionTimeOut)
+ .session
clientSession.addPasswordIdentity(basicAuthSshClientProperties.password)
clientSession.auth().verify(basicAuthSshClientProperties.connectionTimeOut)
@@ -73,7 +75,7 @@ open class BasicAuthSshClientService(private val basicAuthSshClientProperties: B
channel = clientSession.createExecChannel(command)
checkNotNull(channel) { "failed to create Channel for the command : $command" }
- //TODO("Convert to streaming ")
+ // TODO("Convert to streaming ")
val outputStream = ByteArrayOutputStream()
channel!!.out = outputStream
channel!!.err = outputStream
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt
index 337208c78..90a1746e8 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyService.kt
@@ -53,11 +53,13 @@ open class BluePrintSshLibPropertyService(private var bluePrintProperties: BlueP
fun sshClientProperties(jsonNode: JsonNode): SshClientProperties {
val type = jsonNode.get("type")?.textValue()
- ?: throw BluePrintProcessorException("missing type field in ssh client properties")
+ ?: throw BluePrintProcessorException("missing type field in ssh client properties")
return when (type) {
SshLibConstants.TYPE_BASIC_AUTH -> {
- JacksonUtils.readValue(jsonNode,
- BasicAuthSshClientProperties::class.java)!!
+ JacksonUtils.readValue(
+ jsonNode,
+ BasicAuthSshClientProperties::class.java
+ )!!
}
else -> {
throw BluePrintProcessorException("SSH adaptor($type) is not supported")
@@ -79,7 +81,7 @@ open class BluePrintSshLibPropertyService(private var bluePrintProperties: BlueP
private fun basicAuthSshClientProperties(prefix: String): BasicAuthSshClientProperties {
return bluePrintProperties.propertyBeanType(
- prefix, BasicAuthSshClientProperties::class.java)
+ prefix, BasicAuthSshClientProperties::class.java
+ )
}
-
}
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientService.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientService.kt
index 279e437cc..724c4277d 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientService.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientService.kt
@@ -44,4 +44,4 @@ interface BlueprintSshClientService {
suspend fun executeCommandNB(command: String, timeOut: Long): String
suspend fun closeSessionNB()
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt
index f4275b8f2..f4c39c936 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BluePrintSshLibPropertyServiceTest.kt
@@ -29,17 +29,20 @@ import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintSshLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.sshclient.sample.type=basic-auth",
- "blueprintsprocessor.sshclient.sample.host=127.0.0.1",
- "blueprintsprocessor.sshclient.sample.port=22",
- "blueprintsprocessor.sshclient.sample.password=1234",
- "blueprintsprocessor.sshclient.sample.username=dummy"
-])
+@ContextConfiguration(
+ classes = [BluePrintSshLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.sshclient.sample.type=basic-auth",
+ "blueprintsprocessor.sshclient.sample.host=127.0.0.1",
+ "blueprintsprocessor.sshclient.sample.port=22",
+ "blueprintsprocessor.sshclient.sample.password=1234",
+ "blueprintsprocessor.sshclient.sample.username=dummy"
+ ]
+)
class BluePrintSshLibPropertyServiceTest {
@Autowired
@@ -48,11 +51,11 @@ class BluePrintSshLibPropertyServiceTest {
@Test
fun testRestClientProperties() {
val properties = bluePrintSshLibPropertyService
- .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties
+ .sshClientProperties("blueprintsprocessor.sshclient.sample") as BasicAuthSshClientProperties
assertNotNull(properties, "failed to create property bean")
assertEquals(properties.host, "127.0.0.1", "failed to match host property")
assertEquals(properties.port, 22, "failed to match port property")
assertEquals(properties.password, "1234", "failed to match host property")
assertEquals(properties.username, "dummy", "failed to match host property")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt
index 430b988a4..683816f7f 100644
--- a/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/commons/ssh-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/ssh/service/BlueprintSshClientServiceTest.kt
@@ -38,17 +38,20 @@ import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintSshLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
-@TestPropertySource(properties =
-["blueprintsprocessor.sshclient.sample.type=basic-auth",
- "blueprintsprocessor.sshclient.sample.host=localhost",
- "blueprintsprocessor.sshclient.sample.port=52815",
- "blueprintsprocessor.sshclient.sample.username=root",
- "blueprintsprocessor.sshclient.sample.password=dummyps"
-])
+@ContextConfiguration(
+ classes = [BluePrintSshLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
+@TestPropertySource(
+ properties =
+ ["blueprintsprocessor.sshclient.sample.type=basic-auth",
+ "blueprintsprocessor.sshclient.sample.host=localhost",
+ "blueprintsprocessor.sshclient.sample.port=52815",
+ "blueprintsprocessor.sshclient.sample.username=root",
+ "blueprintsprocessor.sshclient.sample.password=dummyps"
+ ]
+)
class BlueprintSshClientServiceTest {
@Autowired
@@ -76,7 +79,7 @@ class BlueprintSshClientServiceTest {
sshd.keyPairProvider = createTestHostKeyProvider()
sshd.passwordAuthenticator = BogusPasswordAuthenticator(userName, password)
sshd.publickeyAuthenticator = AcceptAllPublickeyAuthenticator.INSTANCE
- //sshd.shellFactory = EchoShellFactory()
+ // sshd.shellFactory = EchoShellFactory()
sshd.commandFactory = ProcessShellCommandFactory.INSTANCE
return sshd
}
@@ -96,5 +99,3 @@ class BogusPasswordAuthenticator(userName: String, password: String) : PasswordA
return true
}
}
-
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/configs-api/pom.xml
index 2cf5f5f57..d1352b892 100644
--- a/ms/blueprintsprocessor/modules/inbounds/configs-api/pom.xml
+++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/pom.xml
@@ -34,15 +34,14 @@
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor.functions</groupId>
<artifactId>config-snapshots</artifactId>
- <version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
</dependencies>
</project>
diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt
index eb7929509..0b18fb01f 100644
--- a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotController.kt
@@ -27,7 +27,14 @@ import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
/**
* Exposes Resource Configuration Snapshot API to store and retrieve stored resource configurations.
@@ -37,52 +44,66 @@ import org.springframework.web.bind.annotation.*
*/
@RestController
@RequestMapping("/api/v1/configs")
-@Api(value = "/api/v1/configs",
- description = "Interaction with stored configurations.")
+@Api(
+ value = "/api/v1/configs",
+ description = "Interaction with stored configurations."
+)
open class ResourceConfigSnapshotController(private val resourceConfigSnapshotService: ResourceConfigSnapshotService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun ressCfgSnapshotControllerHealthCheck(): JsonNode = runBlocking {
"Success".asJsonPrimitive()
}
- @RequestMapping(path = [""],
+ @RequestMapping(
+ path = [""],
method = [RequestMethod.GET],
- produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE])
- @ApiOperation(value = "Retrieve a resource configuration snapshot.",
+ produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
+ )
+ @ApiOperation(
+ value = "Retrieve a resource configuration snapshot.",
notes = "Retrieve a config snapshot, identified by its Resource Id and Type. " +
- "An extra 'format' parameter can be passed to tell what content-type is expected.")
+ "An extra 'format' parameter can be passed to tell what content-type is expected."
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun get(
- @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
+ @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
@RequestParam(value = "resourceType", required = true) resourceType: String,
- @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
+ @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
@RequestParam(value = "resourceId", required = true) resourceId: String,
- @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
+ @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
@RequestParam(value = "status", required = false, defaultValue = "RUNNING") status: String,
- @ApiParam(value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
- required = false)
- @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String)
+ @ApiParam(
+ value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
+ required = false
+ )
+ @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
+ ):
- : ResponseEntity<String> = runBlocking {
+ ResponseEntity<String> = runBlocking {
var configSnapshot = ""
if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
try {
- configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(resourceId,
- resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
- } catch (ex : NoSuchElementException) {
+ configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(
+ resourceId,
+ resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
+ )
+ } catch (ex: NoSuchElementException) {
throw ResourceConfigSnapshotException(
- "Could not find configuration snapshot entry for type $resourceType and Id $resourceId")
+ "Could not find configuration snapshot entry for type $resourceType and Id $resourceId"
+ )
}
} else {
throw IllegalArgumentException("Missing param. You must specify resource-id and resource-type.")
@@ -97,12 +118,16 @@ open class ResourceConfigSnapshotController(private val resourceConfigSnapshotSe
ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshot)
}
- @PostMapping("/{resourceType}/{resourceId}/{status}",
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
+ @PostMapping(
+ "/{resourceType}/{resourceId}/{status}",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
notes = "Store a resource configuration snapshot, identified by its resourceId and resourceType, " +
"and optionally its status, either RUNNING or CANDIDATE.",
- response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE)
+ response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResourceIdAndResourceType(
@@ -113,11 +138,14 @@ open class ResourceConfigSnapshotController(private val resourceConfigSnapshotSe
@ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = true)
@PathVariable(value = "status", required = true) status: String,
@ApiParam(value = "Config snapshot to store.", required = true)
- @RequestBody snapshot: String): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
+ @RequestBody snapshot: String
+ ): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
val resultStored =
- resourceConfigSnapshotService.write(snapshot, resourceId, resourceType,
- ResourceConfigSnapshot.Status.valueOf(status.toUpperCase()))
+ resourceConfigSnapshotService.write(
+ snapshot, resourceId, resourceType,
+ ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
+ )
ResponseEntity.ok().body(resultStored)
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotExceptionHandler.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotExceptionHandler.kt
index d21464ef5..d4c31e780 100644
--- a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotExceptionHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotExceptionHandler.kt
@@ -23,16 +23,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
import org.slf4j.LoggerFactory
+import org.springframework.dao.EmptyResultDataAccessException
+import org.springframework.dao.IncorrectResultSizeDataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException
-import org.springframework.dao.EmptyResultDataAccessException
-import org.springframework.dao.IncorrectResultSizeDataAccessException
-import org.springframework.web.server.ServerWebInputException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
+import org.springframework.web.server.ServerWebInputException
import java.io.Serializable
-import java.util.*
+import java.util.Date
/**
* Handle exceptions in ResourceConfigSnapshot API and provide relevant HTTP status codes and messages
@@ -102,9 +102,11 @@ open class ResourceConfigSnapshotExceptionHandler {
log.error(e.message)
}
val errorMessage =
- ErrorMessage(errorCode.message(e.message!!),
+ ErrorMessage(
+ errorCode.message(e.message!!),
errorCode.value,
- debugMsg)
+ debugMsg
+ )
return ResponseEntity(errorMessage, HttpStatus.resolve(errorCode.httpCode)!!)
}
}
@@ -113,6 +115,7 @@ open class ResourceConfigSnapshotExceptionHandler {
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt
index 89f62812e..34c7a7c7c 100644
--- a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/ResourceConfigSnapshotControllerTest.kt
@@ -35,8 +35,10 @@ import org.springframework.web.reactive.function.BodyInserters
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
+@ContextConfiguration(
+ classes = [BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class ResourceConfigSnapshotControllerTest {
@@ -68,24 +70,24 @@ class ResourceConfigSnapshotControllerTest {
runBlocking {
webTestClient
- .post()
- .uri("/api/v1/configs/$resourceType/$resourceId/running")
- .body(BodyInserters.fromObject(snapshotData))
- .exchange()
- .expectStatus().is2xxSuccessful
- .expectBody()
- .jsonPath("$.createdDate")
- .value<String> { println(it) }
+ .post()
+ .uri("/api/v1/configs/$resourceType/$resourceId/running")
+ .body(BodyInserters.fromObject(snapshotData))
+ .exchange()
+ .expectStatus().is2xxSuccessful
+ .expectBody()
+ .jsonPath("$.createdDate")
+ .value<String> { println(it) }
webTestClient
- .post()
- .uri("/api/v1/configs/$resourceType/$resourceId/running")
- .body(BodyInserters.fromObject(snapshotData))
- .exchange()
- .expectStatus().is2xxSuccessful
- .expectBody()
- .jsonPath("$.createdDate")
- .value<String> { println(it)}
+ .post()
+ .uri("/api/v1/configs/$resourceType/$resourceId/running")
+ .body(BodyInserters.fromObject(snapshotData))
+ .exchange()
+ .expectStatus().is2xxSuccessful
+ .expectBody()
+ .jsonPath("$.createdDate")
+ .value<String> { println(it) }
}
}
@@ -93,7 +95,7 @@ class ResourceConfigSnapshotControllerTest {
fun `get returns requested JSON content-type`() {
runBlocking {
post(resourceType, "22", "RUNNING")
- get("json", resourceType,"22", "RUNNING")
+ get("json", resourceType, "22", "RUNNING")
}
}
@@ -122,8 +124,8 @@ class ResourceConfigSnapshotControllerTest {
val arguments = "resourceId=MISSING&resourceType=PNF&status=TOTALLY_WRONG"
webTestClient.get().uri("/api/v1/configs?$arguments")
- .exchange()
- .expectStatus().isBadRequest
+ .exchange()
+ .expectStatus().isBadRequest
}
}
@@ -140,7 +142,7 @@ class ResourceConfigSnapshotControllerTest {
}
}
- private fun post( resourceType: String, resourceId: String, status: String) {
+ private fun post(resourceType: String, resourceId: String, status: String) {
webTestClient
.post()
.uri("/api/v1/configs/$resourceType/$resourceId/$status")
@@ -150,7 +152,7 @@ class ResourceConfigSnapshotControllerTest {
.expectBody()
}
- private fun get(expectedType : String, resourceType: String, resourceId: String, status: String) {
+ private fun get(expectedType: String, resourceType: String, resourceId: String, status: String) {
var requestArguments = "resourceId=$resourceId&resourceType=$resourceType&status=$status"
if (expectedType.isNotEmpty()) {
diff --git a/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt
new file mode 100644
index 000000000..661e28def
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/inbounds/configs-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/configs/api/TestDatabaseConfiguration.kt
@@ -0,0 +1,62 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.configs.api
+
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
+import org.springframework.transaction.PlatformTransactionManager
+import javax.sql.DataSource
+
+@Configuration
+@Import(BluePrintDBLibConfiguration::class)
+@EnableJpaRepositories(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots",
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
+)
+@EnableJpaAuditing
+open class TestDatabaseConfiguration(primaryDataSourceProperties: PrimaryDataSourceProperties) :
+ PrimaryDatabaseConfiguration(primaryDataSourceProperties) {
+
+ @Bean("primaryEntityManager")
+ open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ return primaryEntityManager(
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db"
+ )
+ }
+
+ @Bean("primaryDataSource")
+ override fun primaryDataSource(): DataSource {
+ return super.primaryDataSource()
+ }
+
+ @Bean("primaryTransactionManager")
+ override fun primaryTransactionManager(): PlatformTransactionManager {
+ return super.primaryTransactionManager()
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt
index 5f2a6dfb6..bca77f275 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandler.kt
@@ -30,31 +30,42 @@ import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonString
import org.onap.ccsdk.cds.controllerblueprints.core.emptyTONull
import org.onap.ccsdk.cds.controllerblueprints.core.utils.currentTimestamp
-import org.onap.ccsdk.cds.controllerblueprints.management.api.*
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk
+import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction
import org.slf4j.LoggerFactory
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.stereotype.Service
-//TODO("Convert to coroutines handler")
+// TODO("Convert to coroutines handler")
@Service
-open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: BluePrintModelHandler)
- : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
+open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: BluePrintModelHandler) :
+ BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() {
private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java)
@PreAuthorize("hasRole('USER')")
- override fun uploadBlueprint(request: BluePrintUploadInput, responseObserver:
- StreamObserver<BluePrintManagementOutput>) {
+ override fun uploadBlueprint(
+ request: BluePrintUploadInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
- //TODO("catch if request id is missing")
+ // TODO("catch if request id is missing")
log.info("request(${request.commonHeader.requestId})")
try {
/** Get the file byte array */
val byteArray = request.fileChunk.chunk.toByteArray()
/** Get the Upload Action */
val uploadAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: UploadAction.DRAFT.toString()
+ ?: UploadAction.DRAFT.toString()
when (uploadAction) {
UploadAction.DRAFT.toString() -> {
@@ -66,24 +77,36 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
responseObserver.onNext(successStatus(request.commonHeader, blueprintModel.asJsonString()))
}
UploadAction.VALIDATE.toString() -> {
- //TODO("Not Implemented")
- responseObserver.onNext(failStatus(request.commonHeader,
+ // TODO("Not Implemented")
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Upload action($uploadAction) not implemented",
- BluePrintProcessorException("Not Implemented")))
+ BluePrintProcessorException("Not Implemented")
+ )
+ )
}
UploadAction.ENRICH.toString() -> {
val enrichedByteArray = bluePrintModelHandler.enrichBlueprintFileSource(byteArray)
responseObserver.onNext(outputWithFileBytes(request.commonHeader, enrichedByteArray))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Upload action($uploadAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to upload CBA", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to upload CBA", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
@@ -91,8 +114,10 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
}
@PreAuthorize("hasRole('USER')")
- override fun downloadBlueprint(request: BluePrintDownloadInput,
- responseObserver: StreamObserver<BluePrintManagementOutput>) {
+ override fun downloadBlueprint(
+ request: BluePrintDownloadInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
val blueprintName = request.actionIdentifiers.blueprintName
val blueprintVersion = request.actionIdentifiers.blueprintVersion
@@ -100,7 +125,7 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
/** Get the Search Action */
val searchAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: DownloadAction.SEARCH.toString()
+ ?: DownloadAction.SEARCH.toString()
log.info("request(${request.commonHeader.requestId}): Received download $blueprint")
try {
@@ -110,14 +135,22 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
responseObserver.onNext(outputWithFileBytes(request.commonHeader, downloadByteArray))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Search action($searchAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
@@ -125,8 +158,11 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
}
@PreAuthorize("hasRole('USER')")
- override fun removeBlueprint(request: BluePrintRemoveInput, responseObserver:
- StreamObserver<BluePrintManagementOutput>) {
+ override fun removeBlueprint(
+ request: BluePrintRemoveInput,
+ responseObserver:
+ StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
val blueprintName = request.actionIdentifiers.blueprintName
@@ -137,7 +173,7 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
/** Get the Remove Action */
val removeAction = request.actionIdentifiers?.actionName.emptyTONull()
- ?: RemoveAction.DEFAULT.toString()
+ ?: RemoveAction.DEFAULT.toString()
try {
when (removeAction) {
@@ -146,22 +182,32 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
responseObserver.onNext(successStatus(request.commonHeader))
}
else -> {
- responseObserver.onNext(failStatus(request.commonHeader,
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
"Remove action($removeAction) not implemented",
- BluePrintProcessorException("Not implemented")))
+ BluePrintProcessorException("Not implemented")
+ )
+ )
}
}
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to delete $blueprint", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
}
}
- override fun bootstrapBlueprint(request: BluePrintBootstrapInput,
- responseObserver: StreamObserver<BluePrintManagementOutput>) {
+ override fun bootstrapBlueprint(
+ request: BluePrintBootstrapInput,
+ responseObserver: StreamObserver<BluePrintManagementOutput>
+ ) {
runBlocking {
try {
log.info("request(${request.commonHeader.requestId}): Received bootstrap request")
@@ -173,10 +219,13 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
/** Perform bootstrap of Model Types, Resource Definitions and CBA */
bluePrintModelHandler.bootstrapBlueprint(bootstrapRequest)
responseObserver.onNext(successStatus(request.commonHeader))
-
} catch (e: Exception) {
- responseObserver.onNext(failStatus(request.commonHeader,
- "request(${request.commonHeader.requestId}): Failed to bootstrap", e))
+ responseObserver.onNext(
+ failStatus(
+ request.commonHeader,
+ "request(${request.commonHeader.requestId}): Failed to bootstrap", e
+ )
+ )
} finally {
responseObserver.onCompleted()
}
@@ -184,15 +233,17 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
}
private fun outputWithFileBytes(header: CommonHeader, byteArray: ByteArray): BluePrintManagementOutput =
- BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_SUCCESS)
- .setCode(200)
- .build())
+ BluePrintManagementOutput.newBuilder()
+ .setCommonHeader(header)
+ .setFileChunk(FileChunk.newBuilder().setChunk(ByteString.copyFrom(byteArray)))
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_SUCCESS)
+ .setCode(200)
.build()
+ )
+ .build()
private fun successStatus(header: CommonHeader, propertyContent: String? = null): BluePrintManagementOutput {
// Populate Response Payload
@@ -201,30 +252,34 @@ open class BluePrintManagementGRPCHandler(private val bluePrintModelHandler: Blu
JsonFormat.parser().merge(propertyContent, propertiesBuilder)
}
return BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setProperties(propertiesBuilder.build())
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_SUCCESS)
- .setCode(200)
- .build())
- .build()
+ .setCommonHeader(header)
+ .setProperties(propertiesBuilder.build())
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_SUCCESS)
+ .setCode(200)
+ .build()
+ )
+ .build()
}
private fun failStatus(header: CommonHeader, message: String, e: Exception): BluePrintManagementOutput {
log.error(message, e)
return BluePrintManagementOutput.newBuilder()
- .setCommonHeader(header)
- .setStatus(Status.newBuilder()
- .setTimestamp(currentTimestamp())
- .setMessage(BluePrintConstants.STATUS_FAILURE)
- .setErrorMessage(message)
- .setCode(500)
- .build())
- .build()
-// return io.grpc.Status.INTERNAL
-// .withDescription(message)
-// .withCause(e)
-// .asException()
+ .setCommonHeader(header)
+ .setStatus(
+ Status.newBuilder()
+ .setTimestamp(currentTimestamp())
+ .setMessage(BluePrintConstants.STATUS_FAILURE)
+ .setErrorMessage(message)
+ .setCode(500)
+ .build()
+ )
+ .build()
+ // return io.grpc.Status.INTERNAL
+ // .withDescription(message)
+ // .withCause(e)
+ // .asException()
}
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt
index 5ef50b09f..f257157c8 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelController.kt
@@ -34,7 +34,16 @@ import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.codec.multipart.FilePart
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.DeleteMapping
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.RequestPart
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
/**
@@ -47,8 +56,10 @@ import reactor.core.publisher.Mono
@RequestMapping("/api/v1/blueprint-model")
open class BlueprintModelController(private val bluePrintModelHandler: BluePrintModelHandler) {
- @PostMapping(path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE),
- consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE))
+ @PostMapping(
+ path = arrayOf("/bootstrap"), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE),
+ consumes = arrayOf(MediaType.APPLICATION_JSON_VALUE)
+ )
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
@@ -74,9 +85,11 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
@GetMapping("/paged", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun allBlueprintModel(@RequestParam(defaultValue = "20") limit: Int,
- @RequestParam(defaultValue = "0") offset: Int,
- @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption): Page<BlueprintModelSearch> {
+ fun allBlueprintModel(
+ @RequestParam(defaultValue = "20") limit: Int,
+ @RequestParam(defaultValue = "0") offset: Int,
+ @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
+ ): Page<BlueprintModelSearch> {
val pageRequest = PageRequest.of(offset, limit, Sort.Direction.ASC, sort.columnName)
return this.bluePrintModelHandler.allBlueprintModel(pageRequest)
}
@@ -88,18 +101,17 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
return this.bluePrintModelHandler.searchBluePrintModelsByKeyWord(keyWord)
}
-
@GetMapping("/paged/meta-data/{keyword}", produces = [MediaType.APPLICATION_JSON_VALUE])
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun allBlueprintModelMetaDataPaged(@NotNull @PathVariable(value = "keyword") keyWord: String,
- @RequestParam(defaultValue = "20") limit: Int,
- @RequestParam(defaultValue = "0") offset: Int,
- @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
+ fun allBlueprintModelMetaDataPaged(
+ @NotNull @PathVariable(value = "keyword") keyWord: String,
+ @RequestParam(defaultValue = "20") limit: Int,
+ @RequestParam(defaultValue = "0") offset: Int,
+ @RequestParam(defaultValue = "DATE") sort: BlueprintSortByOption
): Page<BlueprintModelSearch> {
val pageRequest = PageRequest.of(offset, limit, Sort.Direction.ASC, sort.columnName)
return this.bluePrintModelHandler.searchBluePrintModelsByKeyWordPaged(keyWord, pageRequest)
-
}
@DeleteMapping("/{id}")
@@ -113,9 +125,11 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
- fun getBlueprintByNameAndVersion(@PathVariable(value = "name") name: String,
- @PathVariable(value = "version") version: String)
- : Mono<BlueprintModelSearch> = monoMdc {
+ fun getBlueprintByNameAndVersion(
+ @PathVariable(value = "name") name: String,
+ @PathVariable(value = "version") version: String
+ ):
+ Mono<BlueprintModelSearch> = monoMdc {
bluePrintModelHandler.getBlueprintModelSearchByNameAndVersion(name, version)
}
@@ -123,9 +137,11 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
- fun downloadBlueprintByNameAndVersion(@PathVariable(value = "name") name: String,
- @PathVariable(value = "version") version: String)
- : Mono<ResponseEntity<Resource>> = monoMdc {
+ fun downloadBlueprintByNameAndVersion(
+ @PathVariable(value = "name") name: String,
+ @PathVariable(value = "version") version: String
+ ):
+ Mono<ResponseEntity<Resource>> = monoMdc {
bluePrintModelHandler.downloadBlueprintModelFileByNameAndVersion(name, version)
}
@@ -145,8 +161,10 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
bluePrintModelHandler.downloadBlueprintModelFile(id)
}
- @PostMapping("/enrich", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType
- .MULTIPART_FORM_DATA_VALUE])
+ @PostMapping(
+ "/enrich", produces = [MediaType.APPLICATION_JSON_VALUE], consumes = [MediaType
+ .MULTIPART_FORM_DATA_VALUE]
+ )
@ResponseBody
@Throws(BluePrintException::class)
@PreAuthorize("hasRole('USER')")
@@ -170,14 +188,18 @@ open class BlueprintModelController(private val bluePrintModelHandler: BluePrint
}
@DeleteMapping("/name/{name}/version/{version}")
- @ApiOperation(value = "Delete a CBA",
- notes = "Delete the CBA package identified by its name and version.",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ @ApiOperation(
+ value = "Delete a CBA",
+ notes = "Delete the CBA package identified by its name and version.",
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@PreAuthorize("hasRole('USER')")
- fun deleteBlueprint(@ApiParam(value = "Name of the CBA.", required = true)
- @PathVariable(value = "name") name: String,
- @ApiParam(value = "Version of the CBA.", required = true)
- @PathVariable(value = "version") version: String) = monoMdc {
+ fun deleteBlueprint(
+ @ApiParam(value = "Name of the CBA.", required = true)
+ @PathVariable(value = "name") name: String,
+ @ApiParam(value = "Version of the CBA.", required = true)
+ @PathVariable(value = "version") version: String
+ ) = monoMdc {
bluePrintModelHandler.deleteBlueprintModel(name, version)
}
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt
index 346015bc4..d0cb67315 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiData.kt
@@ -24,8 +24,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import java.io.Serializable
-import java.util.*
-
+import java.util.Date
class BootstrapRequest {
var loadModelType: Boolean = false
@@ -40,15 +39,16 @@ class BootstrapRequest {
* @version 1.0
*/
class AutoMapResponse {
+
var resourceAssignments: List<ResourceAssignment>? = null
var dataDictionaries: List<ResourceDictionary>? = null
}
-
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt
index bac281356..adeb3cf89 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeController.kt
@@ -18,11 +18,18 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api
import kotlinx.coroutines.runBlocking
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.springframework.http.MediaType
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.DeleteMapping
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = arrayOf("/api/v1/model-type"))
@@ -55,4 +62,4 @@ open class ModelTypeController(private val modelTypeHandler: ModelTypeHandler) {
fun deleteModelTypeByName(@PathVariable(value = "name") name: String) = runBlocking {
modelTypeHandler.deleteByModelName(name)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt
index bae890a87..562932e23 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryController.kt
@@ -22,7 +22,14 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ResourceDicti
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceSourceMapping
import org.springframework.http.MediaType
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.DeleteMapping
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(value = ["/api/v1/dictionary"])
@@ -57,7 +64,6 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R
@ResponseBody
fun searchResourceDictionaryByTags(@PathVariable(value = "tags") tags: String): List<ResourceDictionary> = runBlocking {
resourceDictionaryHandler.searchResourceDictionaryByTags(tags)
-
}
@GetMapping(path = ["/source-mapping"], produces = [MediaType.APPLICATION_JSON_VALUE])
@@ -65,5 +71,4 @@ open class ResourceDictionaryController(private val resourceDictionaryHandler: R
fun getResourceSourceMapping(): ResourceSourceMapping = runBlocking {
resourceDictionaryHandler.getResourceSourceMapping()
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaJsonNodeConverter.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaJsonNodeConverter.kt
index 97c7ab6a6..4779ad340 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaJsonNodeConverter.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaJsonNodeConverter.kt
@@ -18,7 +18,6 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain
import com.fasterxml.jackson.databind.JsonNode
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-
import javax.persistence.AttributeConverter
import javax.persistence.Converter
@@ -35,4 +34,4 @@ class JpaJsonNodeConverter : AttributeConverter<JsonNode, String> {
override fun convertToEntityAttribute(dbData: String): JsonNode {
return JacksonUtils.jsonNode(dbData)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaResourceDefinitionConverter.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaResourceDefinitionConverter.kt
index 75cfede50..f0692cdd9 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaResourceDefinitionConverter.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/JpaResourceDefinitionConverter.kt
@@ -18,7 +18,6 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
-
import javax.persistence.AttributeConverter
import javax.persistence.Converter
@@ -27,6 +26,7 @@ import javax.persistence.Converter
*/
@Converter
class JpaResourceDefinitionConverter : AttributeConverter<ResourceDefinition, String> {
+
override fun convertToDatabaseColumn(resourceDefinition: ResourceDefinition): String {
return JacksonUtils.getJson(resourceDefinition)
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ModelType.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ModelType.kt
index a964e0416..6e277e5c8 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ModelType.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ModelType.kt
@@ -22,8 +22,16 @@ import io.swagger.annotations.ApiModelProperty
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Convert
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide ModelType Entity
@@ -94,4 +102,4 @@ class ModelType : Serializable {
companion object {
private const val serialVersionUID = 1L
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ResourceDictionary.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ResourceDictionary.kt
index ac5ea2070..209e2bbe8 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ResourceDictionary.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/domain/ResourceDictionary.kt
@@ -22,8 +22,16 @@ import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.jpa.domain.support.AuditingEntityListener
import java.io.Serializable
-import java.util.*
-import javax.persistence.*
+import java.util.Date
+import javax.persistence.Column
+import javax.persistence.Convert
+import javax.persistence.Entity
+import javax.persistence.EntityListeners
+import javax.persistence.Id
+import javax.persistence.Lob
+import javax.persistence.Table
+import javax.persistence.Temporal
+import javax.persistence.TemporalType
/**
* Provide ResourceDictionary Entity
@@ -89,6 +97,4 @@ class ResourceDictionary : Serializable {
companion object {
private const val serialVersionUID = 1L
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt
index 552339be9..f954df7ac 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintArtifactDefinitionEnhancerImpl.kt
@@ -32,22 +32,22 @@ import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.springframework.stereotype.Service
@Service
-open class BluePrintArtifactDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService)
- : BluePrintArtifactDefinitionEnhancer {
+open class BluePrintArtifactDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService
+) :
+ BluePrintArtifactDefinitionEnhancer {
companion object {
const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource"
}
-
private val log = logger(BluePrintArtifactDefinitionEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, artifactDefinition: ArtifactDefinition) {
log.info("enhancing ArtifactDefinition($name)")
@@ -55,7 +55,7 @@ open class BluePrintArtifactDefinitionEnhancerImpl(private val bluePrintRepoServ
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val artifactTypeName = artifactDefinition.type
- ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)")
+ ?: throw BluePrintException("artifact type is missing for ArtifactDefinition($name)")
// Populate Artifact Type
BluePrintEnhancerUtils.populateArtifactType(bluePrintContext, bluePrintRepoService, artifactTypeName)
@@ -80,7 +80,7 @@ open class BluePrintArtifactDefinitionEnhancerImpl(private val bluePrintRepoServ
if (!alreadyEnhanced) {
val resourceAssignments: MutableList<ResourceAssignment> = JacksonUtils.getListFromFile(artifactFilePath, ResourceAssignment::class.java)
as? MutableList<ResourceAssignment>
- ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)")
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($artifactFilePath)")
// Call Resource Assignment Enhancer
resourceAssignmentEnhancerService.enhanceBluePrint(bluePrintTypeEnhancerService, bluePrintRuntimeService, resourceAssignments)
@@ -88,5 +88,4 @@ open class BluePrintArtifactDefinitionEnhancerImpl(private val bluePrintRepoServ
bluePrintRuntimeService.put(alreadyEnhancedKey, true.asJsonPrimitive())
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt
index 0b64ed503..030fbe8ae 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintAttributeDefinitionEnhancerImpl.kt
@@ -26,9 +26,11 @@ import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnha
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-class BluePrintAttributeDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintAttributeDefinitionEnhancer {
+class BluePrintAttributeDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintAttributeDefinitionEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
@@ -39,10 +41,9 @@ class BluePrintAttributeDefinitionEnhancerImpl(private val bluePrintRepoService:
val propertyType = attributeDefinition.type
if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)) {
-
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchema = attributeDefinition.entrySchema
- ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
+ ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) {
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type)
@@ -51,5 +52,4 @@ class BluePrintAttributeDefinitionEnhancerImpl(private val bluePrintRepoService:
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt
index b4d149e16..e99f49489 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImpl.kt
@@ -26,11 +26,13 @@ import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.UUID
@Service
-open class BluePrintEnhancerServiceImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService) : BluePrintEnhancerService {
+open class BluePrintEnhancerServiceImpl(
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceDefinitionEnhancerService: ResourceDefinitionEnhancerService
+) : BluePrintEnhancerService {
private val log = logger(BluePrintEnhancerServiceImpl::class)
@@ -48,16 +50,20 @@ open class BluePrintEnhancerServiceImpl(private val bluePrintTypeEnhancerService
log.info("Enhancing blueprint($basePath)")
val blueprintRuntimeService = BluePrintMetadataUtils
- .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath)
+ .getBaseEnhancementBluePrintRuntime(UUID.randomUUID().toString(), basePath)
try {
- bluePrintTypeEnhancerService.enhanceServiceTemplate(blueprintRuntimeService, "service_template",
- blueprintRuntimeService.bluePrintContext().serviceTemplate)
+ bluePrintTypeEnhancerService.enhanceServiceTemplate(
+ blueprintRuntimeService, "service_template",
+ blueprintRuntimeService.bluePrintContext().serviceTemplate
+ )
log.info("##### Enhancing blueprint Resource Definitions")
- val resourceDefinitions = resourceDefinitionEnhancerService.enhance(bluePrintTypeEnhancerService,
- blueprintRuntimeService)
+ val resourceDefinitions = resourceDefinitionEnhancerService.enhance(
+ bluePrintTypeEnhancerService,
+ blueprintRuntimeService
+ )
// Write the Enhanced Blueprint Definitions
BluePrintFileUtils.writeEnhancedBluePrint(blueprintRuntimeService.bluePrintContext())
@@ -68,12 +74,9 @@ open class BluePrintEnhancerServiceImpl(private val bluePrintTypeEnhancerService
if (blueprintRuntimeService.getBluePrintError().errors.isNotEmpty()) {
throw BluePrintException(blueprintRuntimeService.getBluePrintError().errors.toString())
}
-
} catch (e: Exception) {
throw e
}
return blueprintRuntimeService.bluePrintContext()
}
-
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt
index 723d7bb27..6ca0b2d14 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTemplateEnhancerImpl.kt
@@ -31,22 +31,22 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintNodeTemplateEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintNodeTemplateEnhancer {
+open class BluePrintNodeTemplateEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintNodeTemplateEnhancer {
- private val log= logger(BluePrintNodeTemplateEnhancerImpl::class)
+ private val log = logger(BluePrintNodeTemplateEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeTemplate: NodeTemplate) {
log.info("***** Enhancing NodeTemplate($name)")
this.bluePrintRuntimeService = bluePrintRuntimeService
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
-
val nodeTypeName = nodeTemplate.type
// Get NodeType from Repo and Update Service Template
val nodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext, bluePrintRepoService, nodeTypeName)
@@ -54,7 +54,7 @@ open class BluePrintNodeTemplateEnhancerImpl(private val bluePrintRepoService: B
// Enrich NodeType
bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType)
- //Enrich Node Template Artifacts
+ // Enrich Node Template Artifacts
enhanceNodeTemplateArtifactDefinition(name, nodeTemplate)
}
@@ -65,5 +65,4 @@ open class BluePrintNodeTemplateEnhancerImpl(private val bluePrintRepoService: B
bluePrintTypeEnhancerService.enhanceArtifactDefinition(bluePrintRuntimeService, artifactDefinitionName, artifactDefinition)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt
index efb695b22..d28084e40 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintNodeTypeEnhancerImpl.kt
@@ -34,20 +34,20 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : BluePrintNodeTypeEnhancer {
+open class BluePrintNodeTypeEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) : BluePrintNodeTypeEnhancer {
- private val log= logger(BluePrintNodeTypeEnhancerImpl::class)
+ private val log = logger(BluePrintNodeTypeEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, nodeType: NodeType) {
this.bluePrintRuntimeService = bluePrintRuntimeService
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
-
val derivedFrom = nodeType.derivedFrom
if (!BluePrintTypes.rootNodeTypes().contains(derivedFrom)) {
@@ -62,15 +62,14 @@ open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BlueP
// NodeType Property Definitions
enrichNodeTypeProperties(name, nodeType)
- //NodeType Requirement
+ // NodeType Requirement
enrichNodeTypeRequirements(name, nodeType)
- //NodeType Capability
+ // NodeType Capability
enrichNodeTypeCapabilityProperties(name, nodeType)
- //NodeType Interface
+ // NodeType Interface
enrichNodeTypeInterfaces(name, nodeType)
-
}
open fun enrichNodeTypeAttributes(nodeTypeName: String, nodeType: NodeType) {
@@ -91,15 +90,19 @@ open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BlueP
// Populate Requirement Node
requirementDefinition.node?.let { requirementNodeTypeName ->
// Get Requirement NodeType from Repo and Update Service Template
- val requirementNodeType = BluePrintEnhancerUtils.populateNodeType(bluePrintContext,
- bluePrintRepoService, requirementNodeTypeName)
+ val requirementNodeType = BluePrintEnhancerUtils.populateNodeType(
+ bluePrintContext,
+ bluePrintRepoService, requirementNodeTypeName
+ )
// Enhance Node Type
enhance(bluePrintRuntimeService, requirementNodeTypeName, requirementNodeType)
// Enhance Relationship Type
val relationShipTypeName = requirementDefinition.relationship
- ?: throw BluePrintException("couldn't get relationship name for the NodeType($nodeTypeName) " +
- "Requirement($requirementName)")
+ ?: throw BluePrintException(
+ "couldn't get relationship name for the NodeType($nodeTypeName) " +
+ "Requirement($requirementName)"
+ )
enrichRelationShipType(relationShipTypeName)
}
}
@@ -118,7 +121,6 @@ open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BlueP
// Populate Node type Interface Operation
log.debug("Enriching NodeType({}) Interface({})", nodeTypeName, interfaceName)
populateNodeTypeInterfaceOperation(nodeTypeName, interfaceName, interfaceObj)
-
}
}
@@ -136,8 +138,11 @@ open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BlueP
}
}
- open fun enrichNodeTypeInterfaceOperationOutputs(nodeTypeName: String, operationName: String,
- operation: OperationDefinition) {
+ open fun enrichNodeTypeInterfaceOperationOutputs(
+ nodeTypeName: String,
+ operationName: String,
+ operation: OperationDefinition
+ ) {
operation.outputs?.let { inputs ->
bluePrintTypeEnhancerService.enhancePropertyDefinitions(bluePrintRuntimeService, inputs)
}
@@ -149,5 +154,4 @@ open class BluePrintNodeTypeEnhancerImpl(private val bluePrintRepoService: BlueP
open fun enrichRelationShipType(relationshipName: String) {
BluePrintEnhancerUtils.populateRelationshipType(bluePrintContext, bluePrintRepoService, relationshipName)
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt
index 83fd403e8..212dc440d 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPolicyTypeEnhancerImpl.kt
@@ -27,17 +27,18 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-class BluePrintPolicyTypeEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintPolicyTypeEnhancer {
+class BluePrintPolicyTypeEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintPolicyTypeEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
-
override fun enhance(bluePrintRuntimeService: BluePrintRuntimeService<*>, name: String, type: PolicyType) {
- this.bluePrintRuntimeService = bluePrintRuntimeService
+ this.bluePrintRuntimeService = bluePrintRuntimeService
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt
index b87cf9c6b..eb7443443 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintPropertyDefinitionEnhancerImpl.kt
@@ -32,9 +32,11 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintPropertyDefinitionEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintPropertyDefinitionEnhancer {
+open class BluePrintPropertyDefinitionEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintPropertyDefinitionEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
@@ -44,12 +46,13 @@ open class BluePrintPropertyDefinitionEnhancerImpl(private val bluePrintRepoServ
this.bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val propertyType = propertyDefinition.type
- if (BluePrintTypes.validPrimitiveTypes().contains(propertyType)
- || BluePrintTypes.validComplexTypes().contains(propertyType)) {
+ if (BluePrintTypes.validPrimitiveTypes().contains(propertyType) ||
+ BluePrintTypes.validComplexTypes().contains(propertyType)
+ ) {
// Do Nothing,
} else if (BluePrintTypes.validCollectionTypes().contains(propertyType)) {
val entrySchema = propertyDefinition.entrySchema
- ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
+ ?: throw BluePrintException("Entry Schema is missing for collection property($name)")
if (!BluePrintTypes.validPrimitiveTypes().contains(entrySchema.type)) {
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, entrySchema.type)
@@ -58,5 +61,4 @@ open class BluePrintPropertyDefinitionEnhancerImpl(private val bluePrintRepoServ
BluePrintEnhancerUtils.populateDataTypes(bluePrintContext, bluePrintRepoService, propertyType)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt
index 65e5ff9e1..9f4a4592a 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintServiceTemplateEnhancerImpl.kt
@@ -28,10 +28,10 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService)
- : BluePrintServiceTemplateEnhancer {
- private val log = logger(BluePrintServiceTemplateEnhancerImpl::class)
+open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) :
+ BluePrintServiceTemplateEnhancer {
+ private val log = logger(BluePrintServiceTemplateEnhancerImpl::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var bluePrintContext: BluePrintContext
@@ -57,7 +57,6 @@ open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhance
bluePrintContext.serviceTemplate.policyTypes = mutableMapOf()
bluePrintContext.serviceTemplate.relationshipTypes = mutableMapOf()
log.info("reinitialized all type definitions")
-
}
open fun enhanceTopologyTemplate() {
@@ -65,4 +64,4 @@ open class BluePrintServiceTemplateEnhancerImpl(private val bluePrintTypeEnhance
bluePrintTypeEnhancerService.enhanceTopologyTemplate(bluePrintRuntimeService, "topology_template", topologyTemplate)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt
index c22370c33..c0100fbea 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTopologyTemplateEnhancerImpl.kt
@@ -27,8 +27,11 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintTopologyTemplateEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService) : BluePrintTopologyTemplateEnhancer {
+open class BluePrintTopologyTemplateEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService
+) :
+ BluePrintTopologyTemplateEnhancer {
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
@@ -57,5 +60,4 @@ open class BluePrintTopologyTemplateEnhancerImpl(private val bluePrintRepoServic
bluePrintTypeEnhancerService.enhanceWorkflow(bluePrintRuntimeService, workflowName, workflow)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt
index db361a248..5b7c6b2d0 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintTypeEnhancerServiceImpl.kt
@@ -16,7 +16,16 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
-import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.*
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintArtifactDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintAttributeDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintNodeTypeEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPolicyTypeEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintPropertyDefinitionEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintServiceTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTopologyTemplateEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
+import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
@@ -62,4 +71,4 @@ open class BluePrintTypeEnhancerServiceImpl : BluePrintTypeEnhancerService {
override fun getAttributeDefinitionEnhancers(): List<BluePrintAttributeDefinitionEnhancer> {
return context.getBeansOfType(BluePrintAttributeDefinitionEnhancer::class.java).map { it.value }
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt
index 394289ced..88127e3ca 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintWorkflowEnhancerImpl.kt
@@ -17,13 +17,17 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.data.Workflow
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowEnhancer
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@@ -34,11 +38,14 @@ import org.springframework.stereotype.Service
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BluePrintRepoService,
- private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService)
- : BluePrintWorkflowEnhancer {
- private val log= logger(BluePrintWorkflowEnhancerImpl::class)
+open class BluePrintWorkflowEnhancerImpl(
+ private val bluePrintRepoService: BluePrintRepoService,
+ private val bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ private val resourceAssignmentEnhancerService: ResourceAssignmentEnhancerService
+) :
+ BluePrintWorkflowEnhancer {
+
+ private val log = logger(BluePrintWorkflowEnhancerImpl::class)
companion object {
const val ARTIFACT_TYPE_MAPPING_SOURCE: String = "artifact-mapping-resource"
@@ -70,8 +77,6 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
// Enrich Only for Resource Assignment and Dynamic Input Properties if any
enhanceStepTargets(name, workflow)
-
-
}
open fun enhanceWorkflowInputs(name: String, workflow: Workflow) {
@@ -102,11 +107,12 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
enhanceStepTargets(name, workflow, firstNodeTemplateName, true)
}
else -> {
- throw BluePrintProcessorException("couldn't execute workflow($name) step mapped " +
- "to node template($firstNodeTemplateName) derived from($derivedFrom)")
+ throw BluePrintProcessorException(
+ "couldn't execute workflow($name) step mapped " +
+ "to node template($firstNodeTemplateName) derived from($derivedFrom)"
+ )
}
}
-
}
private fun enhanceStepTargets(name: String, workflow: Workflow, nodeTemplateName: String, isDG: Boolean) {
@@ -132,10 +138,10 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
log.info("identified workflow($name) targets($componentNodeTemplateName)")
val resourceAssignmentArtifacts = bluePrintContext.nodeTemplateByName(componentNodeTemplateName)
- .artifacts?.filter {
+ .artifacts?.filter {
it.value.type == ARTIFACT_TYPE_MAPPING_SOURCE
}?.map {
- log.info("resource assignment artifacts(${it.key}) for NodeType(${componentNodeTemplateName})")
+ log.info("resource assignment artifacts(${it.key}) for NodeType($componentNodeTemplateName)")
it.value.file
}
resourceAssignmentArtifacts
@@ -162,13 +168,13 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
val filePath = "${bluePrintContext.rootPath}/$fileName"
- log.info("enriching artifacts file(${filePath}")
+ log.info("enriching artifacts file($filePath")
val resourceAssignmentProperties: MutableMap<String, PropertyDefinition> = hashMapOf()
val resourceAssignments: MutableList<ResourceAssignment> = JacksonUtils.getListFromFile(filePath, ResourceAssignment::class.java)
as? MutableList<ResourceAssignment>
- ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
+ ?: throw BluePrintProcessorException("couldn't get ResourceAssignment definitions for the file($filePath)")
val alreadyEnhancedKey = "enhanced-$fileName"
val alreadyEnhanced = bluePrintRuntimeService.check(alreadyEnhancedKey)
@@ -215,7 +221,6 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
// Overwrite WorkFlow DataType
bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dynamicDataType)
-
} else {
log.info("dynamic dataType($dataTypeName) already present for workflow($workflowName).")
}
@@ -224,4 +229,4 @@ open class BluePrintWorkflowEnhancerImpl(private val bluePrintRepoService: BlueP
dynamicDataType.properties?.put(propertyName, propertyDefinition)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt
index 55eb42f89..94e183405 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceAssignmentEnhancerService.kt
@@ -16,6 +16,7 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
@@ -25,7 +26,6 @@ import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDictionaryConstants
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.factory.ResourceSourceMappingFactory
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@@ -38,9 +38,11 @@ import org.springframework.stereotype.Service
interface ResourceAssignmentEnhancerService {
@Throws(BluePrintException::class)
- fun enhanceBluePrint(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>,
- resourceAssignments: List<ResourceAssignment>)
+ fun enhanceBluePrint(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ resourceAssignments: List<ResourceAssignment>
+ )
}
/**
@@ -50,17 +52,20 @@ interface ResourceAssignmentEnhancerService {
*/
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService)
- : ResourceAssignmentEnhancerService {
- private val log= logger(ResourceAssignmentEnhancerServiceImpl::class)
+open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService) :
+ ResourceAssignmentEnhancerService {
+
+ private val log = logger(ResourceAssignmentEnhancerServiceImpl::class)
/**
* Get the defined source instance from the ResourceAssignment,
* then get the NodeType of the Sources assigned
*/
- override fun enhanceBluePrint(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>,
- resourceAssignments: List<ResourceAssignment>) {
+ override fun enhanceBluePrint(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ resourceAssignments: List<ResourceAssignment>
+ ) {
val uniqueSourceNodeTypeNames = hashSetOf<String>()
@@ -77,14 +82,16 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR
// TODO("Candidate for Optimisation")
if (checkResourceDefinitionNeeded(resourceAssignment)) {
- bluePrintTypeEnhancerService.enhancePropertyDefinition(bluePrintRuntimeService, resourceAssignment.name,
- resourceAssignment.property!!);
+ bluePrintTypeEnhancerService.enhancePropertyDefinition(
+ bluePrintRuntimeService, resourceAssignment.name,
+ resourceAssignment.property!!
+ )
// Get the Resource Definition from Repo
val resourceDefinition: ResourceDefinition = getResourceDefinition(dictionaryName)
val sourceNodeTemplate = resourceDefinition.sources[dictionarySource]
- ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)")
+ ?: throw BluePrintException("failed to get assigned dictionarySource($dictionarySource) from resourceDefinition($dictionaryName)")
// Enrich as NodeTemplate
bluePrintTypeEnhancerService.enhanceNodeTemplate(bluePrintRuntimeService, dictionarySource, sourceNodeTemplate)
@@ -95,16 +102,15 @@ open class ResourceAssignmentEnhancerServiceImpl(private val resourceDefinitionR
val nodeType = resourceDefinitionRepoService.getNodeType(nodeTypeName)
bluePrintTypeEnhancerService.enhanceNodeType(bluePrintRuntimeService, nodeTypeName, nodeType)
}
-
}
private fun checkResourceDefinitionNeeded(resourceAssignment: ResourceAssignment): Boolean {
- return !((resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT)
- || resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT))
- && BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!))
+ return !((resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_INPUT) ||
+ resourceAssignment.dictionarySource.equals(ResourceDictionaryConstants.SOURCE_DEFAULT)) &&
+ BluePrintTypes.validPrimitiveOrCollectionPrimitive(resourceAssignment.property!!))
}
private fun getResourceDefinition(name: String): ResourceDefinition {
return resourceDefinitionRepoService.getResourceDefinition(name)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt
index c018664e4..042c76805 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/ResourceDefinitionEnhancerService.kt
@@ -20,6 +20,8 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.enhancer
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.core.logger
@@ -28,20 +30,20 @@ import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeServ
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.ResourceDictionaryUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.service.ResourceDefinitionRepoService
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
import org.springframework.stereotype.Service
interface ResourceDefinitionEnhancerService {
@Throws(BluePrintException::class)
- fun enhance(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>): List<ResourceDefinition>
+ fun enhance(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>
+ ): List<ResourceDefinition>
}
@Service
class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoService: ResourceDefinitionRepoService) :
- ResourceDefinitionEnhancerService {
+ ResourceDefinitionEnhancerService {
private val log = logger(ResourceDefinitionEnhancerService::class)
@@ -54,8 +56,10 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe
// 2. Get all the Unique Resource assignments from all mapping files
// 3. Collect the Resource Definition for Resource Assignment names from database.
// 4. Create the Resource Definition under blueprint base path.
- override fun enhance(bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
- bluePrintRuntimeService: BluePrintRuntimeService<*>): List<ResourceDefinition> {
+ override fun enhance(
+ bluePrintTypeEnhancerService: BluePrintTypeEnhancerService,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>
+ ): List<ResourceDefinition> {
var resourceDefinitions: List<ResourceDefinition> = mutableListOf()
@@ -82,7 +86,6 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe
}?.mapNotNull { artifactDefinitionMap ->
artifactDefinitionMap.value.file
}
-
}?.flatten()?.distinct()
}
@@ -104,33 +107,34 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe
val distinctResourceAssignments = resourceAssignments.distinctBy { it.name }
generateResourceDictionary(blueprintBasePath, distinctResourceAssignments)
- //log.info("distinct Resource assignment ($distinctResourceAssignments)")
+ // log.info("distinct Resource assignment ($distinctResourceAssignments)")
}
-
// Read the Resource Definitions from the Database and write to type file.
- private fun generateResourceDictionary(blueprintBasePath: String, resourceAssignments: List<ResourceAssignment>)
- : List<ResourceDefinition> {
+ private fun generateResourceDictionary(blueprintBasePath: String, resourceAssignments: List<ResourceAssignment>):
+ List<ResourceDefinition> {
val resourceKeys = resourceAssignments.mapNotNull { it.dictionaryName }.distinct().sorted()
log.info("distinct resource keys ($resourceKeys)")
- //TODO("Optimise DB single Query to multiple Query")
+ // TODO("Optimise DB single Query to multiple Query")
return resourceKeys.map { resourceKey ->
getResourceDefinition(resourceKey)
}
}
- private fun enrichResourceDefinitionSources(bluePrintContext: BluePrintContext,
- resourceDefinitions: List<ResourceDefinition>) {
+ private fun enrichResourceDefinitionSources(
+ bluePrintContext: BluePrintContext,
+ resourceDefinitions: List<ResourceDefinition>
+ ) {
val sources = resourceDefinitions
- .map { it.sources }
- .map {
- it.values
- .map { nodeTemplate ->
- nodeTemplate.type
- }
- }
- .flatten().distinct()
+ .map { it.sources }
+ .map {
+ it.values
+ .map { nodeTemplate ->
+ nodeTemplate.type
+ }
+ }
+ .flatten().distinct()
log.info("Enriching Resource Definition sources Node Template: $sources")
sources.forEach {
BluePrintEnhancerUtils.populateNodeType(bluePrintContext, resourceDefinitionRepoService, it)
@@ -141,4 +145,4 @@ class ResourceDefinitionEnhancerServiceImpl(private val resourceDefinitionRepoSe
private fun getResourceDefinition(name: String): ResourceDefinition {
return resourceDefinitionRepoService.getResourceDefinition(name)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt
index 5f7eacee8..392fa0bb4 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/BluePrintModelHandler.kt
@@ -27,11 +27,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintMod
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.BootstrapRequest
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.BluePrintDatabaseLoadService
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.BluePrintEnhancerUtils
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintCompileCache
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils
import org.springframework.core.io.ByteArrayResource
@@ -46,8 +50,7 @@ import org.springframework.http.codec.multipart.FilePart
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
-import java.util.*
-
+import java.util.UUID
/**
* BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest
@@ -57,21 +60,24 @@ import java.util.*
*/
@Service
-open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService,
- private val blueprintsProcessorCatalogService: BluePrintCatalogService,
- private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintModelSearchRepository: BlueprintModelSearchRepository,
- private val blueprintModelRepository: BlueprintModelRepository,
- private val blueprintModelContentRepository: BlueprintModelContentRepository,
- private val bluePrintEnhancerService: BluePrintEnhancerService) {
+open class BluePrintModelHandler(
+ private val bluePrintDatabaseLoadService: BluePrintDatabaseLoadService,
+ private val blueprintsProcessorCatalogService: BluePrintCatalogService,
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintModelSearchRepository: BlueprintModelSearchRepository,
+ private val blueprintModelRepository: BlueprintModelRepository,
+ private val blueprintModelContentRepository: BlueprintModelContentRepository,
+ private val bluePrintEnhancerService: BluePrintEnhancerService
+) {
private val log = logger(BluePrintModelHandler::class)
-
open suspend fun bootstrapBlueprint(bootstrapRequest: BootstrapRequest) {
- log.info("Bootstrap request with type load(${bootstrapRequest.loadModelType}), " +
- "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " +
- "cba load(${bootstrapRequest.loadCBA})")
+ log.info(
+ "Bootstrap request with type load(${bootstrapRequest.loadModelType}), " +
+ "resource dictionary load(${bootstrapRequest.loadResourceDictionary}) and " +
+ "cba load(${bootstrapRequest.loadCBA})"
+ )
if (bootstrapRequest.loadModelType) {
bluePrintDatabaseLoadService.initModelTypes()
}
@@ -113,12 +119,13 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
try {
return upload(filePart, false)
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Save CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Save CBA: ${e.message}", e
+ )
}
}
-
/**
* This is a searchBlueprintModels method
*
@@ -140,9 +147,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
@Throws(BluePrintException::class)
open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch {
return blueprintModelSearchRepository.findByArtifactNameAndArtifactVersion(name, version)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version))
-
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)
+ )
}
/**
@@ -154,15 +162,19 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
* @throws BluePrintException BluePrintException
</Resource> */
@Throws(BluePrintException::class)
- open fun downloadBlueprintModelFileByNameAndVersion(name: String,
- version: String): ResponseEntity<Resource> {
+ open fun downloadBlueprintModelFileByNameAndVersion(
+ name: String,
+ version: String
+ ): ResponseEntity<Resource> {
try {
val archiveByteArray = download(name, version)
val fileName = "${name}_$version.zip"
return prepareResourceEntity(fileName, archiveByteArray)
} catch (e: BluePrintException) {
- throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while " + "downloading the CBA file: %s", e.message), e)
+ throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while " + "downloading the CBA file: %s", e.message), e
+ )
}
}
@@ -183,8 +195,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
val fileName = "${blueprintModel.artifactName}_${blueprintModel.artifactVersion}.zip"
val file = blueprintModel.blueprintModelContent?.content
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while downloading the CBA file: couldn't get model content"))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while downloading the CBA file: couldn't get model content")
+ )
return prepareResourceEntity(fileName, file)
}
@@ -193,9 +207,9 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
</Resource> */
private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> {
return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain"))
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
- .body(ByteArrayResource(file))
+ .contentType(MediaType.parseMediaType("text/plain"))
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
+ .body(ByteArrayResource(file))
}
/**
@@ -229,7 +243,7 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
@Throws(BluePrintException::class)
open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel {
val blueprintModel = blueprintModelRepository
- .findByArtifactNameAndArtifactVersion(name, version)
+ .findByArtifactNameAndArtifactVersion(name, version)
if (blueprintModel != null) {
return blueprintModel
} else {
@@ -248,8 +262,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
@Throws(BluePrintException::class)
open fun getBlueprintModelSearch(id: String): BlueprintModelSearch {
return blueprintModelSearchRepository.findById(id)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id)
+ )
}
/**
@@ -262,10 +278,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
</BlueprintModelSearch> */
open fun searchBluePrintModelsByKeyWord(keyWord: String): List<BlueprintModelSearch> {
return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
- keyWord, keyWord, keyWord, keyWord, keyWord)
+ keyWord, keyWord, keyWord, keyWord, keyWord
+ )
}
-
/**
* This is a searchBluePrintModelsByKeyWordPagebale method to retrieve specific BlueprintModel in Database
* where keyword equals updatedBy or tags or artifcat name or artifcat version or artifact type and pageable
@@ -275,7 +291,14 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
* @return List<BlueprintModelSearch> list of the controller blueprint
</BlueprintModelSearch> */
open fun searchBluePrintModelsByKeyWordPaged(keyWord: String, pageRequest: PageRequest): Page<BlueprintModelSearch> {
- return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(keyWord, keyWord, keyWord, keyWord, keyWord, pageRequest)
+ return blueprintModelSearchRepository.findByUpdatedByOrTagsOrOrArtifactNameOrOrArtifactVersionOrArtifactType(
+ keyWord,
+ keyWord,
+ keyWord,
+ keyWord,
+ keyWord,
+ pageRequest
+ )
}
/**
@@ -319,8 +342,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
val enhancedByteArray = enrichBlueprintFileSource(filePart)
return BluePrintEnhancerUtils.prepareResourceEntity("enhanced-cba.zip", enhancedByteArray)
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Enriching CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Enriching CBA: ${e.message}", e
+ )
}
}
@@ -336,8 +361,10 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
try {
return upload(filePart, true)
} catch (e: Exception) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Publishing CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Publishing CBA: ${e.message}", e
+ )
}
}
@@ -357,16 +384,19 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
val blueprintId = blueprintsProcessorCatalogService.saveToDatabase(saveId, compressedFile, validate)
return blueprintModelSearchRepository.findById(blueprintId)
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId))
-
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, blueprintId)
+ )
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Upload CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Upload CBA: ${e.message}", e
+ )
} finally {
// Clean blueprint script cache
val cacheKey = BluePrintFileUtils
- .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId))
+ .compileCacheKey(normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, saveId))
BluePrintCompileCache.cleanClassLoader(cacheKey)
deleteNBDir(blueprintArchive)
deleteNBDir(blueprintWorking)
@@ -379,11 +409,15 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
try {
val blueprintModel = getBlueprintModelByNameAndVersion(name, version)
return blueprintModel.blueprintModelContent?.content
- ?: throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while downloading the CBA file: couldn't get model content"))
+ ?: throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while downloading the CBA file: couldn't get model content")
+ )
} catch (e: BluePrintException) {
- throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
- String.format("Error while " + "downloading the CBA file: %s", e.message), e)
+ throw BluePrintException(
+ ErrorCode.RESOURCE_NOT_FOUND.value,
+ String.format("Error while " + "downloading the CBA file: %s", e.message), e
+ )
}
}
@@ -396,17 +430,18 @@ open class BluePrintModelHandler(private val bluePrintDatabaseLoadService: BlueP
try {
when (fileSource) {
is FilePart -> BluePrintEnhancerUtils
- .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
+ .copyFilePartToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
is ByteArray -> BluePrintEnhancerUtils
- .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
- } // Enhance the Blue Prints
+ .copyByteArrayToEnhanceDir(fileSource, blueprintArchive, blueprintWorkingDir)
+ } // Enhance the Blue Prints
bluePrintEnhancerService.enhance(blueprintWorkingDir)
return BluePrintEnhancerUtils.compressEnhanceDirAndReturnByteArray(blueprintWorkingDir, blueprintArchive)
-
} catch (e: IOException) {
- throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
- "Error in Enriching CBA: ${e.message}", e)
+ throw BluePrintException(
+ ErrorCode.IO_FILE_INTERRUPT.value,
+ "Error in Enriching CBA: ${e.message}", e
+ )
} finally {
BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir)
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt
index 5c7ba275d..a364f3678 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeHandler.kt
@@ -17,10 +17,10 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils.ModelTypeValidator
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@@ -46,7 +46,6 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository
}
}
-
/**
* This is a searchModelTypes service
*
@@ -66,7 +65,7 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository
* @throws BluePrintException BluePrintException
*/
@Throws(BluePrintException::class)
- suspend open fun saveModel(modelType: ModelType): ModelType {
+ open suspend fun saveModel(modelType: ModelType): ModelType {
lateinit var dbModel: ModelType
ModelTypeValidator.validateModelType(modelType)
val dbModelType: ModelType? = modelTypeRepository.findByModelName(modelType.modelName)
@@ -86,16 +85,14 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository
return dbModel
}
-
/**
* This is a deleteByModelName service
*
* @param modelName modelName
*/
- suspend open fun deleteByModelName(modelName: String) {
+ open suspend fun deleteByModelName(modelName: String) {
check(modelName.isNotBlank()) { "Model Name Information is missing." }
modelTypeRepository.deleteByModelName(modelName)
-
}
/**
@@ -119,4 +116,4 @@ open class ModelTypeHandler(private val modelTypeRepository: ModelTypeRepository
check(derivedFrom.isNotBlank()) { "Model derivedFrom Information is missing." }
return modelTypeRepository.findByDerivedFrom(derivedFrom)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt
index 8ba4c7b38..af40f56ed 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ResourceDictionaryHandler.kt
@@ -31,7 +31,6 @@ import org.springframework.stereotype.Service
@Service
class ResourceDictionaryHandler(private val resourceDictionaryRepository: ResourceDictionaryRepository) {
-
/**
* This is a getDataDictionaryByName service
*
@@ -85,8 +84,8 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour
val resourceDefinition = resourceDictionary.definition
Preconditions.checkNotNull(resourceDefinition, "failed to get resource definition from content")
// Validate the Resource Definitions
- //TODO( Save Validator)
- //validate(resourceDefinition)
+ // TODO( Save Validator)
+ // validate(resourceDefinition)
resourceDictionary.tags = resourceDefinition.tags!!
resourceDefinition.updatedBy = resourceDictionary.updatedBy
@@ -137,11 +136,11 @@ class ResourceDictionaryHandler(private val resourceDictionaryRepository: Resour
}
private fun validateResourceDictionary(resourceDictionary: ResourceDictionary): Boolean {
- checkNotEmpty(resourceDictionary.name){ "DataDictionary Definition name is missing."}
+ checkNotEmpty(resourceDictionary.name) { "DataDictionary Definition name is missing." }
checkNotNull(resourceDictionary.definition) { "DataDictionary Definition Information is missing." }
- checkNotEmpty(resourceDictionary.description){ "DataDictionary Definition Information is missing."}
- checkNotEmpty(resourceDictionary.tags){ "DataDictionary Definition tags is missing."}
- checkNotEmpty(resourceDictionary.updatedBy){ "DataDictionary Definition updatedBy is missing."}
+ checkNotEmpty(resourceDictionary.description) { "DataDictionary Definition Information is missing." }
+ checkNotEmpty(resourceDictionary.tags) { "DataDictionary Definition tags is missing." }
+ checkNotEmpty(resourceDictionary.updatedBy) { "DataDictionary Definition updatedBy is missing." }
return true
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt
index 36df06909..8d209449c 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintCatalogLoadService.kt
@@ -25,7 +25,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogS
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.io.File
-import java.util.*
+import java.util.UUID
@Service
open class BluePrintCatalogLoadService(private val controllerBlueprintsCatalogService: BluePrintCatalogService) {
@@ -66,5 +66,4 @@ open class BluePrintCatalogLoadService(private val controllerBlueprintsCatalogSe
errorBuilder.appendln("Couldn't load BlueprintModel(${file.name}: ${e.message}")
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt
index 31bd2c953..02d6ad3c1 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/BluePrintDatabaseLoadService.kt
@@ -23,10 +23,12 @@ import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
-open class BluePrintDatabaseLoadService(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val modelTypeLoadService: ModelTypeLoadService,
- private val resourceDictionaryLoadService: ResourceDictionaryLoadService,
- private val bluePrintCatalogLoadService: BluePrintCatalogLoadService) {
+open class BluePrintDatabaseLoadService(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val modelTypeLoadService: ModelTypeLoadService,
+ private val resourceDictionaryLoadService: ResourceDictionaryLoadService,
+ private val bluePrintCatalogLoadService: BluePrintCatalogLoadService
+) {
private val log = LoggerFactory.getLogger(BluePrintDatabaseLoadService::class.java)
@@ -62,4 +64,4 @@ open class BluePrintDatabaseLoadService(private val bluePrintLoadConfiguration:
bluePrintCatalogLoadService.loadPathsBluePrintModelCatalog(paths)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt
index 9f43740aa..e96daf9f0 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ModelTypeLoadService.kt
@@ -26,7 +26,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.handler.ModelTypeHandler
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.EntityType
+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.normalizedFile
import org.onap.ccsdk.cds.controllerblueprints.core.readNBText
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@@ -108,7 +112,7 @@ open class ModelTypeLoadService(private val modelTypeHandler: ModelTypeHandler)
val dataKey = FilenameUtils.getBaseName(file.name)
val definitionContent = file.readNBText()
val definition = JacksonUtils.readValue(definitionContent, classType) as EntityType
- //checkNotNull(definition) { "failed to get data type from file : ${file.name}" }
+ // checkNotNull(definition) { "failed to get data type from file : ${file.name}" }
val modelType = ModelType()
val definitionType: String?
@@ -143,4 +147,4 @@ open class ModelTypeLoadService(private val modelTypeHandler: ModelTypeHandler)
errorBuilder.appendln("Couldn't load ${classType.name}(${file.name}: ${e.message}")
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt
index 95073e99d..0350bc731 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/load/ResourceDictionaryLoadService.kt
@@ -66,7 +66,6 @@ open class ResourceDictionaryLoadService(private val resourceDictionaryHandler:
if (!errorBuilder.isEmpty) {
log.error(errorBuilder.toString())
}
-
}
private suspend fun loadResourceDictionary(errorBuilder: StrBuilder, file: File) {
@@ -91,9 +90,8 @@ open class ResourceDictionaryLoadService(private val resourceDictionaryHandler:
resourceDictionary.updatedBy = resourceDefinition.updatedBy
if (StringUtils.isBlank(resourceDefinition.tags)) {
- resourceDictionary.tags = (resourceDefinition.name + ", " + resourceDefinition.updatedBy
- + ", " + resourceDefinition.updatedBy)
-
+ resourceDictionary.tags = (resourceDefinition.name + ", " + resourceDefinition.updatedBy +
+ ", " + resourceDefinition.updatedBy)
} else {
resourceDictionary.tags = resourceDefinition.tags!!
}
@@ -107,5 +105,4 @@ open class ResourceDictionaryLoadService(private val resourceDictionaryHandler:
errorBuilder.appendln("Couldn't load Resource dictionary (${file.name}: ${e.message}")
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/BluePrintsReactRepository.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepository.kt
index 1d69cd7cc..80aa6b49a 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/BluePrintsReactRepository.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepository.kt
@@ -21,6 +21,7 @@ import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
+
// TODO("Convert into coroutines")
/**
* ModelTypeReactRepository.
@@ -40,37 +41,36 @@ open class ModelTypeReactRepository(private val modelTypeRepository: ModelTypeRe
fun findByModelNameIn(modelNames: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByModelNameIn(modelNames))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDerivedFrom(derivedFrom: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDerivedFrom(derivedFrom))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDerivedFromIn(derivedFroms: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDerivedFromIn(derivedFroms))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDefinitionType(definitionType: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDefinitionType(definitionType))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByDefinitionTypeIn(definitionTypes: List<String>): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByDefinitionTypeIn(definitionTypes))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun findByTagsContainingIgnoreCase(tags: String): Flux<ModelType> {
return Flux.fromIterable(modelTypeRepository.findByTagsContainingIgnoreCase(tags))
- .subscribeOn(Schedulers.elastic())
+ .subscribeOn(Schedulers.elastic())
}
fun deleteByModelName(modelName: String): Mono<Void> {
modelTypeRepository.deleteByModelName(modelName)
return Mono.empty()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeRepository.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeRepository.kt
index 3e36947a4..8beea7161 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeRepository.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeRepository.kt
@@ -23,6 +23,7 @@ import javax.transaction.Transactional
@Repository
interface ModelTypeRepository : JpaRepository<ModelType, String> {
+
/**
* This is a findByModelName method
*
@@ -30,6 +31,7 @@ interface ModelTypeRepository : JpaRepository<ModelType, String> {
* @return Optional<ModelType>
*/
fun findByModelName(modelName: String): ModelType?
+
/**
* This is a findByModelNameIn method
*
@@ -37,19 +39,21 @@ interface ModelTypeRepository : JpaRepository<ModelType, String> {
* @return List<ModelType>
*/
fun findByModelNameIn(modelNames: List<String>): List<ModelType>
+
/**
* This is a findByDerivedFrom method
*
* @param derivedFrom Derived From
* @return List<ModelType>
- */
+ */
fun findByDerivedFrom(derivedFrom: String): List<ModelType>
+
/**
* This is a findByDerivedFromIn method
*
* @param derivedFroms Derived Froms
* @return List<ModelType>
- */
+ */
fun findByDerivedFromIn(derivedFroms: List<String>): List<ModelType>
/**
@@ -59,12 +63,13 @@ interface ModelTypeRepository : JpaRepository<ModelType, String> {
* @return List<ModelType>
*/
fun findByDefinitionType(definitionType: String): List<ModelType>
+
/**
* This is a findByDefinitionTypeIn method
*
* @param definitionTypes Definition Types
* @return List<ModelType>
- */
+ */
fun findByDefinitionTypeIn(definitionTypes: List<String>): List<ModelType>
/**
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepository.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepository.kt
index 68db371c6..da7893861 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepository.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepository.kt
@@ -20,7 +20,6 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictio
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
-
/**
* ResourceMappingRepository.java Purpose: Provide Configuration Generator ResourceMappingRepository
*
@@ -30,7 +29,6 @@ import org.springframework.stereotype.Repository
@Repository
interface ResourceDictionaryRepository : JpaRepository<ResourceDictionary, String> {
-
/**
* This is a findByName method
*
@@ -61,6 +59,4 @@ interface ResourceDictionaryRepository : JpaRepository<ResourceDictionary, Strin
* @param name name
*/
fun deleteByName(name: String)
-
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt
index f8e6163a5..420a9fcd7 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/service/BluePrintRepoServiceImpl.kt
@@ -23,7 +23,11 @@ import org.apache.commons.lang3.StringUtils
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ModelTypeRepository
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.repository.ResourceDictionaryRepository
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.CapabilityDefinition
+import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
+import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition
@@ -36,37 +40,39 @@ interface ResourceDefinitionRepoService : BluePrintRepoService {
}
@Service
-open class BluePrintRepoFileService(private val modelTypeRepository: ModelTypeRepository,
- private val resourceDictionaryRepository: ResourceDictionaryRepository) : ResourceDefinitionRepoService {
+open class BluePrintRepoFileService(
+ private val modelTypeRepository: ModelTypeRepository,
+ private val resourceDictionaryRepository: ResourceDictionaryRepository
+) : ResourceDefinitionRepoService {
@Throws(BluePrintException::class)
override fun getNodeType(nodeTypeName: String): NodeType {
return getModelType(nodeTypeName, NodeType::class.java)
- ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)")
+ ?: throw BluePrintException("couldn't get NodeType($nodeTypeName)")
}
@Throws(BluePrintException::class)
override fun getDataType(dataTypeName: String): DataType {
return getModelType(dataTypeName, DataType::class.java)
- ?: throw BluePrintException("couldn't get DataType($dataTypeName)")
+ ?: throw BluePrintException("couldn't get DataType($dataTypeName)")
}
@Throws(BluePrintException::class)
override fun getArtifactType(artifactTypeName: String): ArtifactType {
return getModelType(artifactTypeName, ArtifactType::class.java)
- ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)")
+ ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName)")
}
@Throws(BluePrintException::class)
override fun getRelationshipType(relationshipTypeName: String): RelationshipType {
return getModelType(relationshipTypeName, RelationshipType::class.java)
- ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)")
+ ?: throw BluePrintException("couldn't get RelationshipType($relationshipTypeName)")
}
@Throws(BluePrintException::class)
override fun getCapabilityDefinition(capabilityDefinitionName: String): CapabilityDefinition {
return getModelType(capabilityDefinitionName, CapabilityDefinition::class.java)
- ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)")
+ ?: throw BluePrintException("couldn't get CapabilityDefinition($capabilityDefinitionName)")
}
@Throws(BluePrintException::class)
@@ -81,12 +87,16 @@ open class BluePrintRepoFileService(private val modelTypeRepository: ModelTypeRe
@Throws(BluePrintException::class)
private fun <T> getModelType(modelName: String, valueClass: Class<T>): T? {
- Preconditions.checkArgument(StringUtils.isNotBlank(modelName),
- "Failed to get model from repo, model name is missing")
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(modelName),
+ "Failed to get model from repo, model name is missing"
+ )
val modelDefinition = getModelDefinition(modelName)
- Preconditions.checkNotNull(modelDefinition,
- String.format("Failed to get model content for model name (%s)", modelName))
+ Preconditions.checkNotNull(
+ modelDefinition,
+ String.format("Failed to get model content for model name (%s)", modelName)
+ )
return JacksonUtils.readValue(modelDefinition, valueClass)
}
@@ -102,4 +112,4 @@ open class BluePrintRepoFileService(private val modelTypeRepository: ModelTypeRe
}
return modelDefinition
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt
index c79d1b526..4d5ca36cf 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtils.kt
@@ -19,12 +19,18 @@
package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils
import kotlinx.coroutines.reactive.awaitSingle
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ArtifactType
import org.onap.ccsdk.cds.controllerblueprints.core.data.DataType
import org.onap.ccsdk.cds.controllerblueprints.core.data.NodeType
import org.onap.ccsdk.cds.controllerblueprints.core.data.RelationshipType
+import org.onap.ccsdk.cds.controllerblueprints.core.deCompress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteNBDir
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintRepoService
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateNBDirs
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
import org.springframework.core.io.ByteArrayResource
@@ -36,47 +42,57 @@ import org.springframework.http.codec.multipart.FilePart
import java.io.File
import java.nio.file.Paths
-
class BluePrintEnhancerUtils {
companion object {
val log = logger(BluePrintEnhancerUtils)
- fun populateDataTypes(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- dataTypeName: String): DataType {
+ fun populateDataTypes(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ dataTypeName: String
+ ): DataType {
val dataType = bluePrintContext.serviceTemplate.dataTypes?.get(dataTypeName)
- ?: bluePrintRepoService.getDataType(dataTypeName)
- ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.")
+ ?: bluePrintRepoService.getDataType(dataTypeName)
+ ?: throw BluePrintException("couldn't get DataType($dataTypeName) from repo.")
bluePrintContext.serviceTemplate.dataTypes?.put(dataTypeName, dataType)
return dataType
}
- fun populateRelationshipType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- relationshipName: String): RelationshipType {
+ fun populateRelationshipType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ relationshipName: String
+ ): RelationshipType {
val relationshipType = bluePrintContext.serviceTemplate.relationshipTypes?.get(relationshipName)
- ?: bluePrintRepoService.getRelationshipType(relationshipName)
- ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.")
+ ?: bluePrintRepoService.getRelationshipType(relationshipName)
+ ?: throw BluePrintException("couldn't get RelationshipType($relationshipName) from repo.")
bluePrintContext.serviceTemplate.relationshipTypes?.put(relationshipName, relationshipType)
return relationshipType
}
-
- fun populateNodeType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- nodeTypeName: String): NodeType {
+ fun populateNodeType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ nodeTypeName: String
+ ): NodeType {
val nodeType = bluePrintContext.serviceTemplate.nodeTypes?.get(nodeTypeName)
- ?: bluePrintRepoService.getNodeType(nodeTypeName)
- ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.")
+ ?: bluePrintRepoService.getNodeType(nodeTypeName)
+ ?: throw BluePrintException("couldn't get NodeType($nodeTypeName) from repo.")
bluePrintContext.serviceTemplate.nodeTypes?.put(nodeTypeName, nodeType)
return nodeType
}
- fun populateArtifactType(bluePrintContext: BluePrintContext, bluePrintRepoService: BluePrintRepoService,
- artifactTypeName: String): ArtifactType {
+ fun populateArtifactType(
+ bluePrintContext: BluePrintContext,
+ bluePrintRepoService: BluePrintRepoService,
+ artifactTypeName: String
+ ): ArtifactType {
val artifactType = bluePrintContext.serviceTemplate.artifactTypes?.get(artifactTypeName)
- ?: bluePrintRepoService.getArtifactType(artifactTypeName)
- ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.")
+ ?: bluePrintRepoService.getArtifactType(artifactTypeName)
+ ?: throw BluePrintException("couldn't get ArtifactType($artifactTypeName) from repo.")
bluePrintContext.serviceTemplate.artifactTypes?.put(artifactTypeName, artifactType)
return artifactType
}
@@ -90,17 +106,16 @@ class BluePrintEnhancerUtils {
return targetFile
}
-
suspend fun filePartAsFile(filePart: FilePart, targetFile: File): File {
// Delete the Directory
targetFile.parentFile.reCreateNBDirs()
return filePart.transferTo(targetFile)
- .thenReturn(targetFile)
- .awaitSingle()
+ .thenReturn(targetFile)
+ .awaitSingle()
}
private suspend fun byteArrayAsArchiveFile(byteArray: ByteArray, archiveDir: String, enhanceDir: String): File {
- //Recreate the Base Directories
+ // Recreate the Base Directories
normalizedFile(archiveDir).reCreateNBDirs()
normalizedFile(enhanceDir).reCreateNBDirs()
val archiveFile = normalizedFile(archiveDir, "cba.zip")
@@ -109,7 +124,7 @@ class BluePrintEnhancerUtils {
}
private suspend fun filePartAsArchiveFile(filePart: FilePart, archiveDir: String, enhanceDir: String): File {
- //Recreate the Base Directories
+ // Recreate the Base Directories
normalizedFile(archiveDir).reCreateNBDirs()
normalizedFile(enhanceDir).reCreateNBDirs()
val archiveFile = normalizedFile(archiveDir, "cba.zip")
@@ -132,17 +147,23 @@ class BluePrintEnhancerUtils {
}
/** compress [enhanceDir] to [archiveDir] and return ByteArray */
- suspend fun compressEnhanceDirAndReturnByteArray(enhanceDir: String, archiveDir: String,
- outputFileName: String = "enhanced-cba.zip"): ByteArray {
+ suspend fun compressEnhanceDirAndReturnByteArray(
+ enhanceDir: String,
+ archiveDir: String,
+ outputFileName: String = "enhanced-cba.zip"
+ ): ByteArray {
val compressedFile = normalizedFile(archiveDir, outputFileName)
BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile)
return compressedFile.readBytes()
}
/** compress [enhanceDir] to [archiveDir] and return ResponseEntity */
- suspend fun compressEnhanceDirAndReturnFilePart(enhanceDir: String, archiveDir: String,
- outputFileName: String = "enhanced-cba.zip")
- : ResponseEntity<Resource> {
+ suspend fun compressEnhanceDirAndReturnFilePart(
+ enhanceDir: String,
+ archiveDir: String,
+ outputFileName: String = "enhanced-cba.zip"
+ ):
+ ResponseEntity<Resource> {
val compressedFile = normalizedFile(archiveDir, outputFileName)
BluePrintArchiveUtils.compress(Paths.get(enhanceDir).toFile(), compressedFile)
return prepareResourceEntity(compressedFile)
@@ -152,12 +173,13 @@ class BluePrintEnhancerUtils {
suspend fun prepareResourceEntity(file: File): ResponseEntity<Resource> {
return prepareResourceEntity(file.name, file.readBytes())
}
+
/** convert [byteArray] to ResourceEntity with [fileName]*/
fun prepareResourceEntity(fileName: String, byteArray: ByteArray): ResponseEntity<Resource> {
return ResponseEntity.ok()
- .contentType(MediaType.parseMediaType("text/plain"))
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
- .body(ByteArrayResource(byteArray))
+ .contentType(MediaType.parseMediaType("text/plain"))
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
+ .body(ByteArrayResource(byteArray))
}
suspend fun cleanEnhancer(archiveLocation: String, enhancementLocation: String) {
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/SortByOptionsEnum.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintSortByOption.kt
index 6f5636516..92573892a 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/SortByOptionsEnum.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BlueprintSortByOption.kt
@@ -3,4 +3,4 @@ package org.onap.ccsdk.cds.blueprintsprocessor.designer.api.utils
enum class BlueprintSortByOption(val columnName: String) {
DATE("createdDate"),
NAME("artifactName")
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt
index 8ec0b9bab..6b9ea28f0 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/ModelTypeValidator.kt
@@ -21,7 +21,11 @@ import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
-import org.onap.ccsdk.cds.controllerblueprints.core.data.*
+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.utils.JacksonUtils
class ModelTypeValidator {
@@ -38,23 +42,23 @@ class ModelTypeValidator {
when (definitionType) {
BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE -> {
JacksonUtils.readValue(definitionContent, DataType::class.java)
- ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not DataType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_NODE_TYPE -> {
JacksonUtils.readValue(definitionContent, NodeType::class.java)
- ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not NodeType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_ARTIFACT_TYPE -> {
JacksonUtils.readValue(definitionContent, ArtifactType::class.java)
- ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not ArtifactType valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_CAPABILITY_TYPE -> {
JacksonUtils.readValue(definitionContent, CapabilityDefinition::class.java)
- ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not CapabilityDefinition valid content $definitionContent")
}
BluePrintConstants.MODEL_DEFINITION_TYPE_RELATIONSHIP_TYPE -> {
JacksonUtils.readValue(definitionContent, RelationshipType::class.java)
- ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent")
+ ?: throw BluePrintException("Model type definition is not RelationshipType valid content $definitionContent")
}
}
return true
@@ -79,5 +83,4 @@ class ModelTypeValidator {
return true
}
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt
index 61f515017..582fd9a41 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BluePrintManagementGRPCHandlerTest.kt
@@ -32,20 +32,29 @@ import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
-import org.onap.ccsdk.cds.controllerblueprints.management.api.*
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintBootstrapInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintDownloadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintRemoveInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput
+import org.onap.ccsdk.cds.controllerblueprints.management.api.DownloadAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk
+import org.onap.ccsdk.cds.controllerblueprints.management.api.RemoveAction
+import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction
import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration
-import org.springframework.context.annotation.ComponentScan
-import org.springframework.test.annotation.DirtiesContext
+import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-import kotlin.test.*
+import kotlin.test.AfterTest
+import kotlin.test.BeforeTest
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
-@EnableAutoConfiguration
-@DirtiesContext
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintManagementGRPCHandlerTest {
@@ -74,8 +83,10 @@ class BluePrintManagementGRPCHandlerTest {
val req = createBootstrapInputRequest(id)
val bootstrapOutput = blockingStub.bootstrapBlueprint(req)
assertEquals(200, bootstrapOutput.status.code)
- assertTrue(bootstrapOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ bootstrapOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, bootstrapOutput.commonHeader.requestId)
}
@@ -87,8 +98,10 @@ class BluePrintManagementGRPCHandlerTest {
val output = blockingStub.uploadBlueprint(req)
assertEquals(200, output.status.code)
- assertTrue(output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, output.commonHeader.requestId)
val downloadId = "123_download"
@@ -96,8 +109,10 @@ class BluePrintManagementGRPCHandlerTest {
val downloadOutput = blockingStub.downloadBlueprint(downloadReq)
assertEquals(200, downloadOutput.status.code)
- assertTrue(downloadOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ downloadOutput.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertNotNull(downloadOutput.fileChunk?.chunk, "failed to get cba file chunks")
assertEquals(downloadId, downloadOutput.commonHeader.requestId)
}
@@ -110,8 +125,10 @@ class BluePrintManagementGRPCHandlerTest {
var output = blockingStub.uploadBlueprint(req)
assertEquals(200, output.status.code)
- assertTrue(output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
- "failed to get success status")
+ assertTrue(
+ output.status.message.contentEquals(BluePrintConstants.STATUS_SUCCESS),
+ "failed to get success status"
+ )
assertEquals(id, output.commonHeader.requestId)
val removeReq = createRemoveInputRequest(id)
@@ -142,18 +159,18 @@ class BluePrintManagementGRPCHandlerTest {
private fun createBootstrapInputRequest(id: String): BluePrintBootstrapInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintBootstrapInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setLoadModelType(false)
- .setLoadResourceDictionary(false)
- .setLoadCBA(false)
- .build()
+ .setCommonHeader(commonHeader)
+ .setLoadModelType(false)
+ .setLoadResourceDictionary(false)
+ .setLoadCBA(false)
+ .build()
}
private fun createUploadInputRequest(id: String, action: String): BluePrintUploadInput {
@@ -161,59 +178,63 @@ class BluePrintManagementGRPCHandlerTest {
assertTrue(file.exists(), "couldnt get file ${file.absolutePath}")
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName(action)
- .setBlueprintName("sample")
- .setBlueprintVersion("1.0.0")
- .build()
+ .setActionName(action)
+ .setBlueprintName("sample")
+ .setBlueprintVersion("1.0.0")
+ .build()
val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes()))
- .build()
+ .build()
return BluePrintUploadInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setFileChunk(fileChunk)
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setFileChunk(fileChunk)
+ .build()
}
private fun createDownloadInputRequest(id: String, action: String): BluePrintDownloadInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintDownloadInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(ActionIdentifiers.newBuilder()
- .setBlueprintName("baseconfiguration")
- .setBlueprintVersion("1.0.0")
- .setActionName(action).build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(
+ ActionIdentifiers.newBuilder()
+ .setBlueprintName("baseconfiguration")
+ .setBlueprintVersion("1.0.0")
+ .setActionName(action).build()
+ )
+ .build()
}
private fun createRemoveInputRequest(id: String): BluePrintRemoveInput {
val commonHeader = CommonHeader
- .newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(id)
- .setSubRequestId("1234-56").build()
+ .newBuilder()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(id)
+ .setSubRequestId("1234-56").build()
return BluePrintRemoveInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(ActionIdentifiers.newBuilder()
- .setBlueprintName("sample")
- .setBlueprintVersion("1.0.0")
- .setActionName(RemoveAction.DEFAULT.toString()).build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(
+ ActionIdentifiers.newBuilder()
+ .setBlueprintName("sample")
+ .setBlueprintVersion("1.0.0")
+ .setActionName(RemoveAction.DEFAULT.toString()).build()
+ )
+ .build()
}
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt
index 149acb03c..0e33884a0 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/BlueprintModelControllerTest.kt
@@ -26,12 +26,14 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintModelSearch
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.compress
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.core.io.ByteArrayResource
@@ -60,8 +62,9 @@ import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class BlueprintModelControllerTest {
@@ -82,7 +85,6 @@ class BlueprintModelControllerTest {
private var testZipFile: File? = null
-
@Before
fun setUp() {
assertNotNull(webTestClient, " Failed to create WebTestClient")
@@ -121,14 +123,14 @@ class BlueprintModelControllerTest {
}.build()
val saveBP = webTestClient
- .post()
- .uri("/api/v1/blueprint-model")
- .body(BodyInserters.fromMultipartData(body))
- .exchange()
- .expectStatus().isOk
- .returnResult<BlueprintModelSearch>()
- .responseBody
- .awaitSingle()
+ .post()
+ .uri("/api/v1/blueprint-model")
+ .body(BodyInserters.fromMultipartData(body))
+ .exchange()
+ .expectStatus().isOk
+ .returnResult<BlueprintModelSearch>()
+ .responseBody
+ .awaitSingle()
assertNotNull(saveBP, "failed to get response")
assertEquals("baseconfiguration", saveBP.artifactName, "mismatch artifact name")
@@ -141,18 +143,21 @@ class BlueprintModelControllerTest {
@Test
@Throws(JSONException::class)
fun test02_getBluePrintByNameAndVersion() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
+ HttpStatus.OK, false
+ )
}
-
@Test
@Throws(JSONException::class)
fun test03_getBlueprintModel() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/${bp!!.id}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/${bp!!.id}",
+ HttpStatus.OK, false
+ )
}
@Test
@@ -164,9 +169,11 @@ class BlueprintModelControllerTest {
@Test
@Throws(JSONException::class)
fun test05_downloadBluePrint() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/download/${bp!!.id}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/download/${bp!!.id}",
+ HttpStatus.OK, false
+ )
}
@Test
@@ -185,14 +192,14 @@ class BlueprintModelControllerTest {
}.build()
val publishBP = webTestClient
- .post()
- .uri("/api/v1/blueprint-model/publish")
- .body(BodyInserters.fromMultipartData(body))
- .exchange()
- .expectStatus().isOk
- .returnResult<BlueprintModelSearch>()
- .responseBody
- .awaitSingle()
+ .post()
+ .uri("/api/v1/blueprint-model/publish")
+ .body(BodyInserters.fromMultipartData(body))
+ .exchange()
+ .expectStatus().isOk
+ .returnResult<BlueprintModelSearch>()
+ .responseBody
+ .awaitSingle()
assertNotNull(publishBP, "failed to get response")
assertEquals("baseconfiguration", publishBP.artifactName, "mismatch artifact name")
@@ -205,49 +212,60 @@ class BlueprintModelControllerTest {
@Test
@Throws(JSONException::class)
fun test08_searchBlueprintModels() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/search/${bp!!.artifactName}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/search/${bp!!.artifactName}",
+ HttpStatus.OK, false
+ )
}
@Test
@Throws(JSONException::class)
fun test09_downloadBlueprintByNameAndVersion() {
- webTestClient(HttpMethod.GET, null,
- "/api/v1/blueprint-model/download/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
- HttpStatus.OK, false)
+ webTestClient(
+ HttpMethod.GET, null,
+ "/api/v1/blueprint-model/download/by-name/${bp!!.artifactName}/version/${bp!!.artifactVersion}",
+ HttpStatus.OK, false
+ )
}
@Test
fun test10_deleteBluePrint() {
-// webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}")
-// .header("Authorization", "Basic " + Base64Utils
-// .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
-// .exchange()
-// .expectStatus().is2xxSuccessful
+ // webTestClient.delete().uri("/api/v1/blueprint-model/${bp!!.id}")
+ // .header("Authorization", "Basic " + Base64Utils
+ // .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
+ // .exchange()
+ // .expectStatus().is2xxSuccessful
webTestClient.delete().uri("/api/v1/blueprint-model/name/${bp!!.artifactName}/version/${bp!!.artifactVersion}")
- .header("Authorization", "Basic " + Base64Utils
- .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
- .exchange()
- .expectStatus().is2xxSuccessful
+ .header(
+ "Authorization", "Basic " + Base64Utils
+ .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))
+ )
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
@Throws(JSONException::class)
- private fun webTestClient(requestMethod: HttpMethod, body: BodyInserters.MultipartInserter?, uri: String,
- expectedResponceStatus: HttpStatus, setParam: Boolean) {
+ private fun webTestClient(
+ requestMethod: HttpMethod,
+ body: BodyInserters.MultipartInserter?,
+ uri: String,
+ expectedResponceStatus: HttpStatus,
+ setParam: Boolean
+ ) {
log.info("Requesting($uri): Method(${requestMethod.name})")
webTestClient.method(requestMethod).uri(uri)
- .header("Authorization", "Basic " + Base64Utils
- .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8)))
- .body(body)
- .exchange()
- .expectStatus().isEqualTo(expectedResponceStatus)
- .expectBody()
- .returnResult().responseBody!!
-
+ .header(
+ "Authorization", "Basic " + Base64Utils
+ .encodeToString(("ccsdkapps" + ":" + "ccsdkapps").toByteArray(UTF_8))
+ )
+ .body(body)
+ .exchange()
+ .expectStatus().isEqualTo(expectedResponceStatus)
+ .expectBody()
+ .returnResult().responseBody!!
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiTestConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiTestConfiguration.kt
index 03e016b8e..33a2bd778 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiTestConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/DesignerApiTestConfiguration.kt
@@ -21,7 +21,10 @@ import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
@Configuration
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.controllerblueprints",
- "org.onap.ccsdk.cds.blueprintsprocessor"])
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.controllerblueprints",
+ "org.onap.ccsdk.cds.blueprintsprocessor.designer.api",
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary"]
+)
@EnableAutoConfiguration
open class DesignerApiTestConfiguration
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt
index 8871676d2..6b409dbef 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ModelTypeControllerTest.kt
@@ -21,12 +21,9 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
@@ -35,8 +32,9 @@ import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeControllerTest {
@@ -62,8 +60,8 @@ class ModelTypeControllerTest {
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
modelType = modelTypeController!!.saveModelType(modelType)
log.info("Saved Mode {}", modelType.toString())
@@ -71,15 +69,16 @@ class ModelTypeControllerTest {
Assert.assertNotNull("Failed to get Saved ModelType, Id", modelType.modelName)
val dbModelType = modelTypeController!!.getModelTypeByName(modelType.modelName)
- Assert.assertNotNull("Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
- dbModelType)
+ Assert.assertNotNull(
+ "Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
+ dbModelType
+ )
// Model Update
modelType.updatedBy = "bs2796@xxx.com"
modelType = modelTypeController!!.saveModelType(modelType)
Assert.assertNotNull("Failed to get Saved ModelType", modelType)
Assert.assertEquals("Failed to get Saved getUpdatedBy ", "bs2796@xxx.com", modelType.updatedBy)
-
}
@Test
@@ -92,7 +91,6 @@ class ModelTypeControllerTest {
val dbModelTypes = modelTypeController!!.searchModelTypes(tags)
Assert.assertNotNull("Failed to search ResourceMapping by tags", dbModelTypes)
Assert.assertTrue("Failed to search ResourceMapping by tags count", dbModelTypes.isNotEmpty())
-
}
@Test
@@ -113,7 +111,8 @@ class ModelTypeControllerTest {
@Throws(Exception::class)
fun test04DeleteModelType() {
log.info(
- "************************ test03DeleteModelType ***********************")
+ "************************ test03DeleteModelType ***********************"
+ )
val dbResourceMapping = modelTypeController!!.getModelTypeByName(modelName)
Assert.assertNotNull("Failed to get response for api call getModelByName ", dbResourceMapping)
Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbResourceMapping!!.modelName)
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryControllerTest.kt
index b13b1ac08..c4390dbd2 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/ResourceDictionaryControllerTest.kt
@@ -20,9 +20,6 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ContextConfiguration
@@ -32,8 +29,9 @@ import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ResourceDictionaryControllerTest {
@@ -45,5 +43,4 @@ class ResourceDictionaryControllerTest {
fun testResourceDictionaryControllerPresence() {
assertNotNull(resourceDictionaryController, "failed to initialise ResourceDictionaryController")
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt
new file mode 100644
index 000000000..be012bbc0
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/TestDatabaseConfiguration.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.designer.api
+
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
+import org.springframework.transaction.PlatformTransactionManager
+import javax.sql.DataSource
+
+@Configuration
+@Import(BluePrintDBLibConfiguration::class)
+@EnableJpaRepositories(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.designer.api"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
+)
+@EnableJpaAuditing
+open class TestDatabaseConfiguration(primaryDataSourceProperties: PrimaryDataSourceProperties) :
+ PrimaryDatabaseConfiguration(primaryDataSourceProperties) {
+
+ @Bean("primaryEntityManager")
+ open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ return primaryEntityManager(
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.designer.api"
+ )
+ }
+
+ @Bean("primaryDataSource")
+ override fun primaryDataSource(): DataSource {
+ return super.primaryDataSource()
+ }
+
+ @Bean("primaryTransactionManager")
+ override fun primaryTransactionManager(): PlatformTransactionManager {
+ return super.primaryTransactionManager()
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt
index a5a0511f5..2762725fa 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/enhancer/BluePrintEnhancerServiceImplTest.kt
@@ -21,9 +21,6 @@ import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ModelTypeLoadService
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.load.ResourceDictionaryLoadService
@@ -37,8 +34,9 @@ import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintEnhancerServiceImplTest {
@@ -54,7 +52,6 @@ class BluePrintEnhancerServiceImplTest {
@Autowired
lateinit var bluePrintValidatorService: BluePrintValidatorService
-
@Test
@Throws(Exception::class)
fun testEnhancementAndValidation() {
@@ -93,7 +90,6 @@ class BluePrintEnhancerServiceImplTest {
fun testRemoteScriptsEnhancementAndValidation() {
val basePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/remote_scripts"
testComponentInvokeEnhancementAndValidation(basePath, "remote_scripts-enhance")
-
}
fun testCapabilityCliEnhancementAndValidation() {
@@ -115,12 +111,10 @@ class BluePrintEnhancerServiceImplTest {
Assert.assertTrue("blueprint($basePath) validation failed ", valid)
// Enable this to get the enhanced zip file
-// val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip")
-// normalizedFile(targetPath).compress(compressFile)
+ // val compressFile = normalizedFile("target/blueprints/enrichment", "$targetDirName.zip")
+ // normalizedFile(targetPath).compress(compressFile)
deleteDir(targetPath)
}
}
-
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt
index 7ea845dee..c4a77e565 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/handler/ModelTypeServiceTest.kt
@@ -22,13 +22,10 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
@@ -36,13 +33,14 @@ import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeServiceTest {
+
@Autowired
private val modelTypeHandler: ModelTypeHandler? = null
@@ -65,8 +63,8 @@ class ModelTypeServiceTest {
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
modelType = modelTypeHandler!!.saveModel(modelType)
log.info("Saved Mode {}", modelType.toString())
@@ -74,8 +72,10 @@ class ModelTypeServiceTest {
Assert.assertNotNull("Failed to get Saved ModelType, Id", modelType.modelName)
val dbModelType = modelTypeHandler.getModelTypeByName(modelType.modelName)
- Assert.assertNotNull("Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
- dbModelType)
+ Assert.assertNotNull(
+ "Failed to query ResourceMapping for ID (" + dbModelType!!.modelName + ")",
+ dbModelType
+ )
// Model Update
modelType.updatedBy = "bs2796@xxx.com"
@@ -83,7 +83,6 @@ class ModelTypeServiceTest {
Assert.assertNotNull("Failed to get Saved ModelType", modelType)
Assert.assertEquals("Failed to get Saved getUpdatedBy ", "bs2796@xxx.com", modelType.updatedBy)
}
-
}
@Test
@@ -98,7 +97,6 @@ class ModelTypeServiceTest {
Assert.assertNotNull("Failed to search ResourceMapping by tags", dbModelTypes)
Assert.assertTrue("Failed to search ResourceMapping by tags count", dbModelTypes.size > 0)
}
-
}
@Test
@@ -118,7 +116,6 @@ class ModelTypeServiceTest {
Assert.assertNotNull("Failed to find getModelTypeByDerivedFrom by tags", dbModelTypeByDerivedFroms)
Assert.assertTrue("Failed to find getModelTypeByDerivedFrom by count", dbModelTypeByDerivedFroms.size > 0)
}
-
}
@Test
@@ -126,7 +123,8 @@ class ModelTypeServiceTest {
fun test04DeleteModelType() {
runBlocking {
log.info(
- "************************ test03DeleteModelType ***********************")
+ "************************ test03DeleteModelType ***********************"
+ )
val dbResourceMapping = modelTypeHandler!!.getModelTypeByName(modelName)
Assert.assertNotNull("Failed to get response for api call getModelByName ", dbResourceMapping)
Assert.assertNotNull("Failed to get Id for api call getModelByName ", dbResourceMapping!!.modelName)
@@ -134,5 +132,4 @@ class ModelTypeServiceTest {
modelTypeHandler.deleteByModelName(dbResourceMapping.modelName)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/mock/MockFilePart.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/mock/MockFilePart.kt
index 3165a6e2f..27949901c 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/mock/MockFilePart.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/mock/MockFilePart.kt
@@ -30,11 +30,11 @@ import java.nio.file.Path
class MockFilePart(private val fileName: String) : FilePart {
val log = LoggerFactory.getLogger(MockFilePart::class.java)!!
override fun content(): Flux<DataBuffer> {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun headers(): HttpHeaders {
- TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
+ TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
override fun filename(): String {
@@ -46,8 +46,8 @@ class MockFilePart(private val fileName: String) : FilePart {
}
override fun transferTo(path: Path): Mono<Void> {
- log.info("Copying file($fileName to ${path}")
+ log.info("Copying file($fileName to $path")
FileCopyUtils.copy(File(fileName), path.toFile())
return Mono.empty()
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt
index 3dfed1ccb..4c05f6009 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ModelTypeReactRepositoryTest.kt
@@ -21,21 +21,18 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
-import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ModelType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.annotation.Commit
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import java.nio.charset.Charset
-import java.util.*
+import java.util.Arrays
/**
* ModelTypeReactRepositoryTest.
@@ -44,8 +41,9 @@ import java.util.*
*/
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ModelTypeReactRepositoryTest {
@@ -59,7 +57,7 @@ class ModelTypeReactRepositoryTest {
@Commit
fun test01Save() {
val content = normalizedFile("./src/test/resources/model_type/data_type/datatype-property.json")
- .readText(Charset.defaultCharset())
+ .readText(Charset.defaultCharset())
val modelType = ModelType()
modelType.definitionType = BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE
modelType.derivedFrom = BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT
@@ -67,8 +65,8 @@ class ModelTypeReactRepositoryTest {
modelType.definition = JacksonUtils.jsonNode(content)
modelType.modelName = modelName
modelType.version = "1.0.0"
- modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + ","
- + BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
+ modelType.tags = ("test-datatype ," + BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT + "," +
+ BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)
modelType.updatedBy = "xxxxxx@xxx.com"
val dbModelType = modelTypeReactRepository!!.save(modelType).block()
@@ -80,7 +78,8 @@ class ModelTypeReactRepositoryTest {
val dbFindByModelName = modelTypeReactRepository!!.findByModelName(modelName).block()
Assert.assertNotNull("Failed to findByModelName ", dbFindByModelName)
- val dbFindByDefinitionType = modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block()
+ val dbFindByDefinitionType =
+ modelTypeReactRepository.findByDefinitionType(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE).collectList().block()
Assert.assertNotNull("Failed to findByDefinitionType ", dbFindByDefinitionType)
Assert.assertTrue("Failed to findByDefinitionType count", dbFindByDefinitionType!!.size > 0)
@@ -92,11 +91,13 @@ class ModelTypeReactRepositoryTest {
Assert.assertNotNull("Failed to findByModelNameIn ", dbFindByModelNameIn)
Assert.assertTrue("Failed to findByModelNameIn by count", dbFindByModelNameIn!!.size > 0)
- val dbFindByDefinitionTypeIn = modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block()
+ val dbFindByDefinitionTypeIn =
+ modelTypeReactRepository.findByDefinitionTypeIn(Arrays.asList(BluePrintConstants.MODEL_DEFINITION_TYPE_DATA_TYPE)).collectList().block()
Assert.assertNotNull("Failed to findByDefinitionTypeIn", dbFindByDefinitionTypeIn)
Assert.assertTrue("Failed to findByDefinitionTypeIn by count", dbFindByDefinitionTypeIn!!.size > 0)
- val dbFindByDerivedFromIn = modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block()
+ val dbFindByDerivedFromIn =
+ modelTypeReactRepository.findByDerivedFromIn(Arrays.asList(BluePrintConstants.MODEL_TYPE_DATATYPES_ROOT)).collectList().block()
Assert.assertNotNull("Failed to find findByDerivedFromIn", dbFindByDerivedFromIn)
Assert.assertTrue("Failed to find findByDerivedFromIn by count", dbFindByDerivedFromIn!!.size > 0)
}
@@ -106,5 +107,4 @@ class ModelTypeReactRepositoryTest {
fun test03Delete() {
modelTypeReactRepository!!.deleteByModelName(modelName).block()
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepositoryTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryReactRepositoryTest.kt
index 6351f6aa0..988fa4d73 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryRepositoryTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/repository/ResourceDictionaryReactRepositoryTest.kt
@@ -21,9 +21,6 @@ import org.junit.FixMethodOrder
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.MethodSorters
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertiesService
-import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintPropertyConfiguration
-import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.DesignerApiTestConfiguration
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.domain.ResourceDictionary
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@@ -36,8 +33,9 @@ import org.springframework.test.context.junit4.SpringRunner
import org.springframework.transaction.annotation.Transactional
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [DesignerApiTestConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class, BluePrintDBLibConfiguration::class])
+@ContextConfiguration(
+ classes = [DesignerApiTestConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
class ResourceDictionaryReactRepositoryTest {
@@ -51,8 +49,10 @@ class ResourceDictionaryReactRepositoryTest {
@Commit
fun test01Save() {
val resourceDefinition = JacksonUtils
- .readValueFromFile("./../../../../../components/model-catalog/resource-dictionary/starter-dictionary/sample-db-source.json",
- ResourceDefinition::class.java)
+ .readValueFromFile(
+ "./../../../../../components/model-catalog/resource-dictionary/starter-dictionary/sample-db-source.json",
+ ResourceDefinition::class.java
+ )
Assert.assertNotNull("Failed to get resourceDefinition from content", resourceDefinition)
resourceDefinition!!.name = sourceName
diff --git a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt
index 10bf887f6..c644aeedd 100644
--- a/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/designer-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/designer/api/utils/BluePrintEnhancerUtilsTest.kt
@@ -21,8 +21,12 @@ import org.junit.After
import org.junit.Before
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.designer.api.mock.MockFilePart
-import org.onap.ccsdk.cds.controllerblueprints.core.*
-import java.util.*
+import org.onap.ccsdk.cds.controllerblueprints.core.compress
+import org.onap.ccsdk.cds.controllerblueprints.core.deleteDir
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.reCreateDirs
+import java.util.UUID
import kotlin.test.assertTrue
class BluePrintEnhancerUtilsTest {
@@ -30,7 +34,7 @@ class BluePrintEnhancerUtilsTest {
private val blueprintDir = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
private val blueprintArchivePath: String = "./target/blueprints/archive"
private val blueprintEnrichmentPath: String = "./target/blueprints/enrichment"
- private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip")
+ private var zipBlueprintFileName = normalizedPathName(blueprintArchivePath, "test.zip")
@Before
fun setUp() {
@@ -62,4 +66,3 @@ class BluePrintEnhancerUtilsTest {
}
}
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/pom.xml b/ms/blueprintsprocessor/modules/inbounds/health-api-common/pom.xml
index 2bd6782a7..3b3fec4d1 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/pom.xml
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/pom.xml
@@ -27,7 +27,7 @@
<artifactId>health-api-common</artifactId>
<packaging>jar</packaging>
- <name>Blueprints Processor Health API common </name>
+ <name>Blueprints Processor Health API common</name>
<description>checking system check health endpoints</description>
<dependencies>
@@ -36,7 +36,6 @@
<artifactId>rest-lib</artifactId>
</dependency>
-
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/BasicAuthRestClientServiceConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/BasicAuthRestClientServiceConfiguration.kt
index 0c6099a1a..ead1f3b78 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/BasicAuthRestClientServiceConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/BasicAuthRestClientServiceConfiguration.kt
@@ -45,5 +45,4 @@ open class BasicAuthRestClientServiceConfiguration(private val securityConfigura
open fun getBasicAuthRestClientService(): BasicAuthRestClientService {
return BasicAuthRestClientService(getBasicAuthRestClientProperties())
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt
index c63952d80..f64cba88b 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/HealthCheckProperties.kt
@@ -26,16 +26,16 @@ import org.springframework.context.annotation.PropertySource
@PropertySource("classpath:application.properties")
open class HealthCheckProperties {
- @Value("\${blueprintprocessor.healthcheck.baseUrl}")
+ @Value("\${blueprintprocessor.healthcheck.baseUrl:}")
private val bluePrintProcessorBaseURL: String? = null
- @Value("#{'\${blueprintprocessor.healthcheck.mapping-service-name-with-service-link}'.split(']')}")
+ @Value("#{'\${blueprintprocessor.healthcheck.mapping-service-name-with-service-link:}'.split(']')}")
private val blueprintprocessorServiceMapping: List<String>? = null
- @Value("\${cdslistener.healthcheck.baseUrl}")
+ @Value("\${cdslistener.healthcheck.baseUrl:}")
private val cdsListenerBaseURL: String? = null
- @Value("#{'\${cdslistener.healthcheck.mapping-service-name-with-service-link}'.split(']')}")
+ @Value("#{'\${cdslistener.healthcheck.mapping-service-name-with-service-link:}'.split(']')}")
private val cdsListenerServiceMapping: List<String>? = null
open fun getBluePrintBaseURL(): String? {
@@ -54,7 +54,6 @@ open class HealthCheckProperties {
open fun getCDSListenerServiceInformation(): List<ServiceEndpoint> {
val serviceName = ServiceName.BLUEPRINT
return getListOfServiceEndPoints(cdsListenerServiceMapping, serviceName)
-
}
private fun getListOfServiceEndPoints(serviceMapping: List<String>?, serviceName: ServiceName): MutableList<ServiceEndpoint> {
@@ -67,7 +66,7 @@ open class HealthCheckProperties {
return serviceEndpoints
}
- private fun fillListOfService(serviceName: ServiceName , element: String, listOfCDSListenerServiceEndpoint: MutableList<ServiceEndpoint>) {
+ private fun fillListOfService(serviceName: ServiceName, element: String, listOfCDSListenerServiceEndpoint: MutableList<ServiceEndpoint>) {
val serviceEndpointInfo = element.split(",/")
val serviceEndpoint = getServiceEndpoint(serviceEndpointInfo)
if (serviceName.equals(ServiceName.CDSLISTENER))
@@ -77,16 +76,15 @@ open class HealthCheckProperties {
listOfCDSListenerServiceEndpoint.add(serviceEndpoint)
}
-
private fun getServiceEndpoint(serviceEndpointInfo: List<String>): ServiceEndpoint {
- return ServiceEndpoint(removeSpecialCharacter(serviceEndpointInfo.get(0))
- , removeSpecialCharacter(serviceEndpointInfo.get(1))
+ return ServiceEndpoint(
+ removeSpecialCharacter(serviceEndpointInfo.get(0)), removeSpecialCharacter(serviceEndpointInfo.get(1))
)
}
- private fun removeSpecialCharacter(value:String):String{
- return value.replaceFirst(",[","")
- .replace("[","")
- .replace("]","")
+ private fun removeSpecialCharacter(value: String): String {
+ return value.replaceFirst(",[", "")
+ .replace("[", "")
+ .replace("]", "")
}
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/SecurityEncryptionConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/SecurityEncryptionConfiguration.kt
index 94021207a..8b319fc43 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/SecurityEncryptionConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/configuration/SecurityEncryptionConfiguration.kt
@@ -16,17 +16,15 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration
-
import org.apache.commons.net.util.Base64
import org.springframework.stereotype.Component
-import org.springframework.stereotype.Service
import javax.crypto.Cipher
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
-
@Component
class SecurityEncryptionConfiguration {
+
private val key = "aesEncryptionKey"
private val initVector = "encryptionIntVec"
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ApplicationHealth.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ApplicationHealth.kt
index f66e8774c..f6ce829c1 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ApplicationHealth.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ApplicationHealth.kt
@@ -21,5 +21,3 @@ import org.springframework.boot.actuate.health.Status
data class ApplicationHealth(val status: Status?, val details: Map<String, Any>?) {
constructor() : this(null, HashMap())
}
-
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/HealthApiResponse.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/HealthApiResponse.kt
index 61d8120d4..285dc0878 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/HealthApiResponse.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/HealthApiResponse.kt
@@ -16,8 +16,7 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
-data class HealthApiResponse(val status: HealthCheckStatus, val checks: List<ServicesCheckResponse>
+data class HealthApiResponse(
+ val status: HealthCheckStatus,
+ val checks: List<ServicesCheckResponse>
)
-
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/Metrics.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/Metrics.kt
index d9f1c79d4..ceb92d1b4 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/Metrics.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/Metrics.kt
@@ -16,7 +16,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class Metrics(val names: ArrayList<Any>?) {
constructor() : this(ArrayList())
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/MetricsResponse.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/MetricsResponse.kt
index b3796c91a..f58a31e8c 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/MetricsResponse.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/MetricsResponse.kt
@@ -16,6 +16,4 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-data class MetricsResponse(val maps: HashMap<String, String>) {
-
-}
+data class MetricsResponse(val maps: HashMap<String, String>)
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceEndpoint.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceEndpoint.kt
index ce95a5c0c..badd772c4 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceEndpoint.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceEndpoint.kt
@@ -15,5 +15,4 @@
*/
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class ServiceEndpoint(val serviceName: String, var serviceLink: String)
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceName.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceName.kt
index 1a78a5d10..3e984b3b6 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceName.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServiceName.kt
@@ -17,5 +17,5 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
enum class ServiceName(s: String) {
- BLUEPRINT("Blue Print service"),CDSLISTENER("CDS Listener service")
+ BLUEPRINT("Blue Print service"), CDSLISTENER("CDS Listener service")
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServicesCheckResponse.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServicesCheckResponse.kt
index 391d7f38a..908007523 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServicesCheckResponse.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/ServicesCheckResponse.kt
@@ -16,7 +16,4 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
-
data class ServicesCheckResponse(val name: String, val status: HealthCheckStatus)
-
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/WebClientEnpointResponse.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/WebClientEnpointResponse.kt
index 03e864a9d..1e7e670b5 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/WebClientEnpointResponse.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/domain/WebClientEnpointResponse.kt
@@ -18,5 +18,4 @@ package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-data class WebClientEnpointResponse (val response:BlueprintWebClientService.WebClientResponse<String>?) {
-}
+data class WebClientEnpointResponse(val response: BlueprintWebClientService.WebClientResponse<String>?)
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/EndPointExecution.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/EndPointExecution.kt
index 72fa6c849..9f526251e 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/EndPointExecution.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/EndPointExecution.kt
@@ -16,7 +16,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service
-
import com.fasterxml.jackson.databind.ObjectMapper
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ApplicationHealth
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
@@ -35,8 +34,10 @@ import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class EndPointExecution(private val basicAuthRestClientService: BasicAuthRestClientService
- , private val restClientProperties: BasicAuthRestClientProperties) {
+open class EndPointExecution(
+ private val basicAuthRestClientService: BasicAuthRestClientService,
+ private val restClientProperties: BasicAuthRestClientProperties
+) {
private var logger = LoggerFactory.getLogger(EndPointExecution::class.java)
@@ -46,25 +47,21 @@ open class EndPointExecution(private val basicAuthRestClientService: BasicAuthRe
val result = basicAuthRestClientService.exchangeResource(HttpMethod.GET.name, "", "")
if (result.status == 200)
return WebClientEnpointResponse(result)
-
} catch (e: Exception) {
logger.error("service name ${serviceEndpoint.serviceName} is down ${e.message}")
}
- return WebClientEnpointResponse(BlueprintWebClientService.WebClientResponse(500,""))
+ return WebClientEnpointResponse(BlueprintWebClientService.WebClientResponse(500, ""))
}
private fun addClientPropertiesConfiguration(serviceEndpoint: ServiceEndpoint) {
restClientProperties.url = serviceEndpoint.serviceLink
}
-
open fun getHealthFromWebClientEnpointResponse(webClientEnpointResponse: WebClientEnpointResponse): ApplicationHealth? {
return mappingMetricsToDTO(webClientEnpointResponse?.response?.body.toString())
-
}
private fun mappingMetricsToDTO(body: String): ApplicationHealth {
return ObjectMapper().readValue(body, ApplicationHealth::class.java)
}
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt
index f793754e3..6d49ebe65 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/AbstractHealthCheck.kt
@@ -16,7 +16,11 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.*
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServicesCheckResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.WebClientEnpointResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
import org.slf4j.LoggerFactory
@@ -27,7 +31,7 @@ import org.slf4j.LoggerFactory
* @author Shaaban Ebrahim
* @version 1.0
*/
-abstract class AbstractHealthCheck (private val endPointExecution: EndPointExecution) {
+abstract class AbstractHealthCheck(private val endPointExecution: EndPointExecution) {
private var logger = LoggerFactory.getLogger(BluePrintProcessorHealthCheck::class.java)
@@ -45,10 +49,8 @@ abstract class AbstractHealthCheck (private val endPointExecution: EndPointExec
}
healthApiResponse = HealthApiResponse(systemStatus, listOfResponse)
return healthApiResponse
-
}
-
private fun retrieveServiceStatus(serviceEndpoint: ServiceEndpoint): HealthCheckStatus {
var serviceStatus: HealthCheckStatus = HealthCheckStatus.UP
try {
@@ -59,16 +61,13 @@ abstract class AbstractHealthCheck (private val endPointExecution: EndPointExec
} catch (e: Exception) {
logger.error("service name ${serviceEndpoint.serviceName} is down ${e.message}")
serviceStatus = HealthCheckStatus.DOWN
-
}
return serviceStatus
}
-
open fun retrieveEndpointExecutionStatus(): HealthApiResponse {
return retrieveSystemStatus(setupServiceEndpoint())
}
abstract fun setupServiceEndpoint(): List<ServiceEndpoint>
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt
index d661b32b5..dddad52e2 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/BluePrintProcessorHealthCheck.kt
@@ -28,9 +28,11 @@ import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class BluePrintProcessorHealthCheck(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties)
- : AbstractHealthCheck(endPointExecution) {
+open class BluePrintProcessorHealthCheck(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) :
+ AbstractHealthCheck(endPointExecution) {
override fun setupServiceEndpoint(): List<ServiceEndpoint> {
return healthCheckProperties.getBluePrintServiceInformation()
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/SDCListenerHealthCheck.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/SDCListenerHealthCheck.kt
index 0a7c5e092..aa0d4d5f2 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/SDCListenerHealthCheck.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/health/SDCListenerHealthCheck.kt
@@ -17,14 +17,8 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServicesCheckResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
-import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-import org.slf4j.LoggerFactory
-import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
@@ -34,13 +28,13 @@ import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class SDCListenerHealthCheck (private val endPointExecution: EndPointExecution
- ,private val healthCheckProperties: HealthCheckProperties)
- : AbstractHealthCheck(endPointExecution) {
+open class SDCListenerHealthCheck(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) :
+ AbstractHealthCheck(endPointExecution) {
override fun setupServiceEndpoint(): List<ServiceEndpoint> {
return healthCheckProperties.getCDSListenerServiceInformation()
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt
index c4a8d1235..e3ba72428 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckServiceTest.kt
@@ -16,25 +16,18 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi
+import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
-import org.mockito.ArgumentMatchers.any
-import org.mockito.ArgumentMatchers.eq
-import org.mockito.Mockito.anyString
-import org.mockito.Mockito.mock
-
-import java.util.Arrays
-import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
-import org.mockito.ArgumentMatchers
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito
+import org.mockito.Mockito.anyString
import org.mockito.junit.MockitoJUnitRunner
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthApiResponse
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.EndPointExecution
@@ -42,8 +35,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service.health.BluePrint
import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BasicAuthRestClientService
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
-import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService.WebClientResponse
-import org.springframework.http.HttpMethod
+import java.util.Arrays
@RunWith(MockitoJUnitRunner::class)
class HealthCheckServiceTest {
@@ -62,106 +54,113 @@ class HealthCheckServiceTest {
private var bluePrintProcessorHealthCheck: BluePrintProcessorHealthCheck? = null
-
@Before
fun setup() {
endPointExecution = Mockito.spy(endPointExecution!!)
- Mockito.`when`(healthCheckProperties!!.getBluePrintServiceInformation()).thenReturn(Arrays.asList(
+ Mockito.`when`(healthCheckProperties!!.getBluePrintServiceInformation()).thenReturn(
+ Arrays.asList(
ServiceEndpoint("Execution service ", "http://cds-blueprints-processor-http:8080/api/v1/execution-service/health-check"),
- ServiceEndpoint("Resources service", "http://cds-blueprints-processor-http:8080/api/v1/resources/health-check"), ServiceEndpoint("Template service", "http://cds-blueprints-processor-http:8080/api/v1/template/health-check")
- ))
+ ServiceEndpoint("Resources service", "http://cds-blueprints-processor-http:8080/api/v1/resources/health-check"),
+ ServiceEndpoint("Template service", "http://cds-blueprints-processor-http:8080/api/v1/template/health-check")
+ )
+ )
bluePrintProcessorHealthCheck = BluePrintProcessorHealthCheck(endPointExecution!!, healthCheckProperties)
}
- @Test
+ @Test
fun testSystemIsCompletelyDown() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenThrow(RuntimeException())
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenThrow(RuntimeException())
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
Assert.assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
@Test
fun testSystemIsUPAndRunning() {
- Mockito.`when`(basicAuthRestClientService!!
- .exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenReturn(BlueprintWebClientService.WebClientResponse(200, "Success"))
+ Mockito.`when`(
+ basicAuthRestClientService!!
+ .exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenReturn(BlueprintWebClientService.WebClientResponse(200, "Success"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.UP, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.UP, serviceEndpoint.status)
-
}
-
}
@Test
fun testServiceIsNotFound() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString())).thenReturn(BlueprintWebClientService.WebClientResponse(404, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ ).thenReturn(BlueprintWebClientService.WebClientResponse(404, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
-
@Test
fun testServiceInternalServerError() {
- Mockito.`when`(basicAuthRestClientService!!.exchangeResource(
- anyString(),
- anyString(),
- anyString()))
- .thenReturn(BlueprintWebClientService.WebClientResponse(500, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!.exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ )
+ .thenReturn(BlueprintWebClientService.WebClientResponse(500, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
-
}
@Test
fun testServiceIsRedirected() {
- Mockito.`when`(basicAuthRestClientService!!.
- exchangeResource(
- anyString(),
- anyString(),
- anyString()))
- .thenReturn(BlueprintWebClientService.WebClientResponse(300, "failure"))
+ Mockito.`when`(
+ basicAuthRestClientService!!
+ .exchangeResource(
+ anyString(),
+ anyString(),
+ anyString()
+ )
+ )
+ .thenReturn(BlueprintWebClientService.WebClientResponse(300, "failure"))
val healthApiResponse = bluePrintProcessorHealthCheck!!.retrieveEndpointExecutionStatus()
assertNotNull(healthApiResponse)
assertEquals(HealthCheckStatus.DOWN, healthApiResponse.status)
healthApiResponse.checks.forEach { serviceEndpoint ->
assertNotNull(serviceEndpoint)
assertEquals(HealthCheckStatus.DOWN, serviceEndpoint.status)
-
}
}
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/SecurityConfigurationTest.kt b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/SecurityConfigurationTest.kt
index e1f7abdb7..54becbadf 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/SecurityConfigurationTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api-common/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/SecurityConfigurationTest.kt
@@ -20,7 +20,6 @@ import org.junit.Assert
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.SecurityEncryptionConfiguration
-
class SecurityConfigurationTest {
@Test
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedHealth.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedHealth.kt
index 54c85a0fc..531a275fa 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedHealth.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedHealth.kt
@@ -35,18 +35,20 @@ import org.springframework.web.bind.annotation.RestController
*/
@RestController
@RequestMapping("/api/v1/combinedHealth")
-@Api(value = "/api/v1/combinedHealth",
- description = "gather all HealthCheckResponses for HealthChecks known to the runtime")
+@Api(
+ value = "/api/v1/combinedHealth",
+ description = "gather all HealthCheckResponses for HealthChecks known to the runtime"
+)
open class CombinedHealth(private val combinedHealthService: CombinedHealthService) {
- @RequestMapping(path = [""],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun getSystemHealthCheckResponse(): ResponseEntity<List<ApplicationHealth?>> {
return ResponseEntity.ok().body(combinedHealthService.getCombinedHealthCheck())
-
}
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt
index 785def524..d2f02028c 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/controller/CombinedMetrics.kt
@@ -35,18 +35,20 @@ import org.springframework.web.bind.annotation.RestController
*/
@RestController
@RequestMapping("/api/v1/combinedMetrics")
-@Api(value = "/api/v1/combinedMetrics",
- description = "gather all Metrics info from BluePrint and CDSListener")
+@Api(
+ value = "/api/v1/combinedMetrics",
+ description = "gather all Metrics info from BluePrint and CDSListener"
+)
open class CombinedMetrics(private val combinedMetricsService: CombinedMetricsService) {
- @RequestMapping(path = [""],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = " Metrics Check", hidden = true)
fun getMetricsHealthCheckResponse(): ResponseEntity<MetricsInfo?> {
return ResponseEntity.ok().body(combinedMetricsService.metricsInfo)
-
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt
index 786048ce4..f4c3e93bf 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedHealthService.kt
@@ -22,7 +22,6 @@ import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.WebClientEnpointR
import org.springframework.boot.actuate.health.Status
import org.springframework.stereotype.Service
-
/**
*Service for combined health (BluePrintProcessor and CDSListener)
*
@@ -30,13 +29,15 @@ import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class CombinedHealthService(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties) {
+open class CombinedHealthService(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties
+) {
private fun setupServiceEndpoint(): List<ServiceEndpoint> {
return listOf(
- ServiceEndpoint("BluePrintProcessor Health Check ", healthCheckProperties.getBluePrintBaseURL() + "actuator/health")
- , ServiceEndpoint("CDSListener Health Check", healthCheckProperties.getCDSListenerBaseURL() + "actuator/health")
+ ServiceEndpoint("BluePrintProcessor Health Check ", healthCheckProperties.getBluePrintBaseURL() + "actuator/health"),
+ ServiceEndpoint("CDSListener Health Check", healthCheckProperties.getCDSListenerBaseURL() + "actuator/health")
)
}
@@ -45,14 +46,18 @@ open class CombinedHealthService(private val endPointExecution: EndPointExecutio
for (serviceEndpoint in setupServiceEndpoint().parallelStream()) {
val result: WebClientEnpointResponse? = endPointExecution?.retrieveWebClientResponse(serviceEndpoint)
if (result?.response != null &&
- result.response!!.status?.equals(200)!!) {
+ result.response!!.status?.equals(200)!!
+ ) {
listOfResponse.add(endPointExecution?.getHealthFromWebClientEnpointResponse(result))
} else {
- listOfResponse.add(ApplicationHealth(Status.DOWN,
- hashMapOf(serviceEndpoint.serviceLink to serviceEndpoint.serviceLink)))
+ listOfResponse.add(
+ ApplicationHealth(
+ Status.DOWN,
+ hashMapOf(serviceEndpoint.serviceLink to serviceEndpoint.serviceLink)
+ )
+ )
}
}
return listOfResponse
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt
index a23c9925b..0a2e7ae24 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/service/CombinedMetricsService.kt
@@ -16,7 +16,12 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi.service
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.configuration.HealthCheckProperties
-import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.*
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ActuatorCheckResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.HealthCheckStatus
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.Metrics
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.MetricsInfo
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.MetricsResponse
+import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.domain.ServiceEndpoint
import org.onap.ccsdk.cds.blueprintsprocessor.healthapi.utils.ObjectMappingUtils
import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
import org.springframework.stereotype.Service
@@ -28,14 +33,16 @@ import org.springframework.stereotype.Service
* @version 1.0
*/
@Service
-open class CombinedMetricsService(private val endPointExecution: EndPointExecution
- , private val healthCheckProperties: HealthCheckProperties
- , private val objectMappingUtils: ObjectMappingUtils<Metrics>) {
+open class CombinedMetricsService(
+ private val endPointExecution: EndPointExecution,
+ private val healthCheckProperties: HealthCheckProperties,
+ private val objectMappingUtils: ObjectMappingUtils<Metrics>
+) {
private fun setupServiceEndpoint(): List<ServiceEndpoint> {
return listOf(
- ServiceEndpoint("BluePrintProcessor metrics", healthCheckProperties.getBluePrintBaseURL() + "/actuator/metrics")
- , ServiceEndpoint("CDS Listener metrics", healthCheckProperties.getCDSListenerBaseURL() + "/actuator/metrics")
+ ServiceEndpoint("BluePrintProcessor metrics", healthCheckProperties.getBluePrintBaseURL() + "/actuator/metrics"),
+ ServiceEndpoint("CDS Listener metrics", healthCheckProperties.getCDSListenerBaseURL() + "/actuator/metrics")
)
}
@@ -46,7 +53,8 @@ open class CombinedMetricsService(private val endPointExecution: EndPointExecuti
val webClientResponse = endPointExecution?.retrieveWebClientResponse(serviceEndpoint)
var actuatorsHealthResponse: ActuatorCheckResponse? = null
actuatorsHealthResponse = if (webClientResponse?.response != null &&
- webClientResponse.response!!.status?.equals(200)!!) {
+ webClientResponse.response!!.status?.equals(200)!!
+ ) {
var body = gettingCustomizedBody(serviceEndpoint, webClientResponse.response!!)
ActuatorCheckResponse(serviceEndpoint.serviceName, body)
} else {
@@ -57,7 +65,10 @@ open class CombinedMetricsService(private val endPointExecution: EndPointExecuti
return MetricsInfo(containerHealthChecks)
}
- private fun gettingCustomizedBody(serviceEndpoint: ServiceEndpoint?, webClientResponse: BlueprintWebClientService.WebClientResponse<String>): Any {
+ private fun gettingCustomizedBody(
+ serviceEndpoint: ServiceEndpoint?,
+ webClientResponse: BlueprintWebClientService.WebClientResponse<String>
+ ): Any {
var body: Any
val metrics: Metrics = objectMappingUtils.getObjectFromBody(webClientResponse.body, Metrics::class.java)
val mapOfMetricsInfo = HashMap<String, String>()
@@ -69,4 +80,3 @@ open class CombinedMetricsService(private val endPointExecution: EndPointExecuti
return body
}
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt b/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt
index b1d629da7..5a1999ec1 100644
--- a/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/health-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/healthapi/HealthCheckApplicationTests.kt
@@ -16,7 +16,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.healthapi
-
import org.junit.Test
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration
@@ -40,8 +39,10 @@ import org.springframework.test.web.reactive.server.WebTestClient
*/
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintRuntimeService::class, BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class, ComponentScriptExecutor::class])
+@ContextConfiguration(
+ classes = [BluePrintRuntimeService::class, BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class, ComponentScriptExecutor::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class HealthCheckApplicationTests {
@@ -52,17 +53,14 @@ class HealthCheckApplicationTests {
@Test
fun testHealthApiUp() {
webTestClient.get().uri("/api/v1/combinedHealth")
- .exchange()
- .expectStatus().is2xxSuccessful
-
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
@Test
fun testMetricsApiUp() {
webTestClient.get().uri("/api/v1/combinedMetrics")
- .exchange()
- .expectStatus().is2xxSuccessful
+ .exchange()
+ .expectStatus().is2xxSuccessful
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/pom.xml b/ms/blueprintsprocessor/modules/inbounds/pom.xml
index 6dc39a7ff..81fe3af4e 100644
--- a/ms/blueprintsprocessor/modules/inbounds/pom.xml
+++ b/ms/blueprintsprocessor/modules/inbounds/pom.xml
@@ -53,7 +53,6 @@
<artifactId>resource-resolution</artifactId>
</dependency>
-
<!-- Test Dependencies -->
<dependency>
<groupId>io.mockk</groupId>
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml
index 32324bf6d..8c468feed 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml
@@ -35,8 +35,8 @@
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
</dependencies>
</project>
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceController.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceController.kt
index 3a708a973..b49ca68ed 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceController.kt
@@ -27,31 +27,43 @@ import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/v1/resources")
-@Api(value = "/api/v1/resources",
- description = "Interaction with resolved resources.")
+@Api(
+ value = "/api/v1/resources",
+ description = "Interaction with resolved resources."
+)
open class ResourceController(private var resourceResolutionDBService: ResourceResolutionDBService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun resourceControllerHealthCheck(): JsonNode = runBlocking {
JacksonUtils.getJsonNode("Success")
}
- @RequestMapping(path = [""],
- method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Get all resolved resources using the resolution key. ",
+ @RequestMapping(
+ path = [""],
+ method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Get all resolved resources using the resolution key. ",
notes = "Retrieve all stored resolved resources using the blueprint name, blueprint version, " +
"artifact name and the resolution-key.",
response = ResourceResolution::class,
responseContainer = "List",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun getAllFromResolutionKeyOrFromResourceTypeAndId(
@@ -66,8 +78,9 @@ open class ResourceController(private var resourceResolutionDBService: ResourceR
@ApiParam(value = "Resource Type associated with the resolution.", required = false)
@RequestParam(value = "resourceType", required = false, defaultValue = "") resourceType: String,
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
- @RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String)
- : ResponseEntity<List<ResourceResolution>> = runBlocking {
+ @RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String
+ ):
+ ResponseEntity<List<ResourceResolution>> = runBlocking {
if ((resolutionKey.isNotEmpty() || artifactName.isNotEmpty()) && (resourceId.isNotEmpty() || resourceType.isNotEmpty())) {
throw ResolutionException("Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.")
@@ -76,36 +89,46 @@ open class ResourceController(private var resourceResolutionDBService: ResourceR
.body(resourceResolutionDBService.readWithResolutionKey(bpName, bpVersion, artifactName, resolutionKey))
} else if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
ResponseEntity.ok()
- .body(resourceResolutionDBService.readWithResourceIdAndResourceType(bpName,
- bpVersion,
- resourceId,
- resourceType))
+ .body(
+ resourceResolutionDBService.readWithResourceIdAndResourceType(
+ bpName,
+ bpVersion,
+ resourceId,
+ resourceType
+ )
+ )
} else {
throw ResolutionException("Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.")
}
}
- @RequestMapping(path = ["/resource"],
+ @RequestMapping(
+ path = ["/resource"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Fetch a resource value using resolution key.",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Fetch a resource value using resolution key.",
notes = "Retrieve a stored resource value using the blueprint metadata, artifact name, resolution-key along with the name of the resource value to retrieve.",
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun getOneFromResolutionKey(@ApiParam(value = "Name of the CBA.", required = true)
- @RequestParam(value = "bpName", required = true) bpName: String,
- @ApiParam(value = "Version of the CBA.", required = true)
- @RequestParam(value = "bpVersion", required = true) bpVersion: String,
- @ApiParam(value = "Artifact name for which to retrieve a resolved resource.", required = true)
- @RequestParam(value = "artifactName", required = true) artifactName: String,
- @ApiParam(value = "Resolution Key associated with the resolution.", required = true)
- @RequestParam(value = "resolutionKey", required = true) resolutionKey: String,
- @ApiParam(value = "Name of the resource to retrieve.", required = true)
- @RequestParam(value = "name", required = true) name: String)
- : ResponseEntity<ResourceResolution> = runBlocking {
+ fun getOneFromResolutionKey(
+ @ApiParam(value = "Name of the CBA.", required = true)
+ @RequestParam(value = "bpName", required = true) bpName: String,
+ @ApiParam(value = "Version of the CBA.", required = true)
+ @RequestParam(value = "bpVersion", required = true) bpVersion: String,
+ @ApiParam(value = "Artifact name for which to retrieve a resolved resource.", required = true)
+ @RequestParam(value = "artifactName", required = true) artifactName: String,
+ @ApiParam(value = "Resolution Key associated with the resolution.", required = true)
+ @RequestParam(value = "resolutionKey", required = true) resolutionKey: String,
+ @ApiParam(value = "Name of the resource to retrieve.", required = true)
+ @RequestParam(value = "name", required = true) name: String
+ ):
+ ResponseEntity<ResourceResolution> = runBlocking {
ResponseEntity.ok()
.body(resourceResolutionDBService.readValue(bpName, bpVersion, artifactName, resolutionKey, name))
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceExceptionHandler.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceExceptionHandler.kt
index 42ff8016c..5d5623d4f 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceExceptionHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceExceptionHandler.kt
@@ -23,16 +23,16 @@ import com.fasterxml.jackson.annotation.JsonTypeName
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
import org.slf4j.LoggerFactory
+import org.springframework.dao.EmptyResultDataAccessException
+import org.springframework.dao.IncorrectResultSizeDataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.orm.jpa.JpaObjectRetrievalFailureException
-import org.springframework.dao.EmptyResultDataAccessException
-import org.springframework.dao.IncorrectResultSizeDataAccessException
-import org.springframework.web.server.ServerWebInputException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
+import org.springframework.web.server.ServerWebInputException
import java.io.Serializable
-import java.util.*
+import java.util.Date
/**
* Handle exceptions in Resolution API and provide relevant HTTP status codes and messages
@@ -86,9 +86,11 @@ open class ResourceExceptionHandler {
fun returnError(e: Exception, errorCode: ErrorCode): ResponseEntity<ErrorMessage> {
log.error(e.message, e)
val errorMessage =
- ErrorMessage(errorCode.message(e.message!!),
+ ErrorMessage(
+ errorCode.message(e.message!!),
errorCode.value,
- debugMsg)
+ debugMsg
+ )
return ResponseEntity(errorMessage, HttpStatus.resolve(errorCode.httpCode)!!)
}
@@ -103,6 +105,7 @@ open class ResourceExceptionHandler {
@JsonTypeName("errorMessage")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
class ErrorMessage(var message: String?, var code: Int?, var debugMessage: String?) : Serializable {
+
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
var timestamp = Date()
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateController.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateController.kt
index 93253a554..5913bde1d 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateController.kt
@@ -27,7 +27,14 @@ import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.PathVariable
+import org.springframework.web.bind.annotation.PostMapping
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.RequestParam
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
/**
* Exposes Template Resolution API to store and retrieve rendered template results.
@@ -37,26 +44,34 @@ import org.springframework.web.bind.annotation.*
*/
@RestController
@RequestMapping("/api/v1/template")
-@Api(value = "/api/v1/template",
- description = "Interaction with resolved template.")
+@Api(
+ value = "/api/v1/template",
+ description = "Interaction with resolved template."
+)
open class TemplateController(private val templateResolutionService: TemplateResolutionService) {
- @RequestMapping(path = ["/health-check"],
+ @RequestMapping(
+ path = ["/health-check"],
method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun templateControllerHealthCheck(): JsonNode = runBlocking {
JacksonUtils.getJsonNode("Success")
}
- @RequestMapping(path = [""],
+ @RequestMapping(
+ path = [""],
method = [RequestMethod.GET],
- produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE])
- @ApiOperation(value = "Retrieve a resolved template.",
+ produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
+ )
+ @ApiOperation(
+ value = "Retrieve a resolved template.",
notes = "Retrieve a config template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name and resolution key. An extra 'format' parameter can be passed to tell what content-type" +
- " to expect in return")
+ " to expect in return"
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun get(
@@ -72,11 +87,14 @@ open class TemplateController(private val templateResolutionService: TemplateRes
@RequestParam(value = "resourceType", required = false, defaultValue = "") resourceType: String,
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
@RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String,
- @ApiParam(value = "Expected format of the template being retrieved.",
+ @ApiParam(
+ value = "Expected format of the template being retrieved.",
defaultValue = MediaType.TEXT_PLAIN_VALUE,
- required = true)
- @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String)
- : ResponseEntity<String> = runBlocking {
+ required = true
+ )
+ @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
+ ):
+ ResponseEntity<String> = runBlocking {
var result = ""
@@ -87,7 +105,8 @@ open class TemplateController(private val templateResolutionService: TemplateRes
bpName,
bpVersion,
artifactName,
- resolutionKey)
+ resolutionKey
+ )
} else if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
result =
templateResolutionService.findByResoureIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactName(
@@ -95,12 +114,12 @@ open class TemplateController(private val templateResolutionService: TemplateRes
bpVersion,
artifactName,
resourceId,
- resourceType)
+ resourceType
+ )
} else {
throw ResolutionException("Missing param. Either retrieve resolved template using artifact name and resolution-key OR using resource-id and resource-type.")
}
-
var expectedContentType = format
if (expectedContentType.indexOf('/') < 0) {
expectedContentType = "application/$expectedContentType"
@@ -110,13 +129,14 @@ open class TemplateController(private val templateResolutionService: TemplateRes
ResponseEntity.ok().contentType(expectedMediaType).body(result)
}
-
@PostMapping("/{bpName}/{bpVersion}/{artifactName}/{resolutionKey}", produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resolved template w/ resolution-key",
+ @ApiOperation(
+ value = "Store a resolved template w/ resolution-key",
notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name and resolution key.",
response = TemplateResolution::class,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResolutionKey(
@@ -129,7 +149,8 @@ open class TemplateController(private val templateResolutionService: TemplateRes
@ApiParam(value = "Resolution Key associated with the resolution.", required = true)
@PathVariable(value = "resolutionKey") resolutionKey: String,
@ApiParam(value = "Template to store.", required = true)
- @RequestBody result: String): ResponseEntity<TemplateResolution> = runBlocking {
+ @RequestBody result: String
+ ): ResponseEntity<TemplateResolution> = runBlocking {
val resultStored =
templateResolutionService.write(bpName, bpVersion, artifactName, result, resolutionKey = resolutionKey)
@@ -137,13 +158,17 @@ open class TemplateController(private val templateResolutionService: TemplateRes
ResponseEntity.ok().body(resultStored)
}
- @PostMapping("/{bpName}/{bpVersion}/{artifactName}/{resourceType}/{resourceId}",
- produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Store a resolved template w/ resourceId and resourceType",
+ @PostMapping(
+ "/{bpName}/{bpVersion}/{artifactName}/{resourceType}/{resourceId}",
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
+ @ApiOperation(
+ value = "Store a resolved template w/ resourceId and resourceType",
notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
"artifact name, resourceId and resourceType.",
response = TemplateResolution::class,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.APPLICATION_JSON_VALUE
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
fun postWithResourceIdAndResourceType(
@@ -158,7 +183,8 @@ open class TemplateController(private val templateResolutionService: TemplateRes
@ApiParam(value = "Resource Id associated with the resolution.", required = false)
@PathVariable(value = "resourceId", required = true) resourceId: String,
@ApiParam(value = "Template to store.", required = true)
- @RequestBody result: String): ResponseEntity<TemplateResolution> = runBlocking {
+ @RequestBody result: String
+ ): ResponseEntity<TemplateResolution> = runBlocking {
val resultStored =
templateResolutionService.write(bpName, bpVersion, artifactName, result, resourceId = resourceId, resourceType = resourceType)
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt
index 85ac7bddd..39ff32d75 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceControllerTest.kt
@@ -22,6 +22,7 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolution
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionDBService
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
@@ -35,13 +36,18 @@ import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.reactive.server.WebTestClient
-import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
-
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [ResourceController::class, ResourceResolutionDBService::class, SecurityProperties::class])
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
+@ContextConfiguration(
+ classes = [TestDatabaseConfiguration::class,
+ ResourceController::class, ResourceResolutionDBService::class, SecurityProperties::class]
+)
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.controllerblueprints.core.service",
+ "org.onap.ccsdk.cds.blueprintsprocessor.resource.api",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution"]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class ResourceControllerTest {
@@ -88,8 +94,10 @@ class ResourceControllerTest {
.consumeWith {
val json = String(it.responseBody!!)
val typeFactory = JacksonUtils.objectMapper.typeFactory
- val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(json,
- typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java))
+ val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(
+ json,
+ typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java)
+ )
Assert.assertEquals(2, list.size)
assertEqual(ra1, list[0])
assertEqual(ra1, list[0])
@@ -119,8 +127,10 @@ class ResourceControllerTest {
.consumeWith {
val json = String(it.responseBody!!)
val typeFactory = JacksonUtils.objectMapper.typeFactory
- val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(json,
- typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java))
+ val list: List<ResourceResolution> = JacksonUtils.objectMapper.readValue(
+ json,
+ typeFactory.constructCollectionType(List::class.java, ResourceResolution::class.java)
+ )
Assert.assertEquals(2, list.size)
assertEqual(ra1, list[0])
assertEqual(ra1, list[0])
@@ -128,7 +138,6 @@ class ResourceControllerTest {
}
}
-
@Test
fun getAllFromMissingParamTest() {
runBlocking {
@@ -140,8 +149,10 @@ class ResourceControllerTest {
.expectBody()
.consumeWith {
val r = JacksonUtils.objectMapper.readValue(it.responseBody, ErrorMessage::class.java)
- Assert.assertEquals("Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
- r.message)
+ Assert.assertEquals(
+ "Missing param. Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
+ r.message
+ )
}
}
}
@@ -157,8 +168,10 @@ class ResourceControllerTest {
.expectBody()
.consumeWith {
val r = JacksonUtils.objectMapper.readValue(it.responseBody, ErrorMessage::class.java)
- Assert.assertEquals("Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
- r.message)
+ Assert.assertEquals(
+ "Either retrieve resolved value using artifact name and resolution-key OR using resource-id and resource-type.",
+ r.message
+ )
}
}
}
@@ -195,15 +208,21 @@ class ResourceControllerTest {
}
}
- private suspend fun store(resourceAssignment: ResourceAssignment, resKey: String = "", resId: String = "",
- resType: String = "") {
- resourceResolutionDBService.write(blueprintName,
+ private suspend fun store(
+ resourceAssignment: ResourceAssignment,
+ resKey: String = "",
+ resId: String = "",
+ resType: String = ""
+ ) {
+ resourceResolutionDBService.write(
+ blueprintName,
blueprintVersion,
resKey,
resId,
resType,
templatePrefix,
- resourceAssignment)
+ resourceAssignment
+ )
}
private fun createRA(prefix: String): ResourceAssignment {
@@ -221,8 +240,10 @@ class ResourceControllerTest {
}
private fun assertEqual(resourceAssignment: ResourceAssignment, resourceResolution: ResourceResolution) {
- Assert.assertEquals(JacksonUtils.getValue(resourceAssignment.property?.value!!).toString(),
- resourceResolution.value)
+ Assert.assertEquals(
+ JacksonUtils.getValue(resourceAssignment.property?.value!!).toString(),
+ resourceResolution.value
+ )
Assert.assertEquals(resourceAssignment.status, resourceResolution.status)
Assert.assertEquals(resourceAssignment.dictionarySource, resourceResolution.dictionarySource)
Assert.assertEquals(resourceAssignment.dictionaryName, resourceResolution.dictionaryName)
@@ -230,6 +251,5 @@ class ResourceControllerTest {
Assert.assertEquals(resourceAssignment.name, resourceResolution.name)
Assert.assertEquals(blueprintVersion, resourceResolution.blueprintVersion)
Assert.assertEquals(blueprintName, resourceResolution.blueprintName)
-
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt
index c3a718e11..d91792d01 100644
--- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TemplateControllerTest.kt
@@ -37,8 +37,10 @@ import kotlin.test.AfterTest
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
+@ContextConfiguration(
+ classes = [TestDatabaseConfiguration::class, BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"])
@TestPropertySource(locations = ["classpath:application-test.properties"])
class TemplateControllerTest {
@@ -55,7 +57,7 @@ class TemplateControllerTest {
val payloadDummyTemplateData = "PAYLOAD DATA"
var requestArguments = "bpName=$blueprintName&bpVersion=$blueprintVersion" +
- "&artifactName=$templatePrefix&resolutionKey=$resolutionKey"
+ "&artifactName=$templatePrefix&resolutionKey=$resolutionKey"
@AfterTest
fun cleanDir() {
@@ -113,9 +115,9 @@ class TemplateControllerTest {
fun `get returns 400 error if missing arg`() {
runBlocking {
val arguments = "bpBADName=$blueprintName" +
- "&bpBADVersion=$blueprintVersion" +
- "&artifactName=$templatePrefix" +
- "&resolutionKey=$resolutionKey"
+ "&bpBADVersion=$blueprintVersion" +
+ "&artifactName=$templatePrefix" +
+ "&resolutionKey=$resolutionKey"
webTestClient.get().uri("/api/v1/template?$arguments")
.exchange()
@@ -129,8 +131,10 @@ class TemplateControllerTest {
webTestClient
.get()
- .uri("/api/v1/template?bpName=$blueprintName&bpVersion=$blueprintVersion" +
- "&artifactName=$templatePrefix&resolutionKey=notFound")
+ .uri(
+ "/api/v1/template?bpName=$blueprintName&bpVersion=$blueprintVersion" +
+ "&artifactName=$templatePrefix&resolutionKey=notFound"
+ )
.exchange()
.expectStatus().isNotFound
}
@@ -151,7 +155,7 @@ class TemplateControllerTest {
private fun get(expectedType: String, resKey: String) {
var requestArguments = "bpName=$blueprintName&bpVersion=$blueprintVersion" +
- "&artifactName=$templatePrefix&resolutionKey=$resKey"
+ "&artifactName=$templatePrefix&resolutionKey=$resKey"
if (expectedType.isNotEmpty()) {
requestArguments = "$requestArguments&format=$expectedType"
@@ -172,4 +176,4 @@ class TemplateControllerTest {
.expectBody().equals(payloadDummyTemplateData)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt
new file mode 100644
index 000000000..0ab3b5b21
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/TestDatabaseConfiguration.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.resource.api
+
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
+import org.springframework.transaction.PlatformTransactionManager
+import javax.sql.DataSource
+
+@Configuration
+@Import(BluePrintDBLibConfiguration::class)
+@EnableJpaRepositories(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
+)
+@EnableJpaAuditing
+open class TestDatabaseConfiguration(primaryDataSourceProperties: PrimaryDataSourceProperties) :
+ PrimaryDatabaseConfiguration(primaryDataSourceProperties) {
+
+ @Bean("primaryEntityManager")
+ open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ return primaryEntityManager(
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db"
+ )
+ }
+
+ @Bean("primaryDataSource")
+ override fun primaryDataSource(): DataSource {
+ return super.primaryDataSource()
+ }
+
+ @Bean("primaryTransactionManager")
+ override fun primaryTransactionManager(): PlatformTransactionManager {
+ return super.primaryTransactionManager()
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml
index 9f45c0f35..16995247f 100755
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml
@@ -34,12 +34,12 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-validation</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-validation</artifactId>
</dependency>
<!-- For Message libraries -->
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt
index b25acd148..305437923 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt
@@ -31,16 +31,20 @@ import java.util.concurrent.Phaser
import javax.annotation.PreDestroy
@Service
-open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration,
- private val executionServiceHandler: ExecutionServiceHandler)
- : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
+open class BluePrintProcessingGRPCHandler(
+ private val bluePrintCoreConfiguration: BluePrintCoreConfiguration,
+ private val executionServiceHandler: ExecutionServiceHandler
+) :
+ BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
+
private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java)
private val ph = Phaser(1)
@PreAuthorize("hasRole('USER')")
override fun process(
- responseObserver: StreamObserver<ExecutionServiceOutput>): StreamObserver<ExecutionServiceInput> {
+ responseObserver: StreamObserver<ExecutionServiceOutput>
+ ): StreamObserver<ExecutionServiceInput> {
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
@@ -51,17 +55,18 @@ open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration
}
} catch (e: Exception) {
onError(e)
- }
- finally {
+ } finally {
ph.arriveAndDeregister()
}
}
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
@@ -77,4 +82,4 @@ open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration
ph.arriveAndAwaitAdvance()
log.info("Done waiting in $name")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt
index a9dda7e0c..6293f48f4 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumer.kt
@@ -32,12 +32,15 @@ import org.springframework.stereotype.Service
import java.util.concurrent.Phaser
import javax.annotation.PreDestroy
-@ConditionalOnProperty(name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"],
- havingValue = "true")
+@ConditionalOnProperty(
+ name = ["blueprintsprocessor.messageconsumer.self-service-api.kafkaEnable"],
+ havingValue = "true"
+)
@Service
open class BluePrintProcessingKafkaConsumer(
- private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService,
- private val executionServiceHandler: ExecutionServiceHandler) {
+ private val bluePrintMessageLibPropertyService: BluePrintMessageLibPropertyService,
+ private val executionServiceHandler: ExecutionServiceHandler
+) {
val log = logger(BluePrintProcessingKafkaConsumer::class)
@@ -53,13 +56,15 @@ open class BluePrintProcessingKafkaConsumer(
@EventListener(ApplicationReadyEvent::class)
fun setupMessageListener() = runBlocking {
try {
- log.info("Setting up message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR)...")
+ log.info(
+ "Setting up message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR)..."
+ )
/** Get the Message Consumer Service **/
blueprintMessageConsumerService = try {
bluePrintMessageLibPropertyService
- .blueprintMessageConsumerService(CONSUMER_SELECTOR)
+ .blueprintMessageConsumerService(CONSUMER_SELECTOR)
} catch (e: Exception) {
throw BluePrintProcessorException("failed to create consumer service ${e.message}")
}
@@ -67,7 +72,7 @@ open class BluePrintProcessingKafkaConsumer(
/** Get the Message Producer Service **/
val blueprintMessageProducerService = try {
bluePrintMessageLibPropertyService
- .blueprintMessageProducerService(PRODUCER_SELECTOR)
+ .blueprintMessageProducerService(PRODUCER_SELECTOR)
} catch (e: Exception) {
throw BluePrintProcessorException("failed to create producer service ${e.message}")
}
@@ -83,34 +88,36 @@ open class BluePrintProcessingKafkaConsumer(
log.trace("Consumed Message : $message")
val executionServiceInput = message.jsonAsType<ExecutionServiceInput>()
val executionServiceOutput = executionServiceHandler.doProcess(executionServiceInput)
- //TODO("In future, Message publisher configuration vary with respect to request")
+ // TODO("In future, Message publisher configuration vary with respect to request")
/** Send the response message */
blueprintMessageProducerService.sendMessage(executionServiceOutput)
} catch (e: Exception) {
log.error("failed in processing the consumed message : $message", e)
- }
- finally {
+ } finally {
ph.arriveAndDeregister()
}
}
}
}
} catch (e: Exception) {
- log.error("failed to start message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR) ", e)
+ log.error(
+ "failed to start message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR) ", e
+ )
}
}
@PreDestroy
fun shutdownMessageListener() = runBlocking {
try {
- log.info("Shutting down message consumer($CONSUMER_SELECTOR) and " +
- "message producer($PRODUCER_SELECTOR)...")
+ log.info(
+ "Shutting down message consumer($CONSUMER_SELECTOR) and " +
+ "message producer($PRODUCER_SELECTOR)..."
+ )
blueprintMessageConsumerService.shutDown()
ph.arriveAndAwaitAdvance()
} catch (e: Exception) {
log.error("failed to shutdown message listener($CONSUMER_SELECTOR)", e)
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt
index 130e23ecc..02d3f2026 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt
@@ -32,16 +32,23 @@ import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.security.access.prepost.PreAuthorize
-import org.springframework.web.bind.annotation.*
+import org.springframework.web.bind.annotation.RequestBody
+import org.springframework.web.bind.annotation.RequestMapping
+import org.springframework.web.bind.annotation.RequestMethod
+import org.springframework.web.bind.annotation.ResponseBody
+import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
import java.util.concurrent.Phaser
import javax.annotation.PreDestroy
@RestController
@RequestMapping("/api/v1/execution-service")
-@Api(value = "/api/v1/execution-service",
- description = "Interaction with CBA.")
+@Api(
+ value = "/api/v1/execution-service",
+ description = "Interaction with CBA."
+)
open class ExecutionServiceController {
+
val log = logger(ExecutionServiceController::class)
private val ph = Phaser(1)
@@ -49,9 +56,11 @@ open class ExecutionServiceController {
@Autowired
lateinit var executionServiceHandler: ExecutionServiceHandler
- @RequestMapping(path = ["/health-check"],
- method = [RequestMethod.GET],
- produces = [MediaType.APPLICATION_JSON_VALUE])
+ @RequestMapping(
+ path = ["/health-check"],
+ method = [RequestMethod.GET],
+ produces = [MediaType.APPLICATION_JSON_VALUE]
+ )
@ResponseBody
@ApiOperation(value = "Health Check", hidden = true)
fun executionServiceControllerHealthCheck() = monoMdc(Dispatchers.IO) {
@@ -59,15 +68,19 @@ open class ExecutionServiceController {
}
@RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE])
- @ApiOperation(value = "Execute a CBA workflow (action)",
- notes = "Execute the appropriate CBA's action based on the ExecutionServiceInput object passed as input.",
- produces = MediaType.APPLICATION_JSON_VALUE,
- response = ExecutionServiceOutput::class)
+ @ApiOperation(
+ value = "Execute a CBA workflow (action)",
+ notes = "Execute the appropriate CBA's action based on the ExecutionServiceInput object passed as input.",
+ produces = MediaType.APPLICATION_JSON_VALUE,
+ response = ExecutionServiceOutput::class
+ )
@ResponseBody
@PreAuthorize("hasRole('USER')")
- fun process(@ApiParam(value = "ExecutionServiceInput payload.", required = true)
- @RequestBody executionServiceInput: ExecutionServiceInput)
- : Mono<ResponseEntity<ExecutionServiceOutput>> = monoMdc(Dispatchers.IO) {
+ fun process(
+ @ApiParam(value = "ExecutionServiceInput payload.", required = true)
+ @RequestBody executionServiceInput: ExecutionServiceInput
+ ):
+ Mono<ResponseEntity<ExecutionServiceOutput>> = monoMdc(Dispatchers.IO) {
if (executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC) {
throw IllegalStateException("Can't process async request through the REST endpoint. Use gRPC for async processing.")
@@ -87,4 +100,3 @@ open class ExecutionServiceController {
log.info("Done waiting in $name")
}
}
-
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt
index 356f0f7ee..9524e375e 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt
@@ -21,7 +21,11 @@ import io.grpc.stub.StreamObserver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toProto
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractServiceFunction
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
@@ -36,15 +40,19 @@ import org.springframework.stereotype.Service
import java.util.stream.Collectors
@Service
-class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
- private val blueprintsProcessorCatalogService: BluePrintCatalogService,
- private val bluePrintWorkflowExecutionService
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>) {
+class ExecutionServiceHandler(
+ private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
+ private val blueprintsProcessorCatalogService: BluePrintCatalogService,
+ private val bluePrintWorkflowExecutionService:
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput>
+) {
private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString())
- suspend fun process(executionServiceInput: ExecutionServiceInput,
- responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>) {
+ suspend fun process(
+ executionServiceInput: ExecutionServiceInput,
+ responseObserver: StreamObserver<org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>
+ ) {
when {
executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> {
GlobalScope.launch(Dispatchers.Default) {
@@ -59,9 +67,13 @@ class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintL
responseObserver.onNext(executionServiceOutput.toProto())
responseObserver.onCompleted()
}
- else -> responseObserver.onNext(response(executionServiceInput,
+ else -> responseObserver.onNext(
+ response(
+ executionServiceInput,
"Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.",
- true).toProto());
+ true
+ ).toProto()
+ )
}
}
@@ -81,8 +93,10 @@ class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintL
val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString())
- val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(blueprintRuntimeService,
- executionServiceInput, hashMapOf())
+ val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(
+ blueprintRuntimeService,
+ executionServiceInput, hashMapOf()
+ )
val errors = blueprintRuntimeService.getBluePrintError().errors
if (errors.isNotEmpty()) {
@@ -118,8 +132,11 @@ class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintL
status.message = BluePrintConstants.STATUS_FAILURE
}
- private fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "",
- failure: Boolean = false): ExecutionServiceOutput {
+ private fun response(
+ executionServiceInput: ExecutionServiceInput,
+ errorMessage: String = "",
+ failure: Boolean = false
+ ): ExecutionServiceOutput {
val executionServiceOutput = ExecutionServiceOutput()
executionServiceOutput.commonHeader = executionServiceInput.commonHeader
executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
@@ -138,5 +155,4 @@ class ExecutionServiceHandler(private val bluePrintLoadConfiguration: BluePrintL
return executionServiceOutput
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt
index 16fe36cfe..66cdbef3e 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt
@@ -22,7 +22,7 @@ import org.springframework.util.StringUtils
import java.io.File
import java.io.IOException
import java.nio.file.Path
-import java.util.*
+import java.util.UUID
const val INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE = 500
@@ -55,8 +55,8 @@ fun determineHttpStatusCode(statusCode: Int): HttpStatus {
try {
return HttpStatus.valueOf(statusCode)
} catch (exception: Exception) {
- //if statusCode cannot be converted to a proper HttpStatus, the resource still needs to assign a HTTP status
+ // if statusCode cannot be converted to a proper HttpStatus, the resource still needs to assign a HTTP status
// code to the response. In this case, a 500 Internal Server Error will be returned as default.
return HttpStatus.valueOf(INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt
index ab0d4256c..ff615536b 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt
@@ -22,6 +22,8 @@ import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefi
import org.springframework.stereotype.Service
@Service("bluePrintRuntimeValidatorService")
-open class BluePrintRuntimeValidatorService(bluePrintTypeValidatorService: BluePrintTypeValidatorService,
- resourceDefinitionValidator: ResourceDefinitionValidator)
- : BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator)
+open class BluePrintRuntimeValidatorService(
+ bluePrintTypeValidatorService: BluePrintTypeValidatorService,
+ resourceDefinitionValidator: ResourceDefinitionValidator
+) :
+ BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator)
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt
index 8bedc9628..af23e7902 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt
@@ -18,7 +18,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
-
import com.google.protobuf.util.JsonFormat
import io.grpc.stub.StreamObserver
import io.grpc.testing.GrpcServerRule
@@ -34,20 +33,20 @@ import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceIn
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration
-import org.springframework.context.annotation.ComponentScan
import org.springframework.test.annotation.DirtiesContext
+import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.BeforeTest
@RunWith(SpringRunner::class)
@DirtiesContext
-@EnableAutoConfiguration
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ContextConfiguration(
+ classes = [SelfServiceApiTestConfiguration::class, TestDatabaseConfiguration::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintProcessingGRPCHandlerTest {
+
private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java)
@get:Rule
@@ -67,8 +66,11 @@ class BluePrintProcessingGRPCHandlerTest {
requestObs = blockingStub.process(object : StreamObserver<ExecutionServiceOutput> {
override fun onNext(executionServiceOuput: ExecutionServiceOutput) {
log.debug("onNext {}", executionServiceOuput)
- if ("1234".equals(executionServiceOuput.commonHeader.requestId)) {
- Assert.assertEquals("Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", executionServiceOuput.status.errorMessage)
+ if ("1234" == executionServiceOuput.commonHeader.requestId) {
+ Assert.assertEquals(
+ "Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.",
+ executionServiceOuput.status.errorMessage
+ )
}
}
@@ -86,39 +88,38 @@ class BluePrintProcessingGRPCHandlerTest {
@Test
fun testSelfServiceGRPCHandler() {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("1234")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("1234")
+ .setSubRequestId("1234-56").build()
val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json")
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
val input = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input)
val commonHeader2 = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("2345")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("2345")
+ .setSubRequestId("1234-56").build()
val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build()
val input2 = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader2)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader2)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input2)
requestObs.onCompleted()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt
index 8971ebde2..b26781ad2 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingIntegrationTest.kt
@@ -36,7 +36,7 @@ class BluePrintProcessingIntegrationTest {
private val log = logger(BluePrintProcessingIntegrationTest::class)
/** This is Integration test sample, Do not enable this test case in server build, this is for local desktop testing*/
- //@Test
+ // @Test
fun integrationTestGrpcManagement() {
runBlocking {
val tokenAuthGrpcClientProperties = TokenAuthGrpcClientProperties().apply {
@@ -65,26 +65,26 @@ class BluePrintProcessingIntegrationTest {
})
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId("1234-$it")
- .setSubRequestId("1234-56").build()
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId("1234-$it")
+ .setSubRequestId("1234-56").build()
val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json")
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .build()
val input = ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
requestObs.onNext(input)
requestObs.onCompleted()
@@ -93,4 +93,4 @@ class BluePrintProcessingIntegrationTest {
channel.shutdownNow()
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt
index 01199c131..f71d1b444 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingKafkaConsumerTest.kt
@@ -34,8 +34,10 @@ import kotlin.test.Test
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintMessageLibConfiguration::class,
- BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class])
+@ContextConfiguration(
+ classes = [BluePrintMessageLibConfiguration::class,
+ BluePrintPropertyConfiguration::class, BluePrintPropertiesService::class]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class BluePrintProcessingKafkaConsumerTest {
@@ -45,15 +47,19 @@ class BluePrintProcessingKafkaConsumerTest {
@Test
fun testExecutionInputMessageConsumer() {
runBlocking {
- assertNotNull(bluePrintMessageLibPropertyService,
- "failed to initialise bluePrintMessageLibPropertyService")
+ assertNotNull(
+ bluePrintMessageLibPropertyService,
+ "failed to initialise bluePrintMessageLibPropertyService"
+ )
val executionServiceHandle = mockk<ExecutionServiceHandler>()
coEvery { executionServiceHandle.doProcess(any()) } returns mockk()
- val bluePrintProcessingKafkaConsumer = BluePrintProcessingKafkaConsumer(bluePrintMessageLibPropertyService,
- executionServiceHandle)
+ val bluePrintProcessingKafkaConsumer = BluePrintProcessingKafkaConsumer(
+ bluePrintMessageLibPropertyService,
+ executionServiceHandle
+ )
launch {
bluePrintProcessingKafkaConsumer.setupMessageListener()
@@ -62,5 +68,4 @@ class BluePrintProcessingKafkaConsumerTest {
bluePrintProcessingKafkaConsumer.shutdownMessageListener()
}
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt
index e1a498a6f..a6ebe9c3e 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceControllerTest.kt
@@ -36,17 +36,21 @@ import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.reactive.function.BodyInserters
import java.io.File
-import java.util.*
+import java.util.UUID
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.assertTrue
@RunWith(SpringRunner::class)
@WebFluxTest
-@ContextConfiguration(classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class,
- BluePrintCatalogService::class, SecurityProperties::class])
-@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
- "org.onap.ccsdk.cds.controllerblueprints"])
+@ContextConfiguration(
+ classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class,
+ BluePrintCatalogService::class, SecurityProperties::class]
+)
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor",
+ "org.onap.ccsdk.cds.controllerblueprints"]
+)
@TestPropertySource(locations = ["classpath:application-test.properties"])
class ExecutionServiceControllerTest {
@@ -71,15 +75,17 @@ class ExecutionServiceControllerTest {
blueprintsProcessorCatalogService.saveToDatabase(UUID.randomUUID().toString(), loadTestCbaFile())
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/default-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/default-input.json",
+ ExecutionServiceInput::class.java
+ )!!
webTestClient
- .post()
- .uri("/api/v1/execution-service/process")
- .body(BodyInserters.fromObject(executionServiceInput))
- .exchange()
- .expectStatus().isOk
+ .post()
+ .uri("/api/v1/execution-service/process")
+ .body(BodyInserters.fromObject(executionServiceInput))
+ .exchange()
+ .expectStatus().isOk
}
}
@@ -89,15 +95,17 @@ class ExecutionServiceControllerTest {
blueprintsProcessorCatalogService.saveToDatabase(UUID.randomUUID().toString(), loadTestCbaFile())
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/faulty-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/faulty-input.json",
+ ExecutionServiceInput::class.java
+ )!!
webTestClient
- .post()
- .uri("/api/v1/execution-service/process")
- .body(BodyInserters.fromObject(executionServiceInput))
- .exchange()
- .expectStatus().is5xxServerError
+ .post()
+ .uri("/api/v1/execution-service/process")
+ .body(BodyInserters.fromObject(executionServiceInput))
+ .exchange()
+ .expectStatus().is5xxServerError
}
}
@@ -106,4 +114,4 @@ class ExecutionServiceControllerTest {
assertTrue(testCbaFile.exists(), "couldn't get file ${testCbaFile.absolutePath}")
return testCbaFile
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt
index 293da0da6..5a44403e1 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt
@@ -73,12 +73,12 @@ class ExecutionServiceHandlerTest {
@Service("mock-service-action")
class MockServiceAction : AbstractServiceFunction() {
+
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
val responsePayload = """{"answer" : "correct"}""".jsonAsJsonType()
setResponsePayloadForAction(responsePayload)
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
-
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/SelfServiceApiTestConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/SelfServiceApiTestConfiguration.kt
new file mode 100644
index 000000000..98b882934
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/SelfServiceApiTestConfiguration.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration
+import org.springframework.context.annotation.ComponentScan
+import org.springframework.context.annotation.Configuration
+
+@Configuration
+@ComponentScan(
+ basePackages = ["org.onap.ccsdk.cds.controllerblueprints",
+ "org.onap.ccsdk.cds.blueprintsprocessor"]
+)
+@EnableAutoConfiguration
+open class SelfServiceApiTestConfiguration
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt
new file mode 100644
index 000000000..94da0f574
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/TestDatabaseConfiguration.kt
@@ -0,0 +1,60 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api
+
+import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration
+import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties
+import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDatabaseConfiguration
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Import
+import org.springframework.data.jpa.repository.config.EnableJpaAuditing
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
+import org.springframework.transaction.PlatformTransactionManager
+import javax.sql.DataSource
+
+@Configuration
+@Import(BluePrintDBLibConfiguration::class)
+@EnableJpaRepositories(
+ basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution"],
+ entityManagerFactoryRef = "primaryEntityManager",
+ transactionManagerRef = "primaryTransactionManager"
+)
+@EnableJpaAuditing
+open class TestDatabaseConfiguration(primaryDataSourceProperties: PrimaryDataSourceProperties) :
+ PrimaryDatabaseConfiguration(primaryDataSourceProperties) {
+
+ @Bean("primaryEntityManager")
+ open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean {
+ return primaryEntityManager(
+ "org.onap.ccsdk.cds.blueprintsprocessor.db.primary",
+ "org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution"
+ )
+ }
+
+ @Bean("primaryDataSource")
+ override fun primaryDataSource(): DataSource {
+ return super.primaryDataSource()
+ }
+
+ @Bean("primaryTransactionManager")
+ override fun primaryTransactionManager(): PlatformTransactionManager {
+ return super.primaryTransactionManager()
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt
index 27130a7bc..9f5cc6097 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt
@@ -41,8 +41,10 @@ class MockComponentFunction : AbstractComponentFunction() {
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
log.info("Processing component : $operationInputs")
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- "assignment-params", "params".asJsonPrimitive())
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ "assignment-params", "params".asJsonPrimitive()
+ )
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
@@ -51,13 +53,14 @@ class MockComponentFunction : AbstractComponentFunction() {
}
open class MockResourceSource {
- @Bean(name = [
- "rr-processor-source-input",
- "rr-processor-source-default",
- "rr-processor-source-db",
- "rr-processor-source-rest"])
+ @Bean(
+ name = [
+ "rr-processor-source-input",
+ "rr-processor-source-default",
+ "rr-processor-source-db",
+ "rr-processor-source-rest"]
+ )
open fun sourceInstance(): ResourceAssignmentProcessor {
return mockk<ResourceAssignmentProcessor>()
}
-
}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/UtilsTest.kt
index 07d8ca4e1..db2791101 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/UtilsTest.kt
@@ -23,5 +23,4 @@ class UtilsTest {
val nonExistentHttpStatusCode = determineHttpStatusCode(999999)
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, nonExistentHttpStatusCode)
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt
index 08da9dc28..75d9f487a 100644
--- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt
@@ -26,8 +26,10 @@ import org.springframework.test.context.junit4.SpringRunner
import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [BluePrintRuntimeValidatorService::class,
- BluePrintValidationConfiguration::class, MockResourceSource::class])
+@ContextConfiguration(
+ classes = [BluePrintRuntimeValidatorService::class,
+ BluePrintValidationConfiguration::class, MockResourceSource::class]
+)
class BluePrintRuntimeValidatorServiceTest {
@Autowired
@@ -35,10 +37,10 @@ class BluePrintRuntimeValidatorServiceTest {
@Test
fun testBlueprintRuntimeValidation() {
- val blueprintBasePath = "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ val blueprintBasePath =
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
assertNotNull(bluePrintRuntimeValidatorService, " failed to initilize bluePrintRuntimeValidatorService")
bluePrintRuntimeValidatorService.validateBluePrints(blueprintBasePath)
-
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/pom.xml b/ms/blueprintsprocessor/modules/pom.xml
index 87dfb5652..821465aa2 100644
--- a/ms/blueprintsprocessor/modules/pom.xml
+++ b/ms/blueprintsprocessor/modules/pom.xml
@@ -33,6 +33,7 @@
<description>Blueprints Processor Modules</description>
<modules>
+ <module>blueprints</module>
<module>commons</module>
<module>outbounds</module>
<module>services</module>
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml
index f3044c8bb..6ca0bbc04 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml
+++ b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml
@@ -36,8 +36,8 @@
<artifactId>jython-standalone</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
@@ -56,8 +56,8 @@
<artifactId>grpc-lib</artifactId>
</dependency>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>resource-dict</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>resource-dict</artifactId>
</dependency>
<dependency>
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt
index bee919249..e2a594b08 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt
@@ -17,7 +17,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
-
import com.fasterxml.jackson.databind.JsonNode
import kotlinx.coroutines.withTimeout
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
@@ -25,8 +24,15 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutp
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.getAsString
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonPathParse
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedFile
+import org.onap.ccsdk.cds.controllerblueprints.core.readNBLines
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintVelocityTemplateService
import org.slf4j.LoggerFactory
@@ -36,19 +42,20 @@ import org.slf4j.LoggerFactory
* @author Brinda Santh
*/
abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServiceInput, ExecutionServiceOutput> {
+
@Transient
private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java)
lateinit var executionServiceInput: ExecutionServiceInput
var executionServiceOutput = ExecutionServiceOutput()
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
+ lateinit var implementation: Implementation
lateinit var processId: String
lateinit var workflowName: String
lateinit var stepName: String
lateinit var interfaceName: String
lateinit var operationName: String
lateinit var nodeTemplateName: String
- var timeout: Int = 180
var operationInputs: MutableMap<String, JsonNode> = hashMapOf()
override fun getName(): String {
@@ -56,7 +63,7 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
}
override suspend fun prepareRequestNB(executionRequest: ExecutionServiceInput): ExecutionServiceInput {
- checkNotNull(bluePrintRuntimeService) { "failed to prepare blueprint runtime" }
+ check(this::bluePrintRuntimeService.isInitialized) { "failed to prepare blueprint runtime" }
checkNotNull(executionRequest.stepData) { "failed to get step info" }
// Get the Step Name and Step Inputs
@@ -84,14 +91,17 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
operationName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_OPERATION)
check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" }
+ /** Get the Implementation Details */
+ implementation = bluePrintRuntimeService.bluePrintContext()
+ .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
+ ?: Implementation()
+ check(this::implementation.isInitialized) { "failed to prepare implementation" }
+
val operationResolvedProperties = bluePrintRuntimeService
- .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
+ .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName)
this.operationInputs.putAll(operationResolvedProperties)
- val timeout = this.operationInputs.getOptionalAsInt(BluePrintConstants.PROPERTY_CURRENT_TIMEOUT)
- timeout?.let { this.timeout = timeout }
-
return executionRequest
}
@@ -99,11 +109,11 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
log.info("Preparing Response...")
executionServiceOutput.commonHeader = executionServiceInput.commonHeader
executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers
- var status = Status()
+ val status = Status()
try {
// Resolve the Output Expression
val stepOutputs = bluePrintRuntimeService
- .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
+ .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName)
val stepOutputData = StepData().apply {
name = stepName
@@ -123,7 +133,7 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
override suspend fun applyNB(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
try {
prepareRequestNB(executionServiceInput)
- withTimeout((timeout * 1000).toLong()) {
+ withTimeout((implementation.timeout * 1000).toLong()) {
processNB(executionServiceInput)
}
} catch (runtimeException: RuntimeException) {
@@ -135,7 +145,7 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
fun getOperationInput(key: String): JsonNode {
return operationInputs[key]
- ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
+ ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.")
}
fun getOptionalOperationInput(key: String): JsonNode? {
@@ -184,9 +194,9 @@ abstract class AbstractComponentFunction : BlueprintFunctionNode<ExecutionServic
}
suspend fun readLinesFromArtifact(artifactName: String): List<String> {
- val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
+ val artifactDefinition =
+ bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
val file = normalizedFile(bluePrintRuntimeService.bluePrintContext().rootPath, artifactDefinition.file)
return file.readNBLines()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt
index f17085ef1..041588616 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt
@@ -45,7 +45,7 @@ abstract class AbstractScriptComponentFunction : AbstractComponentFunction() {
@Deprecated("Dependencies will be resolved dynamically")
open fun <T> functionDependencyInstanceAsType(name: String): T {
return functionDependencyInstances[name] as? T
- ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
+ ?: throw BluePrintProcessorException("couldn't get script property instance ($name)")
}
fun checkDynamicProperties(key: String): Boolean {
@@ -125,4 +125,4 @@ abstract class AbstractScriptComponentFunction : AbstractComponentFunction() {
override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
throw BluePrintException("Not Implemented, child class will implement this")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt
index 67ab9c4de..e573afd7a 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractServiceFunction.kt
@@ -109,4 +109,4 @@ abstract class AbstractServiceFunction : BlueprintFunctionNode<ExecutionServiceI
}
return executionServiceInput.payload.jsonPathParse(".$requestExpression")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt
index 062d370bc..4c7d5d0ec 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt
@@ -28,21 +28,29 @@ import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
@Service
-class ComponentFunctionScriptingService(private val applicationContext: ApplicationContext,
- private val blueprintJythonService: BlueprintJythonService) {
+class ComponentFunctionScriptingService(
+ private val applicationContext: ApplicationContext,
+ private val blueprintJythonService: BlueprintJythonService
+) {
private val log = LoggerFactory.getLogger(ComponentFunctionScriptingService::class.java)
- suspend fun <T : AbstractScriptComponentFunction> scriptInstance(componentFunction: AbstractComponentFunction,
- scriptType: String,
- scriptClassReference: String,
- instanceDependencies: List<String>): T {
+ suspend fun <T : AbstractScriptComponentFunction> scriptInstance(
+ componentFunction: AbstractComponentFunction,
+ scriptType: String,
+ scriptClassReference: String,
+ instanceDependencies: List<String>
+ ): T {
- log.info("creating component function of script type($scriptType), reference name($scriptClassReference) and " +
- "instanceDependencies($instanceDependencies)")
+ log.info(
+ "creating component function of script type($scriptType), reference name($scriptClassReference) and " +
+ "instanceDependencies($instanceDependencies)"
+ )
- val scriptComponent: T = scriptInstance(componentFunction.bluePrintRuntimeService.bluePrintContext(),
- scriptType, scriptClassReference)
+ val scriptComponent: T = scriptInstance(
+ componentFunction.bluePrintRuntimeService.bluePrintContext(),
+ scriptType, scriptClassReference
+ )
checkNotNull(scriptComponent) { "failed to initialize script component" }
@@ -60,14 +68,16 @@ class ComponentFunctionScriptingService(private val applicationContext: Applicat
// Populate Instance Properties
instanceDependencies.forEach { instanceDependency ->
scriptComponent.functionDependencyInstances[instanceDependency] = applicationContext
- .getBean(instanceDependency)
+ .getBean(instanceDependency)
}
return scriptComponent
}
-
- suspend fun <T : BlueprintFunctionNode<*, *>> scriptInstance(bluePrintContext: BluePrintContext, scriptType: String,
- scriptClassReference: String): T {
+ suspend fun <T : BlueprintFunctionNode<*, *>> scriptInstance(
+ bluePrintContext: BluePrintContext,
+ scriptType: String,
+ scriptClassReference: String
+ ): T {
var scriptComponent: T? = null
when (scriptType) {
@@ -77,8 +87,10 @@ class ComponentFunctionScriptingService(private val applicationContext: Applicat
}
BluePrintConstants.SCRIPT_KOTLIN -> {
val bluePrintScriptsService: BluePrintScriptsService = BluePrintScriptsServiceImpl()
- scriptComponent = bluePrintScriptsService.scriptInstance<T>(bluePrintContext.rootPath,
- bluePrintContext.name(), bluePrintContext.version(), scriptClassReference, false)
+ scriptComponent = bluePrintScriptsService.scriptInstance<T>(
+ bluePrintContext.rootPath,
+ bluePrintContext.name(), bluePrintContext.version(), scriptClassReference, false
+ )
}
BluePrintConstants.SCRIPT_JYTHON -> {
scriptComponent = blueprintJythonService.jythonComponentInstance(bluePrintContext, scriptClassReference) as T
@@ -89,5 +101,4 @@ class ComponentFunctionScriptingService(private val applicationContext: Applicat
}
return scriptComponent
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt
new file mode 100644
index 000000000..6003cceab
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutor.kt
@@ -0,0 +1,106 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
+
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.asJsonType
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createActionIdentifiersProto
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createCommonHeaderProto
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createExecutionServiceInputProto
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.springframework.beans.factory.config.ConfigurableBeanFactory
+import org.springframework.context.annotation.Scope
+import org.springframework.stereotype.Component
+import java.util.UUID
+
+/**
+ * This is generic Remote Script Component Executor function
+ * @author Brinda Santh
+ */
+@Component("component-remote-script-executor")
+@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+open class ComponentRemoteScriptExecutor(
+ private var streamingRemoteExecutionService: StreamingRemoteExecutionService<
+ org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput,
+ org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>
+) : AbstractComponentFunction() {
+
+ companion object {
+ const val INPUT_SELECTOR = "selector"
+ const val INPUT_BLUEPRINT_NAME = "blueprint-name"
+ const val INPUT_BLUEPRINT_VERSION = "blueprint-version"
+ const val INPUT_BLUEPRINT_ACTION = "blueprint-action"
+ const val INPUT_TIMEOUT = "timeout"
+ const val INPUT_REQUEST_DATA = "request-data"
+
+ const val ATTRIBUTE_RESPONSE_DATA = "response-data"
+ const val ATTRIBUTE_STATUS = "status"
+
+ const val OUTPUT_STATUS = "status"
+ }
+
+ override suspend fun processNB(executionRequest: ExecutionServiceInput) {
+ val selector = getOperationInput(INPUT_SELECTOR)
+ val blueprintName = getOperationInput(INPUT_BLUEPRINT_NAME).asText()
+ val blueprintVersion = getOperationInput(INPUT_BLUEPRINT_VERSION).asText()
+ val blueprintAction = getOperationInput(INPUT_BLUEPRINT_ACTION).asText()
+ val requestData = getOperationInput(INPUT_REQUEST_DATA)
+ val timeout = getOperationInput(INPUT_TIMEOUT).asLong()
+
+ val requestPayload = PayloadUtils.prepareRequestPayloadStr(blueprintAction, requestData)
+
+ val txId = UUID.randomUUID().toString()
+ val commonHeader = createCommonHeaderProto(
+ executionRequest.commonHeader.subRequestId,
+ txId, BluePrintConstants.APP_NAME
+ )
+ val actionIdentifier = createActionIdentifiersProto(blueprintName, blueprintVersion, blueprintAction)
+
+ val executionServiceInputProto =
+ createExecutionServiceInputProto(commonHeader, actionIdentifier, requestPayload)
+
+ /** Invoke remote implementation using GRPC */
+ val executionServiceOutputProto =
+ streamingRemoteExecutionService.sendNonInteractive(selector, txId, executionServiceInputProto, timeout)
+
+ /** Set the response data */
+ if (executionServiceOutputProto.payload != null) {
+ val outputData = PayloadUtils.getResponseDataFromPayload(
+ blueprintAction,
+ executionServiceOutputProto.payload.asJsonType()
+ )
+ setAttribute(ATTRIBUTE_RESPONSE_DATA, outputData)
+ }
+
+ /** set node template attribute */
+ val statusMessage = executionServiceOutputProto.status.message
+ if (statusMessage == BluePrintConstants.STATUS_SUCCESS) {
+ setAttribute(ATTRIBUTE_STATUS, BluePrintConstants.STATUS_SUCCESS.asJsonPrimitive())
+ } else {
+ val errorMessage = executionServiceOutputProto.status.errorMessage ?: "failed in remote execution"
+ throw BluePrintProcessorException(errorMessage)
+ }
+ }
+
+ override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
+ bluePrintRuntimeService.getBluePrintError()
+ .addError("Failed in ComponentCliExecutor : ${runtimeException.message}")
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt
new file mode 100644
index 000000000..0210e88ea
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorDSL.kt
@@ -0,0 +1,148 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
+
+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.asJsonType
+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.dsl.AbstractNodeTemplateOperationImplBuilder
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.PropertiesAssignmentBuilder
+import org.onap.ccsdk.cds.controllerblueprints.core.dsl.nodeType
+
+/** Component Extensions **/
+
+fun BluePrintTypes.nodeTypeComponentRemoteScriptExecutor(): NodeType {
+ return nodeType(
+ id = "component-remote-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ description = "Generic Remote Script Component Executor"
+ ) {
+ /** Attribute definitions */
+ attribute(
+ ComponentRemoteScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false,
+ "Remote executed response data."
+ )
+ attribute(
+ ComponentRemoteScriptExecutor.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true,
+ "Remote execution status."
+ )
+
+ /** Operation definitions */
+ operation("ComponentRemoteScriptExecutor", "ComponentRemoteScriptExecutor Operation") {
+ inputs {
+ property(
+ ComponentRemoteScriptExecutor.INPUT_SELECTOR, BluePrintConstants.DATA_TYPE_JSON,
+ true, "Remote GRPC selector or DSL reference or GRPC Json config."
+ )
+ property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Blueprint name."
+ )
+ property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_VERSION, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Blueprint version."
+ )
+ property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_ACTION, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Blueprint action name."
+ )
+ property(
+ ComponentRemoteScriptExecutor.INPUT_TIMEOUT, BluePrintConstants.DATA_TYPE_INTEGER,
+ true, "Remote execution timeout in sec."
+ ) {
+ defaultValue(180)
+ }
+ property(
+ ComponentRemoteScriptExecutor.INPUT_REQUEST_DATA, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Dynamic Json Content or DSL Json reference."
+ )
+ }
+ outputs {
+ property(
+ ComponentRemoteScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Status of the Component Execution ( success or failure )"
+ )
+ }
+ }
+ }
+}
+
+/** Component Builder */
+fun BluePrintTypes.nodeTemplateComponentRemoteScriptExecutor(
+ id: String,
+ description: String,
+ block: ComponentRemoteScriptExecutorNodeTemplateBuilder.() -> Unit
+):
+ NodeTemplate {
+ return ComponentRemoteScriptExecutorNodeTemplateBuilder(id, description).apply(block).build()
+}
+
+class ComponentRemoteScriptExecutorNodeTemplateBuilder(id: String, description: String) :
+ AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
+ ComponentRemoteScriptExecutorNodeTemplateBuilder.InputsBuilder,
+ ComponentRemoteScriptExecutorNodeTemplateBuilder.OutputsBuilder>(
+ id, "component-remote-script-executor",
+ "ComponentRemoteScriptExecutor",
+ description
+ ) {
+
+ class InputsBuilder : PropertiesAssignmentBuilder() {
+
+ fun selector(selector: String) = selector(selector.asJsonPrimitive())
+
+ fun selector(selector: JsonNode) = property(ComponentRemoteScriptExecutor.INPUT_SELECTOR, selector)
+
+ fun blueprintName(blueprintName: String) = property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME,
+ blueprintName.asJsonPrimitive()
+ )
+
+ fun blueprintVersion(blueprintVersion: String) = property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_VERSION,
+ blueprintVersion.asJsonPrimitive()
+ )
+
+ fun blueprintAction(blueprintAction: String) = property(
+ ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_ACTION,
+ blueprintAction.asJsonPrimitive()
+ )
+
+ fun timeout(timeout: Int) = property(
+ ComponentRemoteScriptExecutor.INPUT_TIMEOUT,
+ timeout.asJsonPrimitive()
+ )
+
+ fun requestData(requestData: String) = requestData(requestData.asJsonType())
+
+ fun requestData(requestData: JsonNode) {
+ property(ComponentRemoteScriptExecutor.INPUT_REQUEST_DATA, requestData)
+ }
+ }
+
+ class OutputsBuilder : PropertiesAssignmentBuilder() {
+
+ fun status(status: String) = status(status.asJsonPrimitive())
+
+ fun status(status: JsonNode) {
+ property(ComponentRemoteScriptExecutor.OUTPUT_STATUS, status)
+ }
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutor.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutor.kt
index c66c3e913..09eee6717 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutor.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutor.kt
@@ -28,8 +28,8 @@ import org.springframework.stereotype.Component
*/
@Component("component-script-executor")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ComponentScriptExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService)
- : AbstractComponentFunction() {
+open class ComponentScriptExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) :
+ AbstractComponentFunction() {
companion object {
const val INPUT_SCRIPT_TYPE = "script-type"
@@ -53,8 +53,10 @@ open class ComponentScriptExecutor(private var componentFunctionScriptingService
val scriptDependencies: MutableList<String> = arrayListOf()
populateScriptDependencies(scriptDependencies)
- scriptComponentFunction = componentFunctionScriptingService.scriptInstance(this, scriptType,
- scriptClassReference, scriptDependencies)
+ scriptComponentFunction = componentFunctionScriptingService.scriptInstance(
+ this, scriptType,
+ scriptClassReference, scriptDependencies
+ )
// Handles both script processing and error handling
scriptComponentFunction.executeScript(executionServiceInput)
@@ -62,11 +64,10 @@ open class ComponentScriptExecutor(private var componentFunctionScriptingService
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
bluePrintRuntimeService.getBluePrintError()
- .addError("Failed in ComponentCliExecutor : ${runtimeException.message}")
-
+ .addError("Failed in ComponentCliExecutor : ${runtimeException.message}")
}
open fun populateScriptDependencies(scriptDependencies: MutableList<String>) {
/** Place holder for Child to add extra dependencies */
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt
index 89338b781..d4ca0f487 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentScriptExecutorDSL.kt
@@ -31,52 +31,72 @@ import kotlin.reflect.KClass
/** Component Extensions **/
fun BluePrintTypes.nodeTypeComponentScriptExecutor(): NodeType {
- return nodeType(id = "component-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
- derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
- description = "Generic Script Component Executor") {
+ return nodeType(
+ id = "component-script-executor", version = BluePrintConstants.DEFAULT_VERSION_NUMBER,
+ derivedFrom = BluePrintConstants.MODEL_TYPE_NODE_COMPONENT,
+ description = "Generic Script Component Executor"
+ ) {
attribute(ComponentScriptExecutor.ATTRIBUTE_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON, false)
attribute(ComponentScriptExecutor.ATTRIBUTE_STATUS, BluePrintConstants.DATA_TYPE_STRING, true)
operation("ComponentScriptExecutor", "ComponentScriptExecutor Operation") {
inputs {
- property(ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Script Type") {
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_TYPE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Script Type"
+ ) {
defaultValue(BluePrintConstants.SCRIPT_INTERNAL)
constrain {
- validValues(listOf(BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(),
+ validValues(
+ listOf(
+ BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive(),
BluePrintConstants.SCRIPT_JYTHON.asJsonPrimitive(),
- BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive()))
+ BluePrintConstants.SCRIPT_KOTLIN.asJsonPrimitive()
+ )
+ )
}
}
- property(ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
- true, "Kotlin Script class name or jython script name.")
- property(ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
- false, "Dynamic Json Content or DSL Json reference.")
+ property(
+ ComponentScriptExecutor.INPUT_SCRIPT_CLASS_REFERENCE, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Kotlin Script class name or jython script name."
+ )
+ property(
+ ComponentScriptExecutor.INPUT_DYNAMIC_PROPERTIES, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Dynamic Json Content or DSL Json reference."
+ )
}
outputs {
- property(ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
- false, "Output Response")
- property(ComponentScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
- true, "Status of the Component Execution ( success or failure )")
+ property(
+ ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, BluePrintConstants.DATA_TYPE_JSON,
+ false, "Output Response"
+ )
+ property(
+ ComponentScriptExecutor.OUTPUT_STATUS, BluePrintConstants.DATA_TYPE_STRING,
+ true, "Status of the Component Execution ( success or failure )"
+ )
}
}
}
}
/** Component Builder */
-fun BluePrintTypes.nodeTemplateComponentScriptExecutor(id: String,
- description: String,
- block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit)
- : NodeTemplate {
+fun BluePrintTypes.nodeTemplateComponentScriptExecutor(
+ id: String,
+ description: String,
+ block: ComponentScriptExecutorNodeTemplateBuilder.() -> Unit
+):
+ NodeTemplate {
return ComponentScriptExecutorNodeTemplateBuilder(id, description).apply(block).build()
}
class ComponentScriptExecutorNodeTemplateBuilder(id: String, description: String) :
- AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
- ComponentScriptExecutorNodeTemplateBuilder.InputsBuilder,
- ComponentScriptExecutorNodeTemplateBuilder.OutputsBuilder>(id, "component-script-executor",
- "ComponentScriptExecutor",
- description) {
+ AbstractNodeTemplateOperationImplBuilder<PropertiesAssignmentBuilder,
+ ComponentScriptExecutorNodeTemplateBuilder.InputsBuilder,
+ ComponentScriptExecutorNodeTemplateBuilder.OutputsBuilder>(
+ id, "component-script-executor",
+ "ComponentScriptExecutor",
+ description
+ ) {
class InputsBuilder : PropertiesAssignmentBuilder() {
@@ -117,4 +137,4 @@ class ComponentScriptExecutorNodeTemplateBuilder(id: String, description: String
property(ComponentScriptExecutor.OUTPUT_RESPONSE_DATA, responseData)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ExecutionServiceConfiguration.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ExecutionServiceConfiguration.kt
index 806c33039..3ff54076d 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ExecutionServiceConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ExecutionServiceConfiguration.kt
@@ -23,7 +23,6 @@ import org.springframework.context.annotation.Configuration
@ComponentScan
open class ExecutionServiceConfiguration
-
object ExecutionServiceConstant {
const val SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION = "grpc-remote-script-execution-service"
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt
index d6146e111..3b83261e5 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/RemoteScriptExecutionService.kt
@@ -21,10 +21,19 @@ import com.google.protobuf.Struct
import com.google.protobuf.Timestamp
import com.google.protobuf.util.JsonFormat
import io.grpc.ManagedChannel
-import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.*
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.PrepareRemoteEnvInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteIdentifier
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.RemoteScriptExecutionOutput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StatusType
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService
-import org.onap.ccsdk.cds.controllerblueprints.command.api.*
+import org.onap.ccsdk.cds.controllerblueprints.command.api.CommandExecutorServiceGrpc
+import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionInput
+import org.onap.ccsdk.cds.controllerblueprints.command.api.ExecutionOutput
+import org.onap.ccsdk.cds.controllerblueprints.command.api.Identifiers
+import org.onap.ccsdk.cds.controllerblueprints.command.api.Packages
+import org.onap.ccsdk.cds.controllerblueprints.command.api.PrepareEnvInput
import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.slf4j.LoggerFactory
@@ -41,11 +50,13 @@ interface RemoteScriptExecutionService {
}
@Service(ExecutionServiceConstant.SERVICE_GRPC_REMOTE_SCRIPT_EXECUTION)
-@ConditionalOnProperty(prefix = "blueprintprocessor.remoteScriptCommand", name = arrayOf("enabled"),
- havingValue = "true", matchIfMissing = false)
+@ConditionalOnProperty(
+ prefix = "blueprintprocessor.remoteScriptCommand", name = arrayOf("enabled"),
+ havingValue = "true", matchIfMissing = false
+)
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService)
- : RemoteScriptExecutionService {
+class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) :
+ RemoteScriptExecutionService {
private val log = LoggerFactory.getLogger(GrpcRemoteScriptExecutionService::class.java)!!
@@ -70,8 +81,8 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi
}
}
- override suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput)
- : RemoteScriptExecutionOutput {
+ override suspend fun prepareEnv(prepareEnvInput: PrepareRemoteEnvInput):
+ RemoteScriptExecutionOutput {
val grpResponse = commandExecutorServiceGrpc.prepareEnv(prepareEnvInput.asGrpcData())
checkNotNull(grpResponse.status) {
@@ -84,8 +95,8 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi
return remoteScriptExecutionOutput
}
- override suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput)
- : RemoteScriptExecutionOutput {
+ override suspend fun executeCommand(remoteExecutionInput: RemoteScriptExecutionInput):
+ RemoteScriptExecutionOutput {
val grpResponse = commandExecutorServiceGrpc.executeCommand(remoteExecutionInput.asGrpcData())
@@ -103,7 +114,6 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi
channel?.shutdownNow()
}
-
fun PrepareRemoteEnvInput.asGrpcData(): PrepareEnvInput {
val correlationId = this.correlationId ?: this.requestId
@@ -116,33 +126,33 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi
}
return PrepareEnvInput.newBuilder()
- .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
- .setRequestId(this.requestId)
- .setCorrelationId(correlationId)
- .setTimeOut(this.timeOut.toInt())
- .addAllPackages(packageList)
- .setProperties(this.properties.asGrpcData())
- .build()
+ .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
+ .setRequestId(this.requestId)
+ .setCorrelationId(correlationId)
+ .setTimeOut(this.timeOut.toInt())
+ .addAllPackages(packageList)
+ .setProperties(this.properties.asGrpcData())
+ .build()
}
fun RemoteScriptExecutionInput.asGrpcData(): ExecutionInput {
val correlationId = this.correlationId ?: this.requestId
return ExecutionInput.newBuilder()
- .setRequestId(this.requestId)
- .setCorrelationId(correlationId)
- .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
- .setCommand(this.command)
- .setTimeOut(this.timeOut.toInt())
- .setProperties(this.properties.asGrpcData())
- .setTimestamp(Timestamp.getDefaultInstance())
- .build()
+ .setRequestId(this.requestId)
+ .setCorrelationId(correlationId)
+ .setIdentifiers(this.remoteIdentifier!!.asGrpcData())
+ .setCommand(this.command)
+ .setTimeOut(this.timeOut.toInt())
+ .setProperties(this.properties.asGrpcData())
+ .setTimestamp(Timestamp.getDefaultInstance())
+ .build()
}
fun RemoteIdentifier.asGrpcData(): Identifiers? {
return Identifiers.newBuilder()
- .setBlueprintName(this.blueprintName)
- .setBlueprintVersion(this.blueprintVersion)
- .build()
+ .setBlueprintName(this.blueprintName)
+ .setBlueprintVersion(this.blueprintVersion)
+ .build()
}
fun Map<String, JsonNode>.asGrpcData(): Struct {
@@ -153,11 +163,10 @@ class GrpcRemoteScriptExecutionService(private val bluePrintGrpcLibPropertyServi
fun ExecutionOutput.asJavaData(): RemoteScriptExecutionOutput {
return RemoteScriptExecutionOutput(
- requestId = this.requestId,
- response = this.responseList,
- status = StatusType.valueOf(this.status.name),
- payload = payload.jsonAsJsonType()
+ requestId = this.requestId,
+ response = this.responseList,
+ status = StatusType.valueOf(this.status.name),
+ payload = payload.jsonAsJsonType()
)
}
-
}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt
index adb1d67d2..239ff00c5 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionService.kt
@@ -20,10 +20,14 @@ import com.fasterxml.jackson.databind.JsonNode
import com.github.marcoferrer.krotoplus.coroutines.client.ClientBidiCallChannel
import com.github.marcoferrer.krotoplus.coroutines.client.clientCallBidiStreaming
import io.grpc.ManagedChannel
-import kotlinx.coroutines.*
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeout
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.GrpcClientProperties
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcClientService
import org.onap.ccsdk.cds.blueprintsprocessor.grpc.service.BluePrintGrpcLibPropertyService
@@ -50,10 +54,12 @@ interface StreamingRemoteExecutionService<ReqT, ResT> {
}
@Service
-@ConditionalOnProperty(prefix = "blueprintsprocessor.streamingRemoteExecution", name = ["enabled"],
- havingValue = "true", matchIfMissing = false)
-class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService)
- : StreamingRemoteExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+@ConditionalOnProperty(
+ prefix = "blueprintsprocessor.streamingRemoteExecution", name = ["enabled"],
+ havingValue = "true", matchIfMissing = false
+)
+class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertyService: BluePrintGrpcLibPropertyService) :
+ StreamingRemoteExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = logger(StreamingRemoteExecutionServiceImpl::class)
@@ -62,7 +68,6 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
private val commChannels: MutableMap<String,
ClientBidiCallChannel<ExecutionServiceInput, ExecutionServiceOutput>> = hashMapOf()
-
/**
* Open new channel to send and receive for grpc properties [selector] for [txId],
* Create the only one GRPC channel per host port and reuse for further communication.
@@ -84,7 +89,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
}
val commChannel = commChannels[txId]
- ?: throw BluePrintException("failed to create response subscription for transactionId($txId) channel")
+ ?: throw BluePrintException("failed to create response subscription for transactionId($txId) channel")
log.info("created subscription for transactionId($txId)")
@@ -97,7 +102,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
*/
override suspend fun send(txId: String, input: ExecutionServiceInput) {
val sendChannel = commChannels[txId]?.requestChannel
- ?: throw BluePrintException("failed to get transactionId($txId) send channel")
+ ?: throw BluePrintException("failed to get transactionId($txId) send channel")
coroutineScope {
launch {
sendChannel.send(input)
@@ -114,15 +119,15 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
* so the correlation is sub request id to receive the response.
*/
@ExperimentalCoroutinesApi
- override suspend fun sendNonInteractive(selector: Any, txId: String, input: ExecutionServiceInput, timeOutMill: Long)
- : ExecutionServiceOutput {
+ override suspend fun sendNonInteractive(selector: Any, txId: String, input: ExecutionServiceInput, timeOutMill: Long):
+ ExecutionServiceOutput {
var output: ExecutionServiceOutput? = null
val flow = openSubscription(selector, txId)
/** Send the request */
val sendChannel = commChannels[txId]?.requestChannel
- ?: throw BluePrintException("failed to get transactionId($txId) send channel")
+ ?: throw BluePrintException("failed to get transactionId($txId) send channel")
sendChannel.send(input)
/** Receive the response with timeout */
@@ -145,7 +150,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
if (!it.requestChannel.isClosedForSend)
it.requestChannel.close()
/** If receive channel has to close immediately, once the subscription has cancelled, then enable this */
- //it.responseChannel.cancel(CancellationException("subscription cancelled"))
+ // it.responseChannel.cancel(CancellationException("subscription cancelled"))
commChannels.remove(txId)
log.info("closed subscription for transactionId($txId)")
}
@@ -182,7 +187,7 @@ class StreamingRemoteExecutionServiceImpl(private val bluePrintGrpcLibPropertySe
suspend fun createGrpcChannel(grpcProperties: GrpcClientProperties): ManagedChannel {
val grpcClientService: BluePrintGrpcClientService = bluePrintGrpcLibPropertyService
- .blueprintGrpcClientService(grpcProperties)
+ .blueprintGrpcClientService(grpcProperties)
return grpcClientService.channel()
}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt
index 814054804..dd4c0ec99 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt
@@ -32,13 +32,19 @@ import org.springframework.stereotype.Service
import java.io.File
@Service
-class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
- private val applicationContext: ApplicationContext) {
+class BlueprintJythonService(
+ val pythonExecutorProperty: PythonExecutorProperty,
+ private val applicationContext: ApplicationContext
+) {
val log: Logger = LoggerFactory.getLogger(BlueprintJythonService::class.java)
- inline fun <reified T> jythonInstance(blueprintContext: BluePrintContext, pythonClassName: String, content: String,
- dependencyInstanceNames: MutableMap<String, Any>?): T {
+ inline fun <reified T> jythonInstance(
+ blueprintContext: BluePrintContext,
+ pythonClassName: String,
+ content: String,
+ dependencyInstanceNames: MutableMap<String, Any>?
+ ): T {
val blueprintBasePath: String = blueprintContext.rootPath
val pythonPath: MutableList<String> = arrayListOf()
@@ -59,8 +65,8 @@ class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
BlueprintFunctionNode<*, *> {
val pythonFileName = bluePrintContext.rootPath
- .plus(File.separator)
- .plus(scriptClassReference)
+ .plus(File.separator)
+ .plus(scriptClassReference)
val pythonClassName = FilenameUtils.getBaseName(pythonFileName)
log.info("Getting Jython Script Class($pythonClassName)")
@@ -70,8 +76,10 @@ class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
val jythonInstances: MutableMap<String, Any> = hashMapOf()
jythonInstances["log"] = LoggerFactory.getLogger(pythonClassName)
- return jythonInstance<BlueprintFunctionNode<*, *>>(bluePrintContext, pythonClassName,
- content, jythonInstances)
+ return jythonInstance<BlueprintFunctionNode<*, *>>(
+ bluePrintContext, pythonClassName,
+ content, jythonInstances
+ )
}
fun jythonComponentInstance(abstractComponentFunction: AbstractComponentFunction): AbstractComponentFunction {
@@ -82,25 +90,27 @@ class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
val operationInputs: MutableMap<String, JsonNode> = abstractComponentFunction.operationInputs
val operationAssignment: OperationAssignment = bluePrintContext
- .nodeTemplateInterfaceOperation(abstractComponentFunction.nodeTemplateName,
- abstractComponentFunction.interfaceName, abstractComponentFunction.operationName)
+ .nodeTemplateInterfaceOperation(
+ abstractComponentFunction.nodeTemplateName,
+ abstractComponentFunction.interfaceName, abstractComponentFunction.operationName
+ )
val blueprintBasePath: String = bluePrintContext.rootPath
val artifactName: String = operationAssignment.implementation?.primary
- ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
+ ?: throw BluePrintProcessorException("missing primary field to get artifact name for node template ($nodeTemplateName)")
val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName)
val pythonFileName = artifactDefinition.file
- ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
+ ?: throw BluePrintProcessorException("missing file name for node template ($nodeTemplateName)'s artifactName($artifactName)")
val pythonClassName = FilenameUtils.getBaseName(pythonFileName)
log.info("Getting Jython Script Class($pythonClassName)")
val content: String? = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName)
- checkNotEmpty(content){ "artifact ($artifactName) content is empty"}
+ checkNotEmpty(content) { "artifact ($artifactName) content is empty" }
val pythonPath: MutableList<String> = operationAssignment.implementation?.dependencies ?: arrayListOf()
pythonPath.add(blueprintBasePath)
@@ -110,17 +120,17 @@ class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty,
jythonInstances["log"] = LoggerFactory.getLogger(nodeTemplateName)
val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode
- ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
+ ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})")
instanceDependenciesNode.forEach { instanceName ->
jythonInstances[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue())
}
- val scriptComponentFunction = jythonInstance<AbstractComponentFunction>(bluePrintContext, pythonClassName,
- content!!, jythonInstances)
+ val scriptComponentFunction = jythonInstance<AbstractComponentFunction>(
+ bluePrintContext, pythonClassName,
+ content!!, jythonInstances
+ )
return scriptComponentFunction
-
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt
index 78b7556f3..b348a9bef 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt
@@ -19,7 +19,7 @@ import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
import org.python.core.PyObject
import org.python.util.PythonInterpreter
-open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython){
+open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython) {
private val blueprintPythonInterpreterProxy: BlueprintPythonInterpreterProxy
init {
@@ -42,9 +42,9 @@ open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython){
try {
return blueprintPythonInterpreterProxy.getPythonInstance(properties)
} catch (e: Exception) {
- throw BluePrintProcessorException("Failed to execute Jython component ${e.toString()}", e)
+ throw BluePrintProcessorException("Failed to execute Jython component $e", e)
}
}
- //TODO Check potential errors in python scripts
+ // TODO Check potential errors in python scripts
}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt
index 6e514de49..6f311bcd2 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt
@@ -33,12 +33,13 @@ open class BlueprintPythonInterpreterProxy(private val bluePrintPython: BluePrin
try {
this.exec(bluePrintPython.content)
} catch (e: PySyntaxError) {
- throw BluePrintProcessorException("Error executing Jython code! Python error: '${e.toString()}'", e)
+ throw BluePrintProcessorException("Error executing Jython code! Python error: '$e'", e)
}
}
val initCommand = bluePrintPython.pythonClassName.plus(" = ").plus(
- bluePrintPython.pythonClassName).plus("()")
+ bluePrintPython.pythonClassName
+ ).plus("()")
this.exec(initCommand)
return this.get(bluePrintPython.pythonClassName)
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt
index 658b0c291..0a220948d 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt
@@ -32,6 +32,7 @@ open class PythonExecutorConfiguration
@Configuration
open class PythonExecutorProperty {
+
@Value("\${blueprints.processor.functions.python.executor.executionPath}")
lateinit var executionPath: String
@Value("#{'\${blueprints.processor.functions.python.executor.modulePaths}'.split(',')}")
@@ -44,8 +45,12 @@ class PythonExecutorConstants {
}
}
-open class BluePrintPython(executablePath: String, blueprintPythonPlatform: MutableList<String>,
- val argv: MutableList<String>){
+open class BluePrintPython(
+ executablePath: String,
+ blueprintPythonPlatform: MutableList<String>,
+ val argv: MutableList<String>
+) {
+
lateinit var moduleName: String
lateinit var pythonClassName: String
lateinit var content: String
@@ -65,4 +70,4 @@ open class BluePrintPython(executablePath: String, blueprintPythonPlatform: Muta
props.setProperty("python.verbose", "error")
props.setProperty("python.executable", executablePath)
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt
new file mode 100644
index 000000000..2091e0366
--- /dev/null
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentRemoteScriptExecutorTest.kt
@@ -0,0 +1,196 @@
+/*
+ * Copyright © 2018-2019 AT&T Intellectual Property.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution
+
+import com.fasterxml.jackson.databind.JsonNode
+import com.fasterxml.jackson.databind.ObjectMapper
+import com.fasterxml.jackson.databind.node.ObjectNode
+import io.mockk.coEvery
+import io.mockk.every
+import io.mockk.mockk
+import kotlinx.coroutines.runBlocking
+import org.junit.Test
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
+import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createExecutionServiceOutputProto
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.createStatus
+import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.toProto
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
+import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
+import org.onap.ccsdk.cds.controllerblueprints.core.jsonAsJsonType
+import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
+import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput
+import kotlin.test.assertNotNull
+
+class ComponentRemoteScriptExecutorTest {
+
+ @Test
+ fun testNodeComponentRemoteScriptExecutorType() {
+ val nodeType = BluePrintTypes.nodeTypeComponentRemoteScriptExecutor()
+ assertNotNull(nodeType, "failed to generate nodeType Component Remote Script Executor")
+ }
+
+ @Test
+ fun testNodeTemplateComponentRemoteScriptExecutor() {
+
+ val nodeTemplate = BluePrintTypes.nodeTemplateComponentRemoteScriptExecutor(
+ "remote-sample",
+ "This is sample node template"
+ ) {
+ definedOperation(" Sample Operation") {
+ implementation(180, "SELF")
+ inputs {
+ selector("remote-script-executor")
+ blueprintName("sample")
+ blueprintVersion("1.0.0")
+ blueprintAction("sample-action")
+ timeout(120)
+ requestData("""{"key" :"value"}""")
+ }
+ outputs {
+ status("success")
+ }
+ }
+ }
+ assertNotNull(nodeTemplate, "failed to generate nodeTemplate Component Remote Script Executor")
+ }
+
+ @Test
+ fun testComponentRemoteScriptExecutor() {
+ runBlocking {
+ /** Mock blueprint context */
+ val blueprintContext = mockk<BluePrintContext>()
+ every { blueprintContext.rootPath } returns normalizedPathName("target")
+ every {
+ blueprintContext.nodeTemplateOperationImplementation(
+ "remote-execute", "ComponentRemoteScriptExecutor", "process"
+ )
+ } returns Implementation()
+
+ val bluePrintRuntime = mockk<DefaultBluePrintRuntimeService>("1234")
+ every { bluePrintRuntime.bluePrintContext() } returns blueprintContext
+
+ val mockExecutionServiceInput = mockExecutionServiceInput(bluePrintRuntime)
+
+ val mockStreamingRemoteExecutionService = mockk<StreamingRemoteExecutionService<
+ org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput,
+ org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput>>()
+
+ coEvery {
+ mockStreamingRemoteExecutionService.sendNonInteractive(
+ any(),
+ any(),
+ any(),
+ any()
+ )
+ } returns mockExecutionServiceOutput(mockExecutionServiceInput)
+
+ val componentRemoteScriptExecutor = ComponentRemoteScriptExecutor(mockStreamingRemoteExecutionService)
+ componentRemoteScriptExecutor.bluePrintRuntimeService = bluePrintRuntime
+ componentRemoteScriptExecutor.implementation = Implementation()
+ val componentRemoteScriptExecutorOutput = componentRemoteScriptExecutor.applyNB(mockExecutionServiceInput)
+ assertNotNull(componentRemoteScriptExecutorOutput, "failed to get executor output")
+ }
+ }
+
+ private fun mockExecutionServiceInput(bluePrintRuntime: DefaultBluePrintRuntimeService): ExecutionServiceInput {
+
+ val mapper = ObjectMapper()
+ val requestNode = mapper.createObjectNode()
+ requestNode.put("ip-address", "0.0.0.0")
+ requestNode.put("type", "grpc")
+
+ val operationInputs = hashMapOf<String, JsonNode>()
+ operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "remote-execute".asJsonPrimitive()
+ operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] =
+ "ComponentRemoteScriptExecutor".asJsonPrimitive()
+ operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "process".asJsonPrimitive()
+
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_SELECTOR] = "remote-script-executor".asJsonPrimitive()
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_NAME] = "sample-blueprint".asJsonPrimitive()
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_VERSION] = "1.0.0".asJsonPrimitive()
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_BLUEPRINT_ACTION] = "remote-activate".asJsonPrimitive()
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_TIMEOUT] = 120.asJsonPrimitive()
+ operationInputs[ComponentRemoteScriptExecutor.INPUT_REQUEST_DATA] = requestNode
+
+ val stepInputData = StepData().apply {
+ name = "remote-execute"
+ properties = operationInputs
+ }
+ val executionServiceInput = ExecutionServiceInput().apply {
+ commonHeader = CommonHeader().apply {
+ requestId = "1234"
+ subRequestId = "1234-123"
+ originatorId = "test-client"
+ }
+ actionIdentifiers = ActionIdentifiers().apply {
+ blueprintName = "sample-blueprint"
+ blueprintVersion = "1.0.0"
+ actionName = "remote-activate"
+ mode = ACTION_MODE_SYNC
+ }
+ payload = """{}""".jsonAsJsonType() as ObjectNode
+ }
+ executionServiceInput.stepData = stepInputData
+
+ every {
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs(
+ "remote-execute", "ComponentRemoteScriptExecutor", "process"
+ )
+ } returns operationInputs
+
+ /** Mock Set Attributes */
+ every {
+ bluePrintRuntime.setNodeTemplateAttributeValue(
+ "remote-execute", any(), any()
+ )
+ } returns Unit
+
+ val operationOutputs = hashMapOf<String, JsonNode>()
+ every {
+ bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs(
+ "remote-execute", "ComponentRemoteScriptExecutor", "process"
+ )
+ } returns operationOutputs
+
+ return executionServiceInput
+ }
+
+ private fun mockExecutionServiceOutput(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
+ val actionName = executionServiceInput.actionIdentifiers.actionName
+ val responsePayload = """
+ {
+ "$actionName-response" :{
+ "key" : "value"
+ }
+ }
+ """.trimIndent()
+ return createExecutionServiceOutputProto(
+ executionServiceInput.commonHeader.toProto(),
+ executionServiceInput.actionIdentifiers.toProto(),
+ createStatus(BluePrintConstants.STATUS_SUCCESS, 200),
+ responsePayload
+ )
+ }
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt
index 6bffffdb5..a0eaeca5f 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/MockBluePrintProcessingServer.kt
@@ -31,15 +31,16 @@ import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOu
private val log = logger(MockBluePrintProcessingServer::class)
-
class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() {
override fun process(responseObserver: StreamObserver<ExecutionServiceOutput>): StreamObserver<ExecutionServiceInput> {
return object : StreamObserver<ExecutionServiceInput> {
override fun onNext(executionServiceInput: ExecutionServiceInput) {
- log.info("Received requestId(${executionServiceInput.commonHeader.requestId}) " +
- "subRequestId(${executionServiceInput.commonHeader.subRequestId})")
+ log.info(
+ "Received requestId(${executionServiceInput.commonHeader.requestId}) " +
+ "subRequestId(${executionServiceInput.commonHeader.subRequestId})"
+ )
runBlocking {
launch(MDCContext()) {
responseObserver.onNext(buildNotification(executionServiceInput))
@@ -52,9 +53,11 @@ class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintPr
override fun onError(error: Throwable) {
log.debug("Fail to process message", error)
- responseObserver.onError(io.grpc.Status.INTERNAL
+ responseObserver.onError(
+ io.grpc.Status.INTERNAL
.withDescription(error.message)
- .asException())
+ .asException()
+ )
}
override fun onCompleted() {
@@ -63,29 +66,27 @@ class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintPr
}
}
-
private fun buildNotification(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder()
- .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_NOTIFICATION)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
private fun buildResponse(input: ExecutionServiceInput): ExecutionServiceOutput {
val status = Status.newBuilder().setCode(200)
- .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
- .build()
+ .setEventType(EventType.EVENT_COMPONENT_EXECUTED)
+ .build()
return ExecutionServiceOutput.newBuilder()
- .setCommonHeader(input.commonHeader)
- .setActionIdentifiers(input.actionIdentifiers)
- .setStatus(status)
- .build()
-
+ .setCommonHeader(input.commonHeader)
+ .setActionIdentifiers(input.actionIdentifiers)
+ .setStatus(status)
+ .build()
}
}
@@ -93,15 +94,14 @@ class MockBluePrintProcessingServer : BluePrintProcessingServiceGrpc.BluePrintPr
fun main() {
try {
val server = ServerBuilder
- .forPort(50052)
- .intercept(GrpcServerLoggingInterceptor())
- .addService(MockBluePrintProcessingServer())
- .build()
+ .forPort(50052)
+ .intercept(GrpcServerLoggingInterceptor())
+ .addService(MockBluePrintProcessingServer())
+ .build()
server.start()
log.info("GRPC Serve started(${server.isShutdown}) on port(${server.port})...")
server.awaitTermination()
} catch (e: Exception) {
e.printStackTrace()
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt
index 9a5be0151..28e2b11b2 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/StreamingRemoteExecutionServiceTest.kt
@@ -23,8 +23,13 @@ import io.grpc.testing.GrpcCleanupRule
import io.mockk.coEvery
import io.mockk.mockk
import io.mockk.spyk
-import kotlinx.coroutines.*
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC
@@ -37,11 +42,10 @@ import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
import org.onap.ccsdk.cds.controllerblueprints.core.logger
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput
-import java.util.*
+import java.util.UUID
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
-
class StreamingRemoteExecutionServiceTest {
val log = logger(StreamingRemoteExecutionServiceTest::class)
@@ -72,7 +76,7 @@ class StreamingRemoteExecutionServiceTest {
val streamingRemoteExecutionService = StreamingRemoteExecutionServiceImpl(bluePrintGrpcLibPropertyService)
val spyStreamingRemoteExecutionService = spyk(streamingRemoteExecutionService)
- /** To test with real server, uncomment below line */
+ /** To test with real server, comment below line */
coEvery() { spyStreamingRemoteExecutionService.createGrpcChannel(any()) } returns channel
/** Test Send and Receive non interactive transaction */
@@ -82,16 +86,21 @@ class StreamingRemoteExecutionServiceTest {
val request = getRequest(requestId)
val invocationId = request.commonHeader.subRequestId
val deferred = async {
- val response = spyStreamingRemoteExecutionService.sendNonInteractive(tokenAuthGrpcClientProperties,
- invocationId, request, 1000L)
+ val response = spyStreamingRemoteExecutionService.sendNonInteractive(
+ tokenAuthGrpcClientProperties,
+ invocationId, request, 1000L
+ )
assertNotNull(response, "failed to get non interactive response")
- assertEquals(response.commonHeader.requestId, requestId,
- "failed to match non interactive response id")
- assertEquals(response.status.eventType, EventType.EVENT_COMPONENT_EXECUTED,
- "failed to match non interactive response type")
+ assertEquals(
+ response.commonHeader.requestId, requestId,
+ "failed to match non interactive response id"
+ )
+ assertEquals(
+ response.status.eventType, EventType.EVENT_COMPONENT_EXECUTED,
+ "failed to match non interactive response type"
+ )
}
nonInteractiveDeferred.add(deferred)
-
}
nonInteractiveDeferred.awaitAll()
@@ -102,7 +111,7 @@ class StreamingRemoteExecutionServiceTest {
val request = getRequest(requestId)
val invocationId = request.commonHeader.requestId
val responseFlow = spyStreamingRemoteExecutionService
- .openSubscription(tokenAuthGrpcClientProperties, invocationId)
+ .openSubscription(tokenAuthGrpcClientProperties, invocationId)
val deferred = async {
responseFlow.collect {
@@ -119,33 +128,30 @@ class StreamingRemoteExecutionServiceTest {
responseFlowsDeferred.awaitAll()
streamingRemoteExecutionService.closeChannel(tokenAuthGrpcClientProperties)
}
-
}
private fun getRequest(requestId: String): ExecutionServiceInput {
val commonHeader = CommonHeader.newBuilder()
- .setTimestamp("2012-04-23T18:25:43.511Z")
- .setOriginatorId("System")
- .setRequestId(requestId)
- .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
-
+ .setTimestamp("2012-04-23T18:25:43.511Z")
+ .setOriginatorId("System")
+ .setRequestId(requestId)
+ .setSubRequestId("$requestId-" + UUID.randomUUID().toString()).build()
val actionIdentifier = ActionIdentifiers.newBuilder()
- .setActionName("SampleScript")
- .setBlueprintName("sample-cba")
- .setBlueprintVersion("1.0.0")
- .setMode(ACTION_MODE_SYNC)
- .build()
+ .setActionName("SampleScript")
+ .setBlueprintName("sample-cba")
+ .setBlueprintVersion("1.0.0")
+ .setMode(ACTION_MODE_SYNC)
+ .build()
val jsonContent = """{ "key1" : "value1" }"""
val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder
JsonFormat.parser().merge(jsonContent, payloadBuilder)
return ExecutionServiceInput.newBuilder()
- .setCommonHeader(commonHeader)
- .setActionIdentifiers(actionIdentifier)
- .setPayload(payloadBuilder.build())
- .build()
-
+ .setCommonHeader(commonHeader)
+ .setActionIdentifiers(actionIdentifier)
+ .setPayload(payloadBuilder.build())
+ .build()
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt
index 2fc9a993b..e013fa889 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/AbstractComponentFunctionTest.kt
@@ -18,7 +18,7 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts;
+package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
@@ -38,6 +38,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.nodeTypeCompone
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
import org.onap.ccsdk.cds.controllerblueprints.core.normalizedPathName
import org.onap.ccsdk.cds.controllerblueprints.core.scripts.BluePrintScriptsServiceImpl
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext
@@ -54,9 +55,11 @@ import kotlin.test.assertNotNull
* Unit test cases for abstract component function.
*/
@RunWith(SpringRunner::class)
-@ContextConfiguration(classes = [ComponentFunctionScriptingService::class,
- BluePrintScriptsServiceImpl::class, PythonExecutorProperty::class,
- BlueprintJythonService::class])
+@ContextConfiguration(
+ classes = [ComponentFunctionScriptingService::class,
+ BluePrintScriptsServiceImpl::class, PythonExecutorProperty::class,
+ BlueprintJythonService::class]
+)
class AbstractComponentFunctionTest {
lateinit var blueprintContext: BluePrintContext
@@ -68,6 +71,11 @@ class AbstractComponentFunctionTest {
fun init() {
blueprintContext = mockk<BluePrintContext>()
every { blueprintContext.rootPath } returns normalizedPathName("target")
+ every {
+ blueprintContext.nodeTemplateOperationImplementation(
+ any(), any(), any()
+ )
+ } returns Implementation()
}
@Test
@@ -97,7 +105,8 @@ class AbstractComponentFunctionTest {
val sampleComponent = SampleComponent()
sampleComponent.workflowName = "sample-action"
sampleComponent.executionServiceInput = JacksonUtils.readValueFromClassPathFile(
- "payload/requests/sample-execution-request.json", ExecutionServiceInput::class.java)!!
+ "payload/requests/sample-execution-request.json", ExecutionServiceInput::class.java
+ )!!
val payload = sampleComponent.requestPayload()
assertNotNull(payload, "failed to get payload")
val data = sampleComponent.requestPayloadActionProperty("data")?.first()
@@ -144,7 +153,7 @@ class AbstractComponentFunctionTest {
* Mocked input for abstract function test.
*/
private fun getMockedInput(bluePrintRuntime: DefaultBluePrintRuntimeService):
- ExecutionServiceInput {
+ ExecutionServiceInput {
val mapper = ObjectMapper()
val rootNode = mapper.createObjectNode()
@@ -153,14 +162,13 @@ class AbstractComponentFunctionTest {
val operationInputs = hashMapOf<String, JsonNode>()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] =
- "activate-restconf".asJsonPrimitive()
+ "activate-restconf".asJsonPrimitive()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] =
- "interfaceName".asJsonPrimitive()
+ "interfaceName".asJsonPrimitive()
operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] =
- "operationName".asJsonPrimitive()
+ "operationName".asJsonPrimitive()
operationInputs["dynamic-properties"] = rootNode
-
val stepInputData = StepData().apply {
name = "activate-restconf"
properties = operationInputs
@@ -178,13 +186,15 @@ class AbstractComponentFunctionTest {
every {
bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs(
- "activate-restconf", "interfaceName", "operationName")
+ "activate-restconf", "interfaceName", "operationName"
+ )
} returns operationInputs
val operationOutputs = hashMapOf<String, JsonNode>()
every {
bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs(
- "activate-restconf", "interfaceName", "operationName")
+ "activate-restconf", "interfaceName", "operationName"
+ )
} returns operationOutputs
every { bluePrintRuntime.bluePrintContext() } returns blueprintContext
@@ -196,6 +206,4 @@ class AbstractComponentFunctionTest {
val componentScriptExecutor = BluePrintTypes.nodeTypeComponentScriptExecutor()
assertNotNull(componentScriptExecutor.interfaces, "failed to get interface operations")
}
-
}
-
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt
index fd18baf52..a34794a85 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt
@@ -33,9 +33,11 @@ import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [BlueprintJythonService::class, PythonExecutorProperty::class])
-@TestPropertySource(properties =
-["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
- "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"])
+@TestPropertySource(
+ properties =
+ ["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
+ "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"]
+)
class BlueprintJythonServiceTest {
lateinit var blueprintContext: BluePrintContext
@@ -47,26 +49,27 @@ class BlueprintJythonServiceTest {
blueprintContext = mockk<BluePrintContext>()
every { blueprintContext.rootPath } returns normalizedPathName("target")
}
-
+
@Test
fun testGetAbstractPythonPlugin() {
- val content = JacksonUtils.getClassPathFileContent("scripts/SamplePythonComponentNode.py")
- val dependencies: MutableMap<String, Any> = hashMapOf()
+ val content = JacksonUtils.getClassPathFileContent("scripts/SamplePythonComponentNode.py")
+ val dependencies: MutableMap<String, Any> = hashMapOf()
- val abstractPythonPlugin = blueprintJythonService
- .jythonInstance<AbstractComponentFunction>(blueprintContext, "SamplePythonComponentNode",
- content, dependencies)
+ val abstractPythonPlugin = blueprintJythonService
+ .jythonInstance<AbstractComponentFunction>(
+ blueprintContext, "SamplePythonComponentNode",
+ content, dependencies
+ )
- assertNotNull(abstractPythonPlugin, "failed to get python component")
+ assertNotNull(abstractPythonPlugin, "failed to get python component")
}
@Test
fun testGetAbstractJythonComponent() {
- val scriptInstance = "test-classes/scripts/SamplePythonComponentNode.py"
-
- val abstractJythonComponent = blueprintJythonService.jythonComponentInstance(blueprintContext, scriptInstance)
+ val scriptInstance = "test-classes/scripts/SamplePythonComponentNode.py"
- assertNotNull(abstractJythonComponent, "failed to get Jython component")
+ val abstractJythonComponent = blueprintJythonService.jythonComponentInstance(blueprintContext, scriptInstance)
+ assertNotNull(abstractJythonComponent, "failed to get Jython component")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHostTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHostTest.kt
index 3c3efa252..9a93abe0c 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHostTest.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHostTest.kt
@@ -16,21 +16,22 @@
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import org.junit.Test
-
import org.junit.runner.RunWith
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.TestPropertySource
import org.springframework.test.context.junit4.SpringRunner
-import kotlin.test.assertNotNull
import kotlin.test.BeforeTest
+import kotlin.test.assertNotNull
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [BluePrintPython::class, PythonExecutorProperty::class, String::class])
-@TestPropertySource(properties =
-["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
- "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"])
+@TestPropertySource(
+ properties =
+ ["blueprints.processor.functions.python.executor.modulePaths=./../../../../../components/scripts/python/ccsdk_blueprints",
+ "blueprints.processor.functions.python.executor.executionPath=./../../../../../components/scripts/python/ccsdk_blueprints"]
+)
class BlueprintPythonHostTest {
lateinit var blueprintPythonHost: BlueprintPythonHost
@@ -59,4 +60,4 @@ class BlueprintPythonHostTest {
assertNotNull(pythonObject, "failed to get python object")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleComponent.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleComponent.kt
index 000d8c09b..31b1a59c8 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleComponent.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleComponent.kt
@@ -18,21 +18,18 @@
* ============LICENSE_END=========================================================
*/
-
package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService
-
import org.slf4j.LoggerFactory
open class SampleComponent : AbstractComponentFunction() {
val log = LoggerFactory.getLogger(SampleComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
}
@@ -40,20 +37,21 @@ open class SampleComponent : AbstractComponentFunction() {
}
}
-open class SampleRestconfComponent (private var componentFunctionScriptingService: ComponentFunctionScriptingService)
- : AbstractComponentFunction() {
+open class SampleRestconfComponent(private var componentFunctionScriptingService: ComponentFunctionScriptingService) :
+ AbstractComponentFunction() {
val log = LoggerFactory.getLogger(SampleScriptComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
var scriptComponent: AbstractScriptComponentFunction
scriptComponent = componentFunctionScriptingService
- .scriptInstance<AbstractScriptComponentFunction>(this,
- "internal",
- "org.onap.ccsdk.cds.blueprintsprocessor.services" +
- ".execution.scripts.SampleTest",
- mutableListOf())
+ .scriptInstance<AbstractScriptComponentFunction>(
+ this,
+ "internal",
+ "org.onap.ccsdk.cds.blueprintsprocessor.services" +
+ ".execution.scripts.SampleTest",
+ mutableListOf()
+ )
scriptComponent.executeScript(executionServiceInput)
}
@@ -65,11 +63,9 @@ open class SampleScriptComponent : AbstractScriptComponentFunction() {
val log = LoggerFactory.getLogger(SampleScriptComponent::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
-
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleTest.kt
index 6a95e29e7..b10f08dd4 100644
--- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleTest.kt
+++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/SampleTest.kt
@@ -29,7 +29,6 @@ open class SampleTest : AbstractScriptComponentFunction() {
val log = LoggerFactory.getLogger(SampleTest::class.java)!!
-
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
val isPresent = checkDynamicProperties("type")
assertTrue(isPresent)
@@ -39,4 +38,4 @@ open class SampleTest : AbstractScriptComponentFunction() {
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml
index fe7dde994..582475dd6 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml
@@ -31,8 +31,8 @@
<dependencies>
<dependency>
- <groupId>org.onap.ccsdk.cds.controllerblueprints</groupId>
- <artifactId>blueprint-core</artifactId>
+ <groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
+ <artifactId>blueprint-core</artifactId>
</dependency>
<dependency>
<groupId>org.onap.ccsdk.cds.blueprintsprocessor</groupId>
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt
index cde919ce8..492b0ba44 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt
@@ -29,23 +29,25 @@ import org.springframework.stereotype.Service
@Service("bluePrintWorkflowExecutionService")
open class BluePrintWorkflowExecutionServiceImpl(
- private val componentWorkflowExecutionService: ComponentWorkflowExecutionService,
- private val dgWorkflowExecutionService: DGWorkflowExecutionService,
- private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService
+ private val componentWorkflowExecutionService: ComponentWorkflowExecutionService,
+ private val dgWorkflowExecutionService: DGWorkflowExecutionService,
+ private val imperativeWorkflowExecutionService: ImperativeWorkflowExecutionService
) : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = LoggerFactory.getLogger(BluePrintWorkflowExecutionServiceImpl::class.java)!!
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
val workflowName = executionServiceInput.actionIdentifiers.actionName
// Assign Workflow inputs
- //check if request structure exists
+ // check if request structure exists
if (!executionServiceInput.payload.has("$workflowName-request")) {
throw BluePrintProcessorException("Input request missing the expected '$workflowName-request' block!")
}
@@ -59,7 +61,7 @@ open class BluePrintWorkflowExecutionServiceImpl(
/** If workflow has multiple steps, then it is imperative workflow */
val executionServiceOutput: ExecutionServiceOutput = if (steps.size > 1) {
imperativeWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
} else {
// Get the DG Node Template
val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName)
@@ -71,15 +73,17 @@ open class BluePrintWorkflowExecutionServiceImpl(
when {
derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> {
componentWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
}
derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_WORKFLOW, true) -> {
dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties)
}
else -> {
- throw BluePrintProcessorException("couldn't execute workflow($workflowName) step mapped " +
- "to node template($nodeTemplateName) derived from($derivedFrom)")
+ throw BluePrintProcessorException(
+ "couldn't execute workflow($workflowName) step mapped " +
+ "to node template($nodeTemplateName) derived from($derivedFrom)"
+ )
}
}
}
@@ -93,5 +97,4 @@ open class BluePrintWorkflowExecutionServiceImpl(
executionServiceOutput.payload.set("$workflowName-response", workflowOutputs.asObjectNode())
return executionServiceOutput
}
-
}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt
index a2db8aab7..044e8cf53 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt
@@ -48,5 +48,4 @@ class BlueprintSvcLogicContext : SvcLogicContext() {
fun getResponse(): Any {
return this.response!!
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt
index df250ae98..9cc325d94 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt
@@ -18,14 +18,25 @@
package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
-import org.onap.ccsdk.sli.core.sli.*
-import org.onap.ccsdk.sli.core.sli.provider.base.*
+import org.onap.ccsdk.sli.core.sli.ExitNodeException
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext
+import org.onap.ccsdk.sli.core.sli.SvcLogicException
+import org.onap.ccsdk.sli.core.sli.SvcLogicGraph
+import org.onap.ccsdk.sli.core.sli.SvcLogicNode
+import org.onap.ccsdk.sli.core.sli.SvcLogicStore
+import org.onap.ccsdk.sli.core.sli.provider.base.AbstractSvcLogicNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.BlockNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.BreakNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ExecuteNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ExitNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.ReturnNodeExecutor
+import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
-import java.util.*
+import java.util.Properties
import javax.annotation.PostConstruct
interface BlueprintSvcLogicService : SvcLogicServiceBase {
@@ -54,7 +65,6 @@ interface BlueprintSvcLogicService : SvcLogicServiceBase {
}
}
-
@Service
class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService {
@@ -88,9 +98,12 @@ class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService {
}
}
- override suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BluePrintRuntimeService<*>,
- input: Any): Any {
- //Initialise BlueprintSvcLogic Context with Blueprint Runtime Service and Input Request
+ override suspend fun execute(
+ graph: SvcLogicGraph,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ input: Any
+ ): Any {
+ // Initialise BlueprintSvcLogic Context with Blueprint Runtime Service and Input Request
val blueprintSvcLogicContext = BlueprintSvcLogicContext()
blueprintSvcLogicContext.setBluePrintRuntimeService(bluePrintRuntimeService)
blueprintSvcLogicContext.setRequest(input)
@@ -140,4 +153,4 @@ class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService {
MDC.remove("currentGraph")
return svcLogicContext
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt
index 3c474de37..70910e15c 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt
@@ -16,7 +16,6 @@
package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow
-
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
@@ -24,12 +23,14 @@ import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeServ
import org.springframework.stereotype.Service
@Service("componentWorkflowExecutionService")
-open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
@@ -38,8 +39,9 @@ open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionSe
// Get the DG Node Template
val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName)
- return nodeTemplateExecutionService.executeNodeTemplate(bluePrintRuntimeService,
- nodeTemplateName, executionServiceInput)
+ return nodeTemplateExecutionService.executeNodeTemplate(
+ bluePrintRuntimeService,
+ nodeTemplateName, executionServiceInput
+ )
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt
index 4485800ff..b1847df43 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt
@@ -26,16 +26,17 @@ import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeServ
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
-
@Service("dgWorkflowExecutionService")
-open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
private val log = LoggerFactory.getLogger(DGWorkflowExecutionService::class.java)
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
@@ -47,8 +48,10 @@ open class DGWorkflowExecutionService(private val blueprintSvcLogicService: Blue
log.info("Executing workflow($workflowName) directed graph NodeTemplate($nodeTemplateName)")
// Get the DG file info
- val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(nodeTemplateName,
- WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH)
+ val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(
+ nodeTemplateName,
+ WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH
+ )
// Populate the DG Path
val dgFilePath = normalizedPathName(bluePrintContext.rootPath, artifactDefinition.file)
@@ -59,10 +62,10 @@ open class DGWorkflowExecutionService(private val blueprintSvcLogicService: Blue
val graph = SvcGraphUtils.getSvcGraphFromFile(dgFilePath)
// Execute the DG
- return blueprintSvcLogicService.execute(graph,
+ return blueprintSvcLogicService.execute(
+ graph,
bluePrintRuntimeService,
- executionServiceInput) as ExecutionServiceOutput
-
+ executionServiceInput
+ ) as ExecutionServiceOutput
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt
index d296ec6e6..ebd9d553d 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionService.kt
@@ -21,23 +21,35 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInpu
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput
import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType
-import org.onap.ccsdk.cds.controllerblueprints.core.*
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
+import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
+import org.onap.ccsdk.cds.controllerblueprints.core.asGraph
+import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.data.EdgeLabel
import org.onap.ccsdk.cds.controllerblueprints.core.data.Graph
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService
-import org.onap.ccsdk.cds.controllerblueprints.core.service.*
+import org.onap.ccsdk.cds.controllerblueprints.core.logger
+import org.onap.ccsdk.cds.controllerblueprints.core.service.AbstractBluePrintWorkFlowService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintWorkFlowService
+import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeExecuteMessage
+import org.onap.ccsdk.cds.controllerblueprints.core.service.NodeSkipMessage
+import org.onap.ccsdk.cds.controllerblueprints.core.service.WorkflowExecuteMessage
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
@Service("imperativeWorkflowExecutionService")
class ImperativeWorkflowExecutionService(
- private val imperativeBluePrintWorkflowService: BluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>)
- : BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
+ private val imperativeBluePrintWorkflowService: BluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>
+) :
+ BluePrintWorkflowExecutionService<ExecutionServiceInput, ExecutionServiceOutput> {
- override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>,
- executionServiceInput: ExecutionServiceInput,
- properties: MutableMap<String, Any>): ExecutionServiceOutput {
+ override suspend fun executeBluePrintWorkflow(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ executionServiceInput: ExecutionServiceInput,
+ properties: MutableMap<String, Any>
+ ): ExecutionServiceOutput {
val bluePrintContext = bluePrintRuntimeService.bluePrintContext()
@@ -45,23 +57,29 @@ class ImperativeWorkflowExecutionService(
val graph = bluePrintContext.workflowByName(workflowName).asGraph()
- return imperativeBluePrintWorkflowService.executeWorkflow(graph, bluePrintRuntimeService,
- executionServiceInput)
+ return imperativeBluePrintWorkflowService.executeWorkflow(
+ graph, bluePrintRuntimeService,
+ executionServiceInput
+ )
}
}
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
-open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : AbstractBluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>() {
+open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ AbstractBluePrintWorkFlowService<ExecutionServiceInput, ExecutionServiceOutput>() {
+
val log = logger(ImperativeBluePrintWorkflowService::class)
lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*>
lateinit var executionServiceInput: ExecutionServiceInput
lateinit var workflowName: String
- override suspend fun executeWorkflow(graph: Graph, bluePrintRuntimeService: BluePrintRuntimeService<*>,
- input: ExecutionServiceInput): ExecutionServiceOutput {
+ override suspend fun executeWorkflow(
+ graph: Graph,
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ input: ExecutionServiceInput
+ ): ExecutionServiceOutput {
this.graph = graph
this.bluePrintRuntimeService = bluePrintRuntimeService
this.executionServiceInput = input
@@ -103,8 +121,8 @@ open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionS
}
}
- override suspend fun prepareNodeExecutionMessage(node: Graph.Node)
- : NodeExecuteMessage<ExecutionServiceInput, ExecutionServiceOutput> {
+ override suspend fun prepareNodeExecutionMessage(node: Graph.Node):
+ NodeExecuteMessage<ExecutionServiceInput, ExecutionServiceOutput> {
val nodeOutput = ExecutionServiceOutput().apply {
commonHeader = executionServiceInput.commonHeader
actionIdentifiers = executionServiceInput.actionIdentifiers
@@ -112,8 +130,8 @@ open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionS
return NodeExecuteMessage(node, executionServiceInput, nodeOutput)
}
- override suspend fun prepareNodeSkipMessage(node: Graph.Node)
- : NodeSkipMessage<ExecutionServiceInput, ExecutionServiceOutput> {
+ override suspend fun prepareNodeSkipMessage(node: Graph.Node):
+ NodeSkipMessage<ExecutionServiceInput, ExecutionServiceOutput> {
val nodeOutput = ExecutionServiceOutput().apply {
commonHeader = executionServiceInput.commonHeader
actionIdentifiers = executionServiceInput.actionIdentifiers
@@ -121,15 +139,18 @@ open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionS
return NodeSkipMessage(node, executionServiceInput, nodeOutput)
}
- override suspend fun executeNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun executeNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
log.info("Executing workflow($workflowName[${this.workflowId}])'s step($${node.id})")
val step = bluePrintRuntimeService.bluePrintContext().workflowStepByName(this.workflowName, node.id)
checkNotEmpty(step.target) { "couldn't get step target for workflow(${this.workflowName})'s step(${node.id})" }
val nodeTemplateName = step.target!!
/** execute node template */
val executionServiceOutput = nodeTemplateExecutionService
- .executeNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeInput)
+ .executeNodeTemplate(bluePrintRuntimeService, nodeTemplateName, nodeInput)
return when (executionServiceOutput.status.message) {
BluePrintConstants.STATUS_FAILURE -> EdgeLabel.FAILURE
@@ -137,18 +158,27 @@ open class ImperativeBluePrintWorkflowService(private val nodeTemplateExecutionS
}
}
- override suspend fun skipNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun skipNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
return EdgeLabel.SUCCESS
}
- override suspend fun cancelNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun cancelNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
TODO("not implemented")
}
- override suspend fun restartNode(node: Graph.Node, nodeInput: ExecutionServiceInput,
- nodeOutput: ExecutionServiceOutput): EdgeLabel {
+ override suspend fun restartNode(
+ node: Graph.Node,
+ nodeInput: ExecutionServiceInput,
+ nodeOutput: ExecutionServiceOutput
+ ): EdgeLabel {
TODO("not implemented")
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt
index b64177aab..6a304e0c7 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt
@@ -23,6 +23,7 @@ import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.StepData
import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
+import org.onap.ccsdk.cds.controllerblueprints.core.data.Implementation
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService
import org.slf4j.LoggerFactory
@@ -33,8 +34,11 @@ open class NodeTemplateExecutionService {
private val log = LoggerFactory.getLogger(NodeTemplateExecutionService::class.java)!!
- suspend fun executeNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String,
- executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput {
+ suspend fun executeNodeTemplate(
+ bluePrintRuntimeService: BluePrintRuntimeService<*>,
+ nodeTemplateName: String,
+ executionServiceInput: ExecutionServiceInput
+ ): ExecutionServiceOutput {
// Get the Blueprint Context
val blueprintContext = bluePrintRuntimeService.bluePrintContext()
@@ -47,12 +51,14 @@ open class NodeTemplateExecutionService {
val operationName = blueprintContext.nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName)
val nodeTemplateImplementation = blueprintContext
- .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
+ .nodeTemplateOperationImplementation(nodeTemplateName, interfaceName, operationName)
+ ?: Implementation()
- val timeout: Int = nodeTemplateImplementation?.timeout ?: 180
-
- log.info("executing node template($nodeTemplateName) component($componentName) " +
- "interface($interfaceName) operation($operationName) with timeout($timeout) sec.")
+ log.info(
+ "executing node template($nodeTemplateName) component($componentName) " +
+ "interface($interfaceName) operation($operationName) on host (${nodeTemplateImplementation.operationHost}) " +
+ "with timeout(${nodeTemplateImplementation.timeout}) sec."
+ )
// Get the Component Instance
val plugin = BluePrintDependencyService.instance<AbstractComponentFunction>(componentName)
@@ -72,7 +78,6 @@ open class NodeTemplateExecutionService {
stepInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = nodeTemplateName.asJsonPrimitive()
stepInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = interfaceName.asJsonPrimitive()
stepInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = operationName.asJsonPrimitive()
- stepInputs[BluePrintConstants.PROPERTY_CURRENT_TIMEOUT] = timeout.asJsonPrimitive()
val stepInputData = StepData().apply {
name = nodeTemplateName
properties = stepInputs
@@ -82,5 +87,4 @@ open class NodeTemplateExecutionService {
// Get the Request from the Context and Set to the Function Input and Invoke the function
return plugin.applyNB(clonedExecutionServiceInput)
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt
index 67f13f760..c1bcc649f 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt
@@ -23,9 +23,8 @@ import org.springframework.context.annotation.Configuration
@ComponentScan
open class WorkflowServiceConfiguration
-
class WorkflowServiceConstants {
companion object {
const val ARTIFACT_TYPE_DIRECTED_GRAPH = "artifact-directed-graph"
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt
index b6e767503..8c4e2d215 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt
@@ -31,14 +31,14 @@ import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
-open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService: NodeTemplateExecutionService)
- : ExecuteNodeExecutor() {
+open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService: NodeTemplateExecutionService) :
+ ExecuteNodeExecutor() {
private val log = LoggerFactory.getLogger(ComponentExecuteNodeExecutor::class.java)
@Throws(SvcLogicException::class)
- override fun execute(svc: SvcLogicServiceBase, node: SvcLogicNode, svcLogicContext: SvcLogicContext)
- : SvcLogicNode = runBlocking {
+ override fun execute(svc: SvcLogicServiceBase, node: SvcLogicNode, svcLogicContext: SvcLogicContext):
+ SvcLogicNode = runBlocking {
var outValue: String
@@ -48,15 +48,16 @@ open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService
val executionInput = ctx.getRequest() as ExecutionServiceInput
- try { // Get the Request from the Context and Set to the Function Input and Invoke the function
- val executionOutput = nodeTemplateExecutionService.executeNodeTemplate(ctx.getBluePrintService(),
- nodeTemplateName, executionInput)
+ try { // Get the Request from the Context and Set to the Function Input and Invoke the function
+ val executionOutput = nodeTemplateExecutionService.executeNodeTemplate(
+ ctx.getBluePrintService(),
+ nodeTemplateName, executionInput
+ )
ctx.setResponse(executionOutput)
outValue = executionOutput.status.message
ctx.status = executionOutput.status.message
-
} catch (e: Exception) {
log.error("Could not execute plugin($nodeTemplateName) : ", e)
outValue = "failure"
@@ -65,5 +66,4 @@ open class ComponentExecuteNodeExecutor(private val nodeTemplateExecutionService
getNextNode(node, outValue)
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt
index 8f9579230..86934f29a 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt
@@ -32,4 +32,4 @@ object SvcGraphUtils {
val svcLogicParser = SvcLogicParser()
return svcLogicParser.parse(fileName).first
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt
index 436de1b56..330056221 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt
@@ -40,7 +40,6 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
-
@RunWith(SpringRunner::class)
@ContextConfiguration(classes = [WorkflowServiceConfiguration::class])
class BluePrintWorkflowExecutionServiceImplTest {
@@ -62,36 +61,48 @@ class BluePrintWorkflowExecutionServiceImplTest {
@Test
fun testBluePrintWorkflowExecutionService() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
@Test
fun testImperativeBluePrintWorkflowExecutionService() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/imperative-test-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/imperative-test-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
@@ -99,16 +110,20 @@ class BluePrintWorkflowExecutionServiceImplTest {
fun `Blueprint fails on missing workflowName-parameters with a useful message`() {
assertFailsWith(exceptionClass = BluePrintProcessorException::class) {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
- //service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input-missing-resource_assignment_request.json",
- ExecutionServiceInput::class.java)!!
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
+ // service input will have a mislabeled input params, we are expecting to get an error when that happens with a useful error message
+ val executionServiceInput =
+ JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input-missing-resource_assignment_request.json",
+ ExecutionServiceInput::class.java
+ )!!
val executionServiceOutput = bluePrintWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
}
}
}
-
}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt
index 12fd9c7c4..3d44894ee 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt
@@ -54,47 +54,51 @@ class BlueprintServiceLogicTest {
@Test
fun testExecuteGraphWithSingleComponent() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input)
val executionServiceOutput = dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
-
}
@Test
fun testExecuteGraphWithMultipleComponents() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("assign-activate-request")
bluePrintRuntimeService.assignWorkflowInputs("assign-activate", input)
-
val executionServiceOutput = dgWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf())
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
}
@Test
@@ -118,5 +122,4 @@ class BlueprintServiceLogicTest {
assertEquals(stepName1, proto1.stepName, " Failed to match the step1 name")
assertEquals(stepName2, proto2.stepName, " Failed to match the step2 name")
}
-
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt
index 3ac5cd864..86d3be26b 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt
@@ -44,7 +44,6 @@ class DGWorkflowExecutionServiceTest {
@Autowired
lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService
-
@Before
fun init() {
BluePrintDependencyService.inject(applicationContext)
@@ -54,25 +53,28 @@ class DGWorkflowExecutionServiceTest {
fun testExecuteDirectedGraph() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
val executionServiceInput = JacksonReactorUtils
- .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile("execution-input/resource-assignment-input.json", ExecutionServiceInput::class.java)!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
bluePrintRuntimeService.assignWorkflowInputs("resource-assignment", input)
- val executionServiceOutput = dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService,
- executionServiceInput, mutableMapOf())
+ val executionServiceOutput = dgWorkflowExecutionService.executeBluePrintWorkflow(
+ bluePrintRuntimeService,
+ executionServiceInput, mutableMapOf()
+ )
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
-
}
-
-
}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt
index b7fcae1d1..415f11d58 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/ImperativeWorkflowExecutionServiceTest.kt
@@ -56,18 +56,36 @@ class ImperativeWorkflowExecutionServiceTest {
}
fun mockServiceTemplate(): ServiceTemplate {
- return serviceTemplate("imperative-test", "1.0.0",
- "brindasanth@onap.com", "tosca") {
+ return serviceTemplate(
+ "imperative-test", "1.0.0",
+ "brindasanth@onap.com", "tosca"
+ ) {
topologyTemplate {
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("resolve-config",
- "cba.wt.imperative.test.ResolveConfig"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-config",
- "cba.wt.imperative.test.ActivateConfig"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-config-rollback",
- "cba.wt.imperative.test.ActivateConfigRollback"))
- nodeTemplate(mockNodeTemplateComponentScriptExecutor("activate-licence",
- "cba.wt.imperative.test.ActivateLicence"))
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "resolve-config",
+ "cba.wt.imperative.test.ResolveConfig"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-config",
+ "cba.wt.imperative.test.ActivateConfig"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-config-rollback",
+ "cba.wt.imperative.test.ActivateConfigRollback"
+ )
+ )
+ nodeTemplate(
+ mockNodeTemplateComponentScriptExecutor(
+ "activate-licence",
+ "cba.wt.imperative.test.ActivateLicence"
+ )
+ )
workflow("imperative-test-wf", "Test Imperative flow") {
step("resolve-config", "resolve-config", "") {
@@ -95,17 +113,19 @@ class ImperativeWorkflowExecutionServiceTest {
val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("12345", bluePrintContext)
val executionServiceInput = JacksonUtils
- .readValueFromClassPathFile("execution-input/imperative-test-input.json",
- ExecutionServiceInput::class.java)!!
+ .readValueFromClassPathFile(
+ "execution-input/imperative-test-input.json",
+ ExecutionServiceInput::class.java
+ )!!
val bluePrintWorkFlowService = ImperativeBluePrintWorkflowService(NodeTemplateExecutionService())
val imperativeWorkflowExecutionService = ImperativeWorkflowExecutionService(bluePrintWorkFlowService)
val output = imperativeWorkflowExecutionService
- .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
+ .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, hashMapOf())
assertNotNull(output, "failed to get imperative workflow output")
assertNotNull(output.status, "failed to get imperative workflow output status")
assertEquals(output.status.message, BluePrintConstants.STATUS_SUCCESS)
assertEquals(output.status.eventType, EventType.EVENT_COMPONENT_EXECUTED.name)
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt
index 24d96629e..1f51a6aae 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionServiceTest.kt
@@ -38,6 +38,7 @@ import kotlin.test.assertNotNull
@ContextConfiguration(classes = [WorkflowServiceConfiguration::class])
class NodeTemplateExecutionServiceTest {
+
@Before
fun init() {
mockkObject(BluePrintDependencyService)
@@ -52,11 +53,15 @@ class NodeTemplateExecutionServiceTest {
@Test
fun testExecuteNodeTemplate() {
runBlocking {
- val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234",
- "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration")
+ val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(
+ "1234",
+ "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration"
+ )
- val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/resource-assignment-input.json",
- ExecutionServiceInput::class.java)!!
+ val executionServiceInput = JacksonUtils.readValueFromClassPathFile(
+ "execution-input/resource-assignment-input.json",
+ ExecutionServiceInput::class.java
+ )!!
// Assign Workflow inputs Mock
val input = executionServiceInput.payload.get("resource-assignment-request")
@@ -65,11 +70,13 @@ class NodeTemplateExecutionServiceTest {
val nodeTemplate = "resource-assignment"
val nodeTemplateExecutionService = NodeTemplateExecutionService()
val executionServiceOutput = nodeTemplateExecutionService
- .executeNodeTemplate(bluePrintRuntimeService, nodeTemplate, executionServiceInput)
+ .executeNodeTemplate(bluePrintRuntimeService, nodeTemplate, executionServiceInput)
assertNotNull(executionServiceOutput, "failed to get response")
- assertEquals(BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
- "failed to get successful response")
+ assertEquals(
+ BluePrintConstants.STATUS_SUCCESS, executionServiceOutput.status.message,
+ "failed to get successful response"
+ )
}
}
-} \ No newline at end of file
+}
diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt
index 44751b5b5..9c3727288 100644
--- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt
+++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt
@@ -29,8 +29,10 @@ import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
-fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BluePrintTypes.nodeTemplateComponentScriptExecutor(id,
- "mock($id) component function") {
+fun mockNodeTemplateComponentScriptExecutor(id: String, script: String) = BluePrintTypes.nodeTemplateComponentScriptExecutor(
+ id,
+ "mock($id) component function"
+) {
definedOperation("") {
inputs {
type("kotlin")
@@ -55,8 +57,10 @@ class MockComponentFunction : AbstractComponentFunction() {
override suspend fun processNB(executionRequest: ExecutionServiceInput) {
log.info("Processing component : $operationInputs")
- bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName,
- "assignment-params", "params".asJsonPrimitive())
+ bluePrintRuntimeService.setNodeTemplateAttributeValue(
+ nodeTemplateName,
+ "assignment-params", "params".asJsonPrimitive()
+ )
}
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
@@ -92,4 +96,4 @@ class PrototypeComponentFunction : AbstractComponentFunction() {
override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) {
log.info("Recovering component..")
}
-} \ No newline at end of file
+}