From c90edac236dffb7c495e266dd04991de7e8f04b7 Mon Sep 17 00:00:00 2001 From: Alexis de Talhouët Date: Mon, 25 Mar 2019 13:04:18 -0400 Subject: Migrate ccsdk/apps to ccsdk/cds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue-ID: CCSDK-1177 Issue-ID: CCSDK-1178 Change-Id: I0c02702fbec52211ca367abbba72aebecee8cbaa Signed-off-by: Alexis de Talhouët --- ms/blueprintsprocessor/application/pom.xml | 14 +- .../blueprintsprocessor/BlueprintGRPCServer.java | 67 ---- .../blueprintsprocessor/BlueprintHttpServer.java | 55 --- .../BlueprintProcessorApplication.java | 39 -- .../apps/blueprintsprocessor/SwaggerConfig.java | 63 ---- .../ccsdk/apps/blueprintsprocessor/WebConfig.java | 78 ---- .../security/AuthenticationManager.java | 40 -- .../security/BasicAuthServerInterceptor.java | 97 ----- .../security/SecurityConfiguration.java | 59 --- .../security/SecurityContextRepository.java | 75 ---- .../blueprintsprocessor/BlueprintGRPCServer.java | 67 ++++ .../blueprintsprocessor/BlueprintHttpServer.java | 55 +++ .../BlueprintProcessorApplication.java | 39 ++ .../cds/blueprintsprocessor/SwaggerConfig.java | 63 ++++ .../ccsdk/cds/blueprintsprocessor/WebConfig.java | 78 ++++ .../security/AuthenticationManager.java | 40 ++ .../security/BasicAuthServerInterceptor.java | 97 +++++ .../security/SecurityConfiguration.java | 59 +++ .../security/SecurityContextRepository.java | 75 ++++ .../application/src/main/resources/logback.xml | 2 +- .../BlueprintProcessorApplicationTest.java | 57 --- .../BlueprintProcessorApplicationTest.java | 57 +++ .../src/test/resources/logback-test.xml | 2 +- ms/blueprintsprocessor/distribution/pom.xml | 6 +- .../distribution/src/main/docker/run.source | 4 +- .../functions/cli-executor/pom.xml | 2 +- .../cli/executor/CliExecutorConfiguration.kt | 22 -- .../cli/executor/api/CliExecutorService.kt | 22 -- .../cli/executor/service/CliExecutorServiceImpl.kt | 25 -- .../cli/executor/CliExecutorConfiguration.kt | 22 ++ .../cli/executor/api/CliExecutorService.kt | 22 ++ .../cli/executor/service/CliExecutorServiceImpl.kt | 25 ++ .../executor/service/CliExecutorServiceImplTest.kt | 38 -- .../executor/service/CliExecutorServiceImplTest.kt | 38 ++ .../src/test/resources/logback-test.xml | 2 +- .../functions/netconf-executor/pom.xml | 6 +- .../netconf/executor/ComponentNetconfExecutor.kt | 75 ---- .../netconf/executor/JsonParserService.kt | 24 -- .../netconf/executor/NetconfComponentFunction.kt | 70 ---- .../functions/netconf/executor/NetconfDevice.kt | 31 -- .../functions/netconf/executor/api/DeviceInfo.kt | 43 --- .../netconf/executor/api/NetconfException.kt | 24 -- .../netconf/executor/api/NetconfMessage.kt | 74 ---- .../netconf/executor/api/NetconfRpcService.kt | 142 -------- .../netconf/executor/api/NetconfSession.kt | 86 ----- .../netconf/executor/api/NetconfSessionListener.kt | 21 -- .../executor/core/NetconfDeviceCommunicator.kt | 243 ------------- .../netconf/executor/core/NetconfRpcServiceImpl.kt | 220 ----------- .../netconf/executor/core/NetconfSessionImpl.kt | 287 --------------- .../netconf/executor/utils/NetconfConstant.kt | 90 ----- .../netconf/executor/utils/NetconfMessageUtils.kt | 404 --------------------- .../netconf/executor/ComponentNetconfExecutor.kt | 75 ++++ .../netconf/executor/JsonParserService.kt | 24 ++ .../netconf/executor/NetconfComponentFunction.kt | 70 ++++ .../functions/netconf/executor/NetconfDevice.kt | 31 ++ .../functions/netconf/executor/api/DeviceInfo.kt | 43 +++ .../netconf/executor/api/NetconfException.kt | 24 ++ .../netconf/executor/api/NetconfMessage.kt | 74 ++++ .../netconf/executor/api/NetconfRpcService.kt | 142 ++++++++ .../netconf/executor/api/NetconfSession.kt | 86 +++++ .../netconf/executor/api/NetconfSessionListener.kt | 21 ++ .../executor/core/NetconfDeviceCommunicator.kt | 243 +++++++++++++ .../netconf/executor/core/NetconfRpcServiceImpl.kt | 220 +++++++++++ .../netconf/executor/core/NetconfSessionImpl.kt | 287 +++++++++++++++ .../netconf/executor/utils/NetconfConstant.kt | 90 +++++ .../netconf/executor/utils/NetconfMessageUtils.kt | 404 +++++++++++++++++++++ .../executor/ComponentNetconfExecutorTest.kt | 79 ---- .../netconf/executor/NetconfSessionImplTest.kt | 111 ------ .../executor/core/NetconfRpcServiceImplTest.kt | 124 ------- .../executor/mocks/NetconfDeviceSimulator.kt | 62 ---- .../executor/mocks/NetconfSubsystemFactory.kt | 125 ------- .../netconf/executor/utils/RpcMessageUtilsTest.kt | 306 ---------------- .../executor/ComponentNetconfExecutorTest.kt | 79 ++++ .../netconf/executor/NetconfSessionImplTest.kt | 111 ++++++ .../executor/core/NetconfRpcServiceImplTest.kt | 124 +++++++ .../executor/mocks/NetconfDeviceSimulator.kt | 62 ++++ .../executor/mocks/NetconfSubsystemFactory.kt | 125 +++++++ .../netconf/executor/utils/RpcMessageUtilsTest.kt | 306 ++++++++++++++++ .../src/test/resources/logback-test.xml | 2 +- ms/blueprintsprocessor/functions/pom.xml | 4 +- .../functions/python-executor/pom.xml | 4 +- .../python/executor/ComponentJythonExecutor.kt | 105 ------ .../python/executor/ComponentJythonExecutor.kt | 105 ++++++ .../python/executor/ComponentJythonExecutorTest.kt | 68 ---- .../executor/mock/MockInstanceConfiguration.kt | 32 -- .../python/executor/ComponentJythonExecutorTest.kt | 68 ++++ .../executor/mock/MockInstanceConfiguration.kt | 32 ++ .../src/test/resources/logback-test.xml | 2 +- .../functions/resource-resolution/pom.xml | 8 +- ...sourceAssignmentProcessorScriptConfiguration.kt | 42 --- .../resolution/ResourceAssignmentRuntimeService.kt | 88 ----- .../resolution/ResourceResolutionComponent.kt | 62 ---- .../resolution/ResourceResolutionConfiguration.kt | 26 -- .../resolution/ResourceResolutionConstants.kt | 31 -- .../resolution/ResourceResolutionService.kt | 228 ------------ .../resolution/ResourceSourceProperties.kt | 79 ---- .../resolution/db/ResourceResolutionRepository.kt | 25 -- .../resolution/db/ResourceResolutionResult.kt | 69 ---- .../db/ResourceResolutionResultService.kt | 64 ---- .../CapabilityResourceResolutionProcessor.kt | 104 ------ .../DatabaseResourceAssignmentProcessor.kt | 190 ---------- .../DefaultResourceResolutionProcessor.kt | 65 ---- .../processor/InputResourceResolutionProcessor.kt | 68 ---- .../processor/ResourceAssignmentProcessor.kt | 115 ------ .../processor/RestResourceResolutionProcessor.kt | 204 ----------- .../resolution/utils/ResourceAssignmentUtils.kt | 159 -------- ...sourceAssignmentProcessorScriptConfiguration.kt | 42 +++ .../resolution/ResourceAssignmentRuntimeService.kt | 88 +++++ .../resolution/ResourceResolutionComponent.kt | 62 ++++ .../resolution/ResourceResolutionConfiguration.kt | 26 ++ .../resolution/ResourceResolutionConstants.kt | 31 ++ .../resolution/ResourceResolutionService.kt | 228 ++++++++++++ .../resolution/ResourceSourceProperties.kt | 79 ++++ .../resolution/db/ResourceResolutionRepository.kt | 25 ++ .../resolution/db/ResourceResolutionResult.kt | 69 ++++ .../db/ResourceResolutionResultService.kt | 64 ++++ .../CapabilityResourceResolutionProcessor.kt | 104 ++++++ .../DatabaseResourceAssignmentProcessor.kt | 190 ++++++++++ .../DefaultResourceResolutionProcessor.kt | 65 ++++ .../processor/InputResourceResolutionProcessor.kt | 68 ++++ .../processor/ResourceAssignmentProcessor.kt | 115 ++++++ .../processor/RestResourceResolutionProcessor.kt | 204 +++++++++++ .../resolution/utils/ResourceAssignmentUtils.kt | 159 ++++++++ .../resolution/ResourceResolutionComponentTest.kt | 79 ---- .../resolution/ResourceResolutionServiceTest.kt | 91 ----- .../CapabilityResourceResolutionProcessorTest.kt | 126 ------- .../resolution/ResourceResolutionComponentTest.kt | 79 ++++ .../resolution/ResourceResolutionServiceTest.kt | 91 +++++ .../CapabilityResourceResolutionProcessorTest.kt | 126 +++++++ .../src/test/resources/logback-test.xml | 2 +- .../functions/restconf-executor/pom.xml | 6 +- .../restconf/executor/ComponentRestconfExecutor.kt | 73 ---- .../restconf/executor/RestconfComponentFunction.kt | 58 --- .../executor/RestconfExecutorConfiguration.kt | 29 -- .../restconf/executor/ComponentRestconfExecutor.kt | 73 ++++ .../restconf/executor/RestconfComponentFunction.kt | 58 +++ .../executor/RestconfExecutorConfiguration.kt | 29 ++ .../kotlin/scripts/InternalSimpleRestconf.cba.kts | 10 +- .../executor/ComponentRestconfExecutorTest.kt | 102 ------ .../executor/ComponentRestconfExecutorTest.kt | 102 ++++++ .../src/test/resources/logback-test.xml | 2 +- .../modules/commons/db-lib/pom.xml | 10 +- .../db/BluePrintDBLibConfiguration.kt | 56 --- .../blueprintsprocessor/db/BluePrintDBLibData.kt | 52 --- .../db/BluePrintDBLibGenericService.kt | 44 --- .../db/BlueprintProcessorCatalogServiceImpl.kt | 114 ------ .../db/primary/BluePrintDBLibPropertyService.kt | 105 ------ .../db/primary/MariaDatabaseConfiguration.kt | 59 --- .../db/primary/MySqlDatabaseConfiguration.kt | 55 --- .../db/primary/PrimaryDBLibGenericService.kt | 27 -- .../db/primary/PrimaryDatabaseConfiguration.kt | 82 ----- .../db/primary/domain/BlueprintProcessorModel.kt | 84 ----- .../domain/BlueprintProcessorModelContent.kt | 101 ------ .../BlueprintProcessorModelContentRepository.kt | 22 -- .../BlueprintProcessorModelRepository.kt | 21 -- .../db/BluePrintDBLibConfiguration.kt | 56 +++ .../blueprintsprocessor/db/BluePrintDBLibData.kt | 52 +++ .../db/BluePrintDBLibGenericService.kt | 44 +++ .../db/BlueprintProcessorCatalogServiceImpl.kt | 114 ++++++ .../db/primary/BluePrintDBLibPropertyService.kt | 105 ++++++ .../db/primary/MariaDatabaseConfiguration.kt | 59 +++ .../db/primary/MySqlDatabaseConfiguration.kt | 55 +++ .../db/primary/PrimaryDBLibGenericService.kt | 27 ++ .../db/primary/PrimaryDatabaseConfiguration.kt | 82 +++++ .../db/primary/domain/BlueprintProcessorModel.kt | 84 +++++ .../domain/BlueprintProcessorModelContent.kt | 101 ++++++ .../BlueprintProcessorModelContentRepository.kt | 22 ++ .../BlueprintProcessorModelRepository.kt | 21 ++ .../db/BlueprintProcessorCatalogServiceImplTest.kt | 52 --- .../db/primary/PrimaryDatabaseConfigurationTest.kt | 49 --- .../db/BlueprintProcessorCatalogServiceImplTest.kt | 52 +++ .../db/primary/PrimaryDatabaseConfigurationTest.kt | 49 +++ .../db-lib/src/test/resources/logback-test.xml | 2 +- .../modules/commons/dmaap-lib/pom.xml | 4 +- .../dmaap/AafAuthDmaapClientService.kt | 63 ---- .../dmaap/BluePrintDmaapClientService.kt | 102 ------ .../dmaap/BluePrintDmaapLibConfiguration.kt | 46 --- .../dmaap/BluePrintDmaapLibPropertyService.kt | 187 ---------- .../dmaap/DmaapClientProperties.kt | 46 --- .../dmaap/HttpNoAuthDmaapClientService.kt | 62 ---- .../dmaap/AafAuthDmaapClientService.kt | 63 ++++ .../dmaap/BluePrintDmaapClientService.kt | 102 ++++++ .../dmaap/BluePrintDmaapLibConfiguration.kt | 46 +++ .../dmaap/BluePrintDmaapLibPropertyService.kt | 187 ++++++++++ .../dmaap/DmaapClientProperties.kt | 46 +++ .../dmaap/HttpNoAuthDmaapClientService.kt | 62 ++++ .../dmaap/TestDmaapEventPublisher.kt | 215 ----------- .../dmaap/TestDmaapEventPublisher.kt | 215 +++++++++++ .../dmaap-lib/src/test/resources/logback-test.xml | 2 +- ms/blueprintsprocessor/modules/commons/pom.xml | 4 +- .../modules/commons/processor-core/pom.xml | 2 +- .../core/BluePrintCoreConfiguration.kt | 49 --- .../core/BluePrintProperties.kt | 29 -- .../core/api/data/BlueprintProcessorData.kt | 123 ------- .../core/factory/ComponentNodeFactory.kt | 68 ---- .../blueprintsprocessor/core/utils/PayloadUtils.kt | 47 --- .../core/BluePrintCoreConfiguration.kt | 49 +++ .../core/BluePrintProperties.kt | 29 ++ .../core/api/data/BlueprintProcessorData.kt | 123 +++++++ .../core/factory/ComponentNodeFactory.kt | 68 ++++ .../blueprintsprocessor/core/utils/PayloadUtils.kt | 47 +++ .../core/BluePrintPropertiesTest.kt | 20 - .../core/BluePrintPropertiesTest.kt | 20 + .../modules/commons/rest-lib/pom.xml | 6 +- .../rest/BluePrintRestLibConfiguration.kt | 39 -- .../rest/BluePrintRestLibData.kt | 55 --- .../rest/service/BasicAuthRestClientService.kt | 58 --- .../service/BluePrintRestLibPropertyService.kt | 129 ------- .../rest/service/BlueprintWebClientService.kt | 115 ------ .../rest/service/DME2ProxyRestClientService.kt | 29 -- .../rest/service/SSLBasicAuthRestClientService.kt | 72 ---- .../rest/service/TokenAuthRestClientService.kt | 47 --- .../rest/utils/WebClientUtils.kt | 35 -- .../rest/BluePrintRestLibConfiguration.kt | 39 ++ .../rest/BluePrintRestLibData.kt | 55 +++ .../rest/service/BasicAuthRestClientService.kt | 58 +++ .../service/BluePrintRestLibPropertyService.kt | 129 +++++++ .../rest/service/BlueprintWebClientService.kt | 115 ++++++ .../rest/service/DME2ProxyRestClientService.kt | 29 ++ .../rest/service/SSLBasicAuthRestClientService.kt | 72 ++++ .../rest/service/TokenAuthRestClientService.kt | 47 +++ .../rest/utils/WebClientUtils.kt | 35 ++ .../service/BluePrintRestLibPropertyServiceTest.kt | 58 --- .../rest/service/RestClientServiceTest.kt | 83 ----- .../service/BluePrintRestLibPropertyServiceTest.kt | 58 +++ .../rest/service/RestClientServiceTest.kt | 83 +++++ .../rest-lib/src/test/resources/logback-test.xml | 2 +- ms/blueprintsprocessor/modules/inbounds/pom.xml | 6 +- .../modules/inbounds/resource-api/pom.xml | 2 +- .../resource/api/ResourceResolutionController.java | 48 --- .../resource/api/ResourceResolutionController.java | 48 +++ .../api/ResourceResolutionControllerTest.java | 22 -- .../api/ResourceResolutionControllerTest.java | 22 ++ .../modules/inbounds/selfservice-api/pom.xml | 8 +- .../api/BluePrintManagementGRPCHandler.kt | 115 ------ .../api/BluePrintProcessingGRPCHandler.kt | 64 ---- .../selfservice/api/ExecutionServiceController.kt | 67 ---- .../selfservice/api/ExecutionServiceHandler.kt | 142 -------- .../selfservice/api/utils/BluePrintMappings.kt | 130 ------- .../selfservice/api/utils/Utils.kt | 59 --- .../validation/BluePrintRuntimeValidatorService.kt | 27 -- .../api/BluePrintManagementGRPCHandler.kt | 115 ++++++ .../api/BluePrintProcessingGRPCHandler.kt | 64 ++++ .../selfservice/api/ExecutionServiceController.kt | 67 ++++ .../selfservice/api/ExecutionServiceHandler.kt | 142 ++++++++ .../selfservice/api/utils/BluePrintMappings.kt | 130 +++++++ .../selfservice/api/utils/Utils.kt | 59 +++ .../validation/BluePrintRuntimeValidatorService.kt | 27 ++ .../api/BluePrintManagementGRPCHandlerTest.kt | 116 ------ .../api/BluePrintProcessingGRPCHandlerTest.kt | 124 ------- .../selfservice/api/ExecutionServiceHandlerTest.kt | 89 ----- .../selfservice/api/mock/Mock.kt | 62 ---- .../selfservice/api/utils/BluePrintMappingTests.kt | 132 ------- .../BluePrintRuntimeValidatorServiceTest.kt | 44 --- .../api/BluePrintManagementGRPCHandlerTest.kt | 116 ++++++ .../api/BluePrintProcessingGRPCHandlerTest.kt | 124 +++++++ .../selfservice/api/ExecutionServiceHandlerTest.kt | 89 +++++ .../selfservice/api/mock/Mock.kt | 62 ++++ .../selfservice/api/utils/BluePrintMappingTests.kt | 132 +++++++ .../BluePrintRuntimeValidatorServiceTest.kt | 44 +++ .../selfservice-api/src/test/resources/logback.xml | 2 +- ms/blueprintsprocessor/modules/outbounds/pom.xml | 2 +- ms/blueprintsprocessor/modules/pom.xml | 2 +- .../modules/services/execution-service/pom.xml | 16 +- .../execution/AbstractComponentFunction.kt | 148 -------- .../execution/AbstractScriptComponentFunction.kt | 50 --- .../execution/ComponentFunctionScriptingService.kt | 87 ----- .../execution/scripts/BlueprintJythonService.kt | 131 ------- .../execution/scripts/BlueprintPythonHost.kt | 46 --- .../scripts/BlueprintPythonInterpreterProxy.kt | 40 -- .../scripts/PythonExecutorConfiguration.kt | 68 ---- .../execution/AbstractComponentFunction.kt | 148 ++++++++ .../execution/AbstractScriptComponentFunction.kt | 50 +++ .../execution/ComponentFunctionScriptingService.kt | 87 +++++ .../execution/scripts/BlueprintJythonService.kt | 131 +++++++ .../execution/scripts/BlueprintPythonHost.kt | 46 +++ .../scripts/BlueprintPythonInterpreterProxy.kt | 40 ++ .../scripts/PythonExecutorConfiguration.kt | 68 ++++ .../scripts/BlueprintJythonServiceTest.kt | 57 --- .../scripts/BlueprintJythonServiceTest.kt | 57 +++ ms/blueprintsprocessor/modules/services/pom.xml | 2 +- .../modules/services/workflow-service/pom.xml | 6 +- .../BluePrintWorkflowExecutionServiceImpl.kt | 72 ---- .../services/workflow/BlueprintSvcLogicContext.kt | 52 --- .../services/workflow/BlueprintSvcLogicService.kt | 143 -------- .../workflow/ComponentWorkflowExecutionService.kt | 49 --- .../workflow/DGWorkflowExecutionService.kt | 70 ---- .../workflow/NodeTemplateExecutionService.kt | 72 ---- .../workflow/WorkflowServiceConfiguration.kt | 31 -- .../executor/ComponentExecuteNodeExecutor.kt | 69 ---- .../services/workflow/utils/SvcGraphUtils.kt | 35 -- .../BluePrintWorkflowExecutionServiceImpl.kt | 72 ++++ .../services/workflow/BlueprintSvcLogicContext.kt | 52 +++ .../services/workflow/BlueprintSvcLogicService.kt | 143 ++++++++ .../workflow/ComponentWorkflowExecutionService.kt | 49 +++ .../workflow/DGWorkflowExecutionService.kt | 70 ++++ .../workflow/NodeTemplateExecutionService.kt | 72 ++++ .../workflow/WorkflowServiceConfiguration.kt | 31 ++ .../executor/ComponentExecuteNodeExecutor.kt | 69 ++++ .../services/workflow/utils/SvcGraphUtils.kt | 35 ++ .../BluePrintWorkflowExecutionServiceImplTest.kt | 54 --- .../services/workflow/BlueprintServiceLogicTest.kt | 99 ----- .../workflow/DGWorkflowExecutionServiceTest.kt | 57 --- .../workflow/mock/MockComponentFunction.kt | 82 ----- .../BluePrintWorkflowExecutionServiceImplTest.kt | 54 +++ .../services/workflow/BlueprintServiceLogicTest.kt | 99 +++++ .../workflow/DGWorkflowExecutionServiceTest.kt | 57 +++ .../workflow/mock/MockComponentFunction.kt | 82 +++++ .../src/test/resources/logback.xml | 2 +- ms/blueprintsprocessor/parent/pom.xml | 42 +-- ms/blueprintsprocessor/pom.xml | 5 +- 311 files changed, 11316 insertions(+), 11315 deletions(-) delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintGRPCServer.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintHttpServer.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplication.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/SwaggerConfig.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/WebConfig.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/AuthenticationManager.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/BasicAuthServerInterceptor.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityConfiguration.java delete mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityContextRepository.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintHttpServer.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplication.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/SwaggerConfig.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/WebConfig.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/AuthenticationManager.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/BasicAuthServerInterceptor.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityConfiguration.java create mode 100644 ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityContextRepository.java delete mode 100644 ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplicationTest.java create mode 100644 ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplicationTest.java delete mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt delete mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt delete mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt create mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt create mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt create mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt delete mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt create mode 100644 ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt delete mode 100644 ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt create mode 100644 ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt delete mode 100644 ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt delete mode 100644 ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt create mode 100644 ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt create mode 100644 ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt delete mode 100755 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt create mode 100755 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt delete mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt create mode 100644 ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt delete mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt delete mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt delete mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt create mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt create mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt create mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt delete mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt create mode 100644 ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt delete mode 100755 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt delete mode 100755 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt create mode 100755 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt create mode 100755 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/DmaapClientProperties.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/apps/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt create mode 100644 ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintCoreConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintProperties.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/factory/ComponentNodeFactory.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/utils/PayloadUtils.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintProperties.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintPropertiesTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibData.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BlueprintWebClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/utils/WebClientUtils.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/RestClientServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionController.java create mode 100644 ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionController.java delete mode 100644 ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java create mode 100644 ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt delete mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt create mode 100644 ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt delete mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt create mode 100644 ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt (limited to 'ms/blueprintsprocessor') diff --git a/ms/blueprintsprocessor/application/pom.xml b/ms/blueprintsprocessor/application/pom.xml index 8757a0367..e7af4c852 100755 --- a/ms/blueprintsprocessor/application/pom.xml +++ b/ms/blueprintsprocessor/application/pom.xml @@ -20,7 +20,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor parent 0.4.2-SNAPSHOT ../parent @@ -32,7 +32,7 @@ - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core @@ -47,23 +47,23 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor resource-api - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions python-executor - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions netconf-executor - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions restconf-executor - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor selfservice-api diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintGRPCServer.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintGRPCServer.java deleted file mode 100644 index 3ac1a6e62..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintGRPCServer.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - -import io.grpc.Server; -import io.grpc.ServerBuilder; -import org.onap.ccsdk.apps.blueprintsprocessor.security.BasicAuthServerInterceptor; -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.BluePrintManagementGRPCHandler; -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.BluePrintProcessingGRPCHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -@ConditionalOnProperty(name = "blueprintsprocessor.grpcEnable", havingValue = "true") -@Component -public class BlueprintGRPCServer implements ApplicationListener { - - private static Logger log = LoggerFactory.getLogger(BlueprintGRPCServer.class); - - @Autowired - private BluePrintProcessingGRPCHandler bluePrintProcessingGRPCHandler; - @Autowired - private BluePrintManagementGRPCHandler bluePrintManagementGRPCHandler; - @Autowired - private BasicAuthServerInterceptor authInterceptor; - - @Value("${blueprintsprocessor.grpcPort}") - private Integer grpcPort; - - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - try { - log.info("Starting Blueprint Processor GRPC Starting.."); - Server server = ServerBuilder - .forPort(grpcPort) - .intercept(authInterceptor) - .addService(bluePrintProcessingGRPCHandler) - .addService(bluePrintManagementGRPCHandler) - .build(); - - server.start(); - log.info("Blueprint Processor GRPC server started and ready to serve on port({})...", server.getPort()); - server.awaitTermination(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintHttpServer.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintHttpServer.java deleted file mode 100644 index 9561b78d4..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintHttpServer.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; -import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory; -import org.springframework.boot.web.server.WebServer; -import org.springframework.http.server.reactive.HttpHandler; -import org.springframework.stereotype.Component; - -@Component -public class BlueprintHttpServer { - - private static Logger log = LoggerFactory.getLogger(BlueprintHttpServer.class); - - @Value("${blueprintsprocessor.httpPort}") - private Integer httpPort; - - @Autowired - HttpHandler httpHandler; - - WebServer http; - - @PostConstruct - public void start() { - ReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(httpPort); - this.http = factory.getWebServer(this.httpHandler); - this.http.start(); - } - - @PreDestroy - public void stop() { - this.http.stop(); - } -} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplication.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplication.java deleted file mode 100644 index 3f8dc375c..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplication.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.context.annotation.ComponentScan; - -/** - * BlueprintProcessorApplication - * - * @author Brinda Santh 8/14/2018 - */ -@SpringBootApplication -@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) -@ComponentScan(basePackages = {"org.onap.ccsdk.apps.controllerblueprints", - "org.onap.ccsdk.apps.blueprintsprocessor"}) -public class BlueprintProcessorApplication { - - public static void main(String[] args) { - SpringApplication.run(BlueprintProcessorApplication.class, args); - } -} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/SwaggerConfig.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/SwaggerConfig.java deleted file mode 100644 index 810480e96..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/SwaggerConfig.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - - -import org.springframework.context.annotation.Bean; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Contact; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; - -import java.util.Collections; - -/** - * SwaggerConfig - * - * @author Brinda Santh 8/13/2018 - */ -//@Configuration -//@EnableSwagger2 -@SuppressWarnings("unused") -@Deprecated -public class SwaggerConfig { - - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build() - .apiInfo(apiInfo()); - } - - private ApiInfo apiInfo() { - return new ApiInfo( - "Blueprints Processor API", - "Controller blueprints processor API for VNF Selfservice.", - "1.0.0", - "Terms of service", - new Contact("Brinda Santh", "www.onap.com", "bs2796@onap.com"), - "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", Collections.emptyList()); - } - - -} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/WebConfig.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/WebConfig.java deleted file mode 100644 index 47c7b7225..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/WebConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - -import org.onap.ccsdk.apps.blueprintsprocessor.security.AuthenticationManager; -import org.onap.ccsdk.apps.blueprintsprocessor.security.SecurityContextRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.config.web.server.ServerHttpSecurity; -import org.springframework.security.web.server.SecurityWebFilterChain; -import org.springframework.web.reactive.config.CorsRegistry; -import org.springframework.web.reactive.config.ResourceHandlerRegistry; -import org.springframework.web.reactive.config.WebFluxConfigurationSupport; - -/** - * WebConfig - * - * @author Brinda Santh 8/13/2018 - */ -@Configuration -public class WebConfig extends WebFluxConfigurationSupport { - - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private SecurityContextRepository securityContextRepository; - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html") - .addResourceLocations("classpath:/META-INF/resources/"); - - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); - } - - @Override - public void addCorsMappings(CorsRegistry corsRegistry) { - corsRegistry.addMapping("/**") - .allowedOrigins("*") - .allowedMethods("*") - .allowedHeaders("*") - .maxAge(3600); - } - - - @Bean - public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { - return http.csrf().disable() - .formLogin().disable() - .httpBasic().disable() - .authenticationManager(authenticationManager) - .securityContextRepository(securityContextRepository) - .authorizeExchange() - .pathMatchers(HttpMethod.OPTIONS).permitAll() - .anyExchange().authenticated() - .and().build(); - - } -} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/AuthenticationManager.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/AuthenticationManager.java deleted file mode 100644 index 726be2ce7..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/AuthenticationManager.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.security; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.ReactiveAuthenticationManager; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import reactor.core.publisher.Mono; - -@Configuration -public class AuthenticationManager implements ReactiveAuthenticationManager { - - @Autowired - private AuthenticationProvider authenticationProvider; - - @Override - public Mono authenticate(Authentication authentication) { - try { - return Mono.just(authenticationProvider.authenticate(authentication)); - } catch (AuthenticationException e) { - return Mono.error(e); - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/BasicAuthServerInterceptor.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/BasicAuthServerInterceptor.java deleted file mode 100644 index db0bfce46..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/BasicAuthServerInterceptor.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.security; - -import com.google.common.base.Strings; -import io.grpc.Metadata; -import io.grpc.ServerCall; -import io.grpc.ServerCallHandler; -import io.grpc.ServerInterceptor; -import io.grpc.Status; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Component; - -@Component -public class BasicAuthServerInterceptor implements ServerInterceptor { - - private static Logger log = LoggerFactory.getLogger(BasicAuthServerInterceptor.class); - - @Autowired - private AuthenticationManager authenticationManager; - - - @Override - public ServerCall.Listener interceptCall( - ServerCall call, - Metadata headers, - ServerCallHandler next) { - String authHeader = headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)); - - if (Strings.isNullOrEmpty(authHeader)) { - throw Status.UNAUTHENTICATED.withDescription("Missing required authentication").asRuntimeException(); - - } - - try { - String[] tokens = decodeBasicAuth(authHeader); - String username = tokens[0]; - - log.info("Basic Authentication Authorization header found for user: {}", username); - - Authentication authRequest = new UsernamePasswordAuthenticationToken(username, tokens[1]); - Authentication authResult = authenticationManager.authenticate(authRequest).block(); - - log.info("Authentication success: {}", authResult); - - SecurityContextHolder.getContext().setAuthentication(authResult); - - } catch (AuthenticationException e) { - SecurityContextHolder.clearContext(); - - log.info("Authentication request failed: {}", e.getMessage()); - - throw Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e).asRuntimeException(); - } - - return next.startCall(call, headers); - } - - private String[] decodeBasicAuth(String authHeader) { - String basicAuth; - try { - basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), - StandardCharsets.UTF_8); - } catch (IllegalArgumentException | IndexOutOfBoundsException e) { - throw new BadCredentialsException("Failed to decode basic authentication token"); - } - - int delim = basicAuth.indexOf(':'); - if (delim == -1) { - throw new BadCredentialsException("Failed to decode basic authentication token"); - } - - return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)}; - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityConfiguration.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityConfiguration.java deleted file mode 100644 index 7ddc42ccd..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityConfiguration.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.security; - -import java.util.Collections; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; - -@Configuration -public class SecurityConfiguration { - - @Value("${security.user.name}") - private String username; - - @Value("${security.user.password}") - private String password; - - @Bean - public UserDetailsService inMemoryUserService() { - UserDetails user = new User(username, password, - Collections.singletonList(new SimpleGrantedAuthority("USER"))); - return new InMemoryUserDetailsManager(user); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public AuthenticationProvider inMemoryAuthenticationProvider() { - DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); - provider.setUserDetailsService(inMemoryUserService()); - return provider; - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityContextRepository.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityContextRepository.java deleted file mode 100644 index f9e184a11..000000000 --- a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/security/SecurityContextRepository.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.security; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.server.reactive.ServerHttpRequest; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextImpl; -import org.springframework.security.web.server.context.ServerSecurityContextRepository; -import org.springframework.stereotype.Component; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -@Component -public class SecurityContextRepository implements ServerSecurityContextRepository { - - @Autowired - private AuthenticationManager authenticationManager; - - @Override - public Mono save(ServerWebExchange swe, SecurityContext sc) { - throw new UnsupportedOperationException("Not supported."); - } - - @Override - public Mono load(ServerWebExchange swe) { - ServerHttpRequest request = swe.getRequest(); - String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); - if (authHeader != null && authHeader.startsWith("Basic")) { - String[] tokens = decodeBasicAuth(authHeader); - String username = tokens[0]; - String password = tokens[1]; - Authentication auth = new UsernamePasswordAuthenticationToken(username, password); - return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new); - } else { - return Mono.empty(); - } - } - - private String[] decodeBasicAuth(String authHeader) { - String basicAuth; - try { - basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), - StandardCharsets.UTF_8); - } catch (IllegalArgumentException | IndexOutOfBoundsException e) { - throw new BadCredentialsException("Failed to decode basic authentication token"); - } - - int delim = basicAuth.indexOf(':'); - if (delim == -1) { - throw new BadCredentialsException("Failed to decode basic authentication token"); - } - - return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)}; - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.java new file mode 100644 index 000000000..16eb4182e --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintGRPCServer.java @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor; + +import io.grpc.Server; +import io.grpc.ServerBuilder; +import org.onap.ccsdk.cds.blueprintsprocessor.security.BasicAuthServerInterceptor; +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.BluePrintManagementGRPCHandler; +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.BluePrintProcessingGRPCHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@ConditionalOnProperty(name = "blueprintsprocessor.grpcEnable", havingValue = "true") +@Component +public class BlueprintGRPCServer implements ApplicationListener { + + private static Logger log = LoggerFactory.getLogger(BlueprintGRPCServer.class); + + @Autowired + private BluePrintProcessingGRPCHandler bluePrintProcessingGRPCHandler; + @Autowired + private BluePrintManagementGRPCHandler bluePrintManagementGRPCHandler; + @Autowired + private BasicAuthServerInterceptor authInterceptor; + + @Value("${blueprintsprocessor.grpcPort}") + private Integer grpcPort; + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + try { + log.info("Starting Blueprint Processor GRPC Starting.."); + Server server = ServerBuilder + .forPort(grpcPort) + .intercept(authInterceptor) + .addService(bluePrintProcessingGRPCHandler) + .addService(bluePrintManagementGRPCHandler) + .build(); + + server.start(); + log.info("Blueprint Processor GRPC server started and ready to serve on port({})...", server.getPort()); + server.awaitTermination(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintHttpServer.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintHttpServer.java new file mode 100644 index 000000000..ae75488c1 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintHttpServer.java @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; +import org.springframework.boot.web.reactive.server.ReactiveWebServerFactory; +import org.springframework.boot.web.server.WebServer; +import org.springframework.http.server.reactive.HttpHandler; +import org.springframework.stereotype.Component; + +@Component +public class BlueprintHttpServer { + + private static Logger log = LoggerFactory.getLogger(BlueprintHttpServer.class); + + @Value("${blueprintsprocessor.httpPort}") + private Integer httpPort; + + @Autowired + HttpHandler httpHandler; + + WebServer http; + + @PostConstruct + public void start() { + ReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(httpPort); + this.http = factory.getWebServer(this.httpHandler); + this.http.start(); + } + + @PreDestroy + public void stop() { + this.http.stop(); + } +} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplication.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplication.java new file mode 100644 index 000000000..85268c7fa --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplication.java @@ -0,0 +1,39 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; + +/** + * BlueprintProcessorApplication + * + * @author Brinda Santh 8/14/2018 + */ +@SpringBootApplication +@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) +@ComponentScan(basePackages = {"org.onap.ccsdk.cds.controllerblueprints", + "org.onap.ccsdk.cds.blueprintsprocessor"}) +public class BlueprintProcessorApplication { + + public static void main(String[] args) { + SpringApplication.run(BlueprintProcessorApplication.class, args); + } +} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/SwaggerConfig.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/SwaggerConfig.java new file mode 100644 index 000000000..8ad3c08f2 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/SwaggerConfig.java @@ -0,0 +1,63 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor; + + +import org.springframework.context.annotation.Bean; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + +import java.util.Collections; + +/** + * SwaggerConfig + * + * @author Brinda Santh 8/13/2018 + */ +//@Configuration +//@EnableSwagger2 +@SuppressWarnings("unused") +@Deprecated +public class SwaggerConfig { + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + private ApiInfo apiInfo() { + return new ApiInfo( + "Blueprints Processor API", + "Controller blueprints processor API for VNF Selfservice.", + "1.0.0", + "Terms of service", + new Contact("Brinda Santh", "www.onap.com", "bs2796@onap.com"), + "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", Collections.emptyList()); + } + + +} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/WebConfig.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/WebConfig.java new file mode 100644 index 000000000..b453b8581 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/WebConfig.java @@ -0,0 +1,78 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor; + +import org.onap.ccsdk.cds.blueprintsprocessor.security.AuthenticationManager; +import org.onap.ccsdk.cds.blueprintsprocessor.security.SecurityContextRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.web.reactive.config.CorsRegistry; +import org.springframework.web.reactive.config.ResourceHandlerRegistry; +import org.springframework.web.reactive.config.WebFluxConfigurationSupport; + +/** + * WebConfig + * + * @author Brinda Santh 8/13/2018 + */ +@Configuration +public class WebConfig extends WebFluxConfigurationSupport { + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private SecurityContextRepository securityContextRepository; + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + @Override + public void addCorsMappings(CorsRegistry corsRegistry) { + corsRegistry.addMapping("/**") + .allowedOrigins("*") + .allowedMethods("*") + .allowedHeaders("*") + .maxAge(3600); + } + + + @Bean + public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { + return http.csrf().disable() + .formLogin().disable() + .httpBasic().disable() + .authenticationManager(authenticationManager) + .securityContextRepository(securityContextRepository) + .authorizeExchange() + .pathMatchers(HttpMethod.OPTIONS).permitAll() + .anyExchange().authenticated() + .and().build(); + + } +} diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/AuthenticationManager.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/AuthenticationManager.java new file mode 100644 index 000000000..1eb0de498 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/AuthenticationManager.java @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and +* limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.ReactiveAuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import reactor.core.publisher.Mono; + +@Configuration +public class AuthenticationManager implements ReactiveAuthenticationManager { + + @Autowired + private AuthenticationProvider authenticationProvider; + + @Override + public Mono authenticate(Authentication authentication) { + try { + return Mono.just(authenticationProvider.authenticate(authentication)); + } catch (AuthenticationException e) { + return Mono.error(e); + } + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/BasicAuthServerInterceptor.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/BasicAuthServerInterceptor.java new file mode 100644 index 000000000..380ed3618 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/BasicAuthServerInterceptor.java @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.security; + +import com.google.common.base.Strings; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Component +public class BasicAuthServerInterceptor implements ServerInterceptor { + + private static Logger log = LoggerFactory.getLogger(BasicAuthServerInterceptor.class); + + @Autowired + private AuthenticationManager authenticationManager; + + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + String authHeader = headers.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)); + + if (Strings.isNullOrEmpty(authHeader)) { + throw Status.UNAUTHENTICATED.withDescription("Missing required authentication").asRuntimeException(); + + } + + try { + String[] tokens = decodeBasicAuth(authHeader); + String username = tokens[0]; + + log.info("Basic Authentication Authorization header found for user: {}", username); + + Authentication authRequest = new UsernamePasswordAuthenticationToken(username, tokens[1]); + Authentication authResult = authenticationManager.authenticate(authRequest).block(); + + log.info("Authentication success: {}", authResult); + + SecurityContextHolder.getContext().setAuthentication(authResult); + + } catch (AuthenticationException e) { + SecurityContextHolder.clearContext(); + + log.info("Authentication request failed: {}", e.getMessage()); + + throw Status.UNAUTHENTICATED.withDescription(e.getMessage()).withCause(e).asRuntimeException(); + } + + return next.startCall(call, headers); + } + + private String[] decodeBasicAuth(String authHeader) { + String basicAuth; + try { + basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), + StandardCharsets.UTF_8); + } catch (IllegalArgumentException | IndexOutOfBoundsException e) { + throw new BadCredentialsException("Failed to decode basic authentication token"); + } + + int delim = basicAuth.indexOf(':'); + if (delim == -1) { + throw new BadCredentialsException("Failed to decode basic authentication token"); + } + + return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)}; + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityConfiguration.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityConfiguration.java new file mode 100644 index 000000000..bd6469bba --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityConfiguration.java @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.security; + +import java.util.Collections; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; + +@Configuration +public class SecurityConfiguration { + + @Value("${security.user.name}") + private String username; + + @Value("${security.user.password}") + private String password; + + @Bean + public UserDetailsService inMemoryUserService() { + UserDetails user = new User(username, password, + Collections.singletonList(new SimpleGrantedAuthority("USER"))); + return new InMemoryUserDetailsManager(user); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + + @Bean + public AuthenticationProvider inMemoryAuthenticationProvider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(inMemoryUserService()); + return provider; + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityContextRepository.java b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityContextRepository.java new file mode 100644 index 000000000..75eebc5c3 --- /dev/null +++ b/ms/blueprintsprocessor/application/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/security/SecurityContextRepository.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.security; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextImpl; +import org.springframework.security.web.server.context.ServerSecurityContextRepository; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +@Component +public class SecurityContextRepository implements ServerSecurityContextRepository { + + @Autowired + private AuthenticationManager authenticationManager; + + @Override + public Mono save(ServerWebExchange swe, SecurityContext sc) { + throw new UnsupportedOperationException("Not supported."); + } + + @Override + public Mono load(ServerWebExchange swe) { + ServerHttpRequest request = swe.getRequest(); + String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); + if (authHeader != null && authHeader.startsWith("Basic")) { + String[] tokens = decodeBasicAuth(authHeader); + String username = tokens[0]; + String password = tokens[1]; + Authentication auth = new UsernamePasswordAuthenticationToken(username, password); + return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new); + } else { + return Mono.empty(); + } + } + + private String[] decodeBasicAuth(String authHeader) { + String basicAuth; + try { + basicAuth = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes(StandardCharsets.UTF_8)), + StandardCharsets.UTF_8); + } catch (IllegalArgumentException | IndexOutOfBoundsException e) { + throw new BadCredentialsException("Failed to decode basic authentication token"); + } + + int delim = basicAuth.indexOf(':'); + if (delim == -1) { + throw new BadCredentialsException("Failed to decode basic authentication token"); + } + + return new String[]{basicAuth.substring(0, delim), basicAuth.substring(delim + 1)}; + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/application/src/main/resources/logback.xml b/ms/blueprintsprocessor/application/src/main/resources/logback.xml index a97bb8c3d..48fc057fe 100644 --- a/ms/blueprintsprocessor/application/src/main/resources/logback.xml +++ b/ms/blueprintsprocessor/application/src/main/resources/logback.xml @@ -27,7 +27,7 @@ - + diff --git a/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplicationTest.java b/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplicationTest.java deleted file mode 100644 index 5777a28fc..000000000 --- a/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/BlueprintProcessorApplicationTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor; - - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * BlueprintProcessorApplicationTest - * - * @author Brinda Santh - * DATE : 8/14/2018 - */ - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = {BlueprintProcessorApplication.class, BluePrintLoadConfiguration.class}) -@SpringBootTest(classes = BlueprintProcessorApplication.class, - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class BlueprintProcessorApplicationTest { - - @Autowired - private ApplicationContext context; - - @Before - public void setUp() { - - } - - @Test - public void testSample() { - Assert.assertNotNull("Failed to create Application Context ", context); - } - -} diff --git a/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplicationTest.java b/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplicationTest.java new file mode 100644 index 000000000..90783d40f --- /dev/null +++ b/ms/blueprintsprocessor/application/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/BlueprintProcessorApplicationTest.java @@ -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.blueprintsprocessor; + + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * BlueprintProcessorApplicationTest + * + * @author Brinda Santh + * DATE : 8/14/2018 + */ + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {BlueprintProcessorApplication.class, BluePrintLoadConfiguration.class}) +@SpringBootTest(classes = BlueprintProcessorApplication.class, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class BlueprintProcessorApplicationTest { + + @Autowired + private ApplicationContext context; + + @Before + public void setUp() { + + } + + @Test + public void testSample() { + Assert.assertNotNull("Failed to create Application Context ", context); + } + +} diff --git a/ms/blueprintsprocessor/application/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/application/src/test/resources/logback-test.xml index a816a06c5..0c8d93bf0 100644 --- a/ms/blueprintsprocessor/application/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/application/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/distribution/pom.xml b/ms/blueprintsprocessor/distribution/pom.xml index 2bd16e5c0..0a9e4a93e 100755 --- a/ms/blueprintsprocessor/distribution/pom.xml +++ b/ms/blueprintsprocessor/distribution/pom.xml @@ -17,7 +17,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor parent 0.4.2-SNAPSHOT ../parent @@ -27,7 +27,7 @@ Blueprints Processor Distribution maven - org.onap.ccsdk.apps + org.onap.ccsdk.cds blueprintsprocessor onap/ccsdk-blueprintsprocessor ${https_proxy} @@ -39,7 +39,7 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor application diff --git a/ms/blueprintsprocessor/distribution/src/main/docker/run.source b/ms/blueprintsprocessor/distribution/src/main/docker/run.source index 7557ab126..e84dacd6b 100755 --- a/ms/blueprintsprocessor/distribution/src/main/docker/run.source +++ b/ms/blueprintsprocessor/distribution/src/main/docker/run.source @@ -4,9 +4,9 @@ java -classpath "/etc:${APP_HOME}/lib/*:/lib/*:/src:/schema:/generated-sources:$ -DVERSION_ROUTEOFFER_ENVCONTEXT=${BUNDLEVERSION}/${STICKYSELECTORKEY}/${ENVCONTEXT} \ -DSecurityFilePath=/etc \ -DREST_NAME_NORMALIZER_PATTERN_FILE=/etc/PatternInputs.txt \ --Dms_name=org.onap.ccsdk.apps.blueprintsprocessor \ +-Dms_name=org.onap.ccsdk.cds.blueprintsprocessor \ -Dlogging.config=${APP_CONFIG_HOME}/logback.xml \ -Djava.security.egd=file:/dev/./urandom \ -DAPPNAME=${APP_NAME} -DAPPENV=${APP_ENV} -DAPPVERSION=${APP_VERSION} -DNAMESPACE=${NAMESPACE} \ -Dspring.config.location=${APP_CONFIG_HOME}/ \ -org.onap.ccsdk.apps.blueprintsprocessor.BlueprintProcessorApplication +org.onap.ccsdk.cds.blueprintsprocessor.BlueprintProcessorApplication diff --git a/ms/blueprintsprocessor/functions/cli-executor/pom.xml b/ms/blueprintsprocessor/functions/cli-executor/pom.xml index 9077c13c6..77c45e76e 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/pom.xml +++ b/ms/blueprintsprocessor/functions/cli-executor/pom.xml @@ -17,7 +17,7 @@ functions - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor 0.4.2-SNAPSHOT 4.0.0 diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt deleted file mode 100644 index c26524959..000000000 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor - -import org.springframework.context.annotation.Configuration - -@Configuration -open class CliExecutorConfiguration \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt deleted file mode 100644 index 3c5c95886..000000000 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor.api - -interface CliExecutorService { - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt deleted file mode 100644 index 02a74fa0c..000000000 --- a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor.service - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor.api.CliExecutorService -import org.springframework.stereotype.Service - -@Service -open class CliExecutorServiceImpl : CliExecutorService { - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt new file mode 100644 index 000000000..f93020678 --- /dev/null +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/CliExecutorConfiguration.kt @@ -0,0 +1,22 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor + +import org.springframework.context.annotation.Configuration + +@Configuration +open class CliExecutorConfiguration \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt new file mode 100644 index 000000000..5ad671ba4 --- /dev/null +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/api/CliExecutorService.kt @@ -0,0 +1,22 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.api + +interface CliExecutorService { + + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt new file mode 100644 index 000000000..43047b38b --- /dev/null +++ b/ms/blueprintsprocessor/functions/cli-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImpl.kt @@ -0,0 +1,25 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.service + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.api.CliExecutorService +import org.springframework.stereotype.Service + +@Service +open class CliExecutorServiceImpl : CliExecutorService { + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt b/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt deleted file mode 100644 index 347aba794..000000000 --- a/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor.service - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.functions.cli.executor.api.CliExecutorService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [CliExecutorServiceImpl::class]) -class CliExecutorServiceImplTest { - - @Autowired - lateinit var cliExecutorService: CliExecutorService - - @Test - fun testCliExecutorService() { - assertNotNull(cliExecutorService, "failed to intilise cliExecutorService") - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt b/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt new file mode 100644 index 000000000..51dd62ceb --- /dev/null +++ b/ms/blueprintsprocessor/functions/cli-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/cli/executor/service/CliExecutorServiceImplTest.kt @@ -0,0 +1,38 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.service + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.functions.cli.executor.api.CliExecutorService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [CliExecutorServiceImpl::class]) +class CliExecutorServiceImplTest { + + @Autowired + lateinit var cliExecutorService: CliExecutorService + + @Test + fun testCliExecutorService() { + assertNotNull(cliExecutorService, "failed to intilise cliExecutorService") + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/cli-executor/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/functions/cli-executor/src/test/resources/logback-test.xml index 071c79431..626b8f911 100644 --- a/ms/blueprintsprocessor/functions/cli-executor/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/functions/cli-executor/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/functions/netconf-executor/pom.xml b/ms/blueprintsprocessor/functions/netconf-executor/pom.xml index 2e6d77edc..16ec6fbc1 100644 --- a/ms/blueprintsprocessor/functions/netconf-executor/pom.xml +++ b/ms/blueprintsprocessor/functions/netconf-executor/pom.xml @@ -16,19 +16,19 @@ --> - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor functions 0.4.2-SNAPSHOT 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions netconf-executor Blueprints Processor Function - Netconf Executor Blueprints Processor Function - Netconf Executor - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions resource-resolution diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt deleted file mode 100644 index c2ccdafd1..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor - -import com.fasterxml.jackson.databind.node.ArrayNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.apps.controllerblueprints.core.getAsString -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component - -@Component("component-netconf-executor") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class ComponentNetconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) - : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(ComponentNetconfExecutor::class.java) - - companion object { - const val SCRIPT_TYPE = "script-type" - const val SCRIPT_CLASS_REFERENCE = "script-class-reference" - const val INSTANCE_DEPENDENCIES = "instance-dependencies" - } - - - lateinit var scriptComponent: NetconfComponentFunction - - override fun process(executionRequest: ExecutionServiceInput) { - - val scriptType = operationInputs.getAsString(SCRIPT_TYPE) - val scriptClassReference = operationInputs.getAsString(SCRIPT_CLASS_REFERENCE) - val instanceDependenciesNode = operationInputs.get(INSTANCE_DEPENDENCIES) as? ArrayNode - - val scriptDependencies: MutableList = arrayListOf() - scriptDependencies.add(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) - - instanceDependenciesNode?.forEach { instanceName -> - scriptDependencies.add(instanceName.textValue()) - } - - scriptComponent = componentFunctionScriptingService.scriptInstance(this, scriptType, - scriptClassReference, scriptDependencies) - - - checkNotNull(scriptComponent) { "failed to get netconf script component" } - - scriptComponent.process(executionServiceInput) - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - scriptComponent.recover(runtimeException, executionRequest) - } - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt deleted file mode 100644 index 111736633..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor - -import org.springframework.stereotype.Service - -@Service("json-parser-service") -class JsonParserService { - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt deleted file mode 100644 index fe8ba54dd..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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.apps.blueprintsprocessor.functions.netconf.executor - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractScriptComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils - -abstract class NetconfComponentFunction : AbstractScriptComponentFunction() { - - open fun resourceResolutionService(): ResourceResolutionService = - functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) - - // Called from python script - fun initializeNetconfConnection(requirementName: String): NetconfDevice { - val deviceInfo = deviceProperties(requirementName) - return NetconfDevice(deviceInfo) - } - - fun generateMessage(artifactName: String): String { - return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - } - - fun resolveFromDatabase(resolutionKey: String, artifactName: String): String { - return resourceResolutionService().resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey) - } - - fun resolveAndGenerateMessage(artifactMapping: String, artifactTemplate: String): String { - return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, - artifactMapping, artifactTemplate) - } - - fun resolveAndGenerateMessage(artifactPrefix: String): String { - return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, - artifactPrefix, mapOf()) - } - - private fun deviceProperties(requirementName: String): DeviceInfo { - - val blueprintContext = bluePrintRuntimeService.bluePrintContext() - - val requirement = blueprintContext.nodeTemplateRequirement(nodeTemplateName, requirementName) - - val capabilityProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties(requirement - .node!!, requirement.capability!!) - - return deviceProperties(capabilityProperties) - } - - private fun deviceProperties(capabilityProperty: MutableMap): DeviceInfo { - return JacksonUtils.getInstanceFromMap(capabilityProperty, DeviceInfo::class.java) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt deleted file mode 100644 index 1c07c5e6c..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.functions.netconf.executor - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSession -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core.NetconfRpcServiceImpl -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core.NetconfSessionImpl - -data class NetconfDevice(val deviceInfo: DeviceInfo) { - val netconfRpcService = NetconfRpcServiceImpl(deviceInfo) - val netconfSession: NetconfSession - - init { - netconfSession = NetconfSessionImpl(deviceInfo, netconfRpcService) - netconfRpcService.setNetconfSession(netconfSession) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt deleted file mode 100644 index 466e6b5ed..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api - -import com.fasterxml.jackson.annotation.JsonIgnore -import com.fasterxml.jackson.annotation.JsonProperty - -class DeviceInfo { - @get:JsonProperty("login-account") - var username: String? = null - @get:JsonProperty("login-key") - var password: String? = null - @get:JsonProperty("target-ip-address") - var ipAddress: String? = null - @get:JsonProperty("port-number") - var port: Int = 0 - @get:JsonProperty("connection-time-out") - var connectTimeout: Long = 5 - @get:JsonIgnore - var source: String? = null - @get:JsonIgnore - var replyTimeout: Int = 5 - @get:JsonIgnore - var idleTimeout: Int = 99999 - - override fun toString(): String { - return "$ipAddress:$port" - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt deleted file mode 100644 index d7642e75f..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.api - -class NetconfException : Exception { - - constructor(cause: Throwable) : super(cause) - constructor(message: String) : super(message) - constructor(message: String, cause: Throwable) : super(message, cause) - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt deleted file mode 100644 index da7466143..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.api - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus - -class DeviceResponse { - var status: String? = null - var errorMessage: String? = null - var responseMessage: String? = null - var requestMessage: String? = null - private var subDeviceResponse: MutableMap? = null - - fun addSubDeviceResponse(key: String, subDeviceResponse: DeviceResponse) { - if (this.subDeviceResponse == null) { - this.subDeviceResponse = hashMapOf() - } - this.subDeviceResponse!![key] = subDeviceResponse - } - - fun isSuccess(): Boolean { - if (this.status != RpcStatus.SUCCESS && !this.errorMessage.isNullOrEmpty()) { - return false - } - return true - } -} - - -/** - * Creates an event of a given type and for the specified subject and the current time. - * - * @param type event type - * @param payload message from the device - * @param messageId id of the message related to the event - * @param deviceInfo device of event - */ -class NetconfReceivedEvent - (private var type: Type, private var payload: String = "", private var messageId: String = "", - private var deviceInfo: DeviceInfo) { - - enum class Type { - DEVICE_REPLY, - DEVICE_UNREGISTERED, - DEVICE_ERROR, - SESSION_CLOSED - } - - fun getType(): Type { - return type - } - - fun getMessagePayload(): String { - return payload - } - - fun getMessageID(): String { - return messageId - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt deleted file mode 100644 index 02c0a3426..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.ModifyAction -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfDatastore - -interface NetconfRpcService { - - /** - * Lock - * - * @param configTarget running or candidate, default candidate - * @return Device response - */ - fun lock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse - - /** - * Get-config - * - * @param filter filter content, default empty - * @param configTarget running or candidate, default running - * @return Device response - */ - fun getConfig(filter: String = "", configTarget: String = NetconfDatastore.RUNNING.datastore): DeviceResponse - - /** - * Delete config - * - * @param configTarget running or candidate, default candidate - * @return Device response - */ - fun deleteConfig(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse - - /** - * Edit-config - * - * @param messageContent edit config content. - * @param configTarget running or candidate, default candidate - * @param editDefaultOperation, default set to none. Valid values: merge, replace, create, delete, none - * @return Device response - */ - fun editConfig(messageContent: String, configTarget: String = NetconfDatastore.CANDIDATE.datastore, - editDefaultOperation: String = ModifyAction.NONE.action): DeviceResponse - - /** - * Invoke custom RPC as provided as input. - * - * Some use cases might required one to directly invoke a device - * specific RPC. The RPC must be correctly formatted. - * - * Ex: in order to rollback last submitted configuration - * for JUNOS devices, such RPC can be use: - * - * <rpc> - * <load-configuration rollback="1"/> - * </rpc> - * - * - * @param rpc the rpc content. - */ - fun invokeRpc(rpc: String): DeviceResponse - - /** - * Validate - * - * @param configTarget running or candidate, default candidate - * @return Device response - */ - fun validate(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse - - /** - * Commit - * - * @param confirmed Perform a confirmed operation. If flag set to true, - * then it is expected to have a follow-up operation to confirm the request - * @param confirmTimeout Timeout period for confirmed commit, in seconds. - * @param persist Make the confirmed commit survive a session termination, and - * set a token on the ongoing confirmed commit. - * @param persistId Used to issue a follow-up confirmed commit or a confirming - * commit from any session, with the token from the previous operation. - * If unspecified, the confirm timeout defaults to 600 seconds. - * @return Device response - */ - fun commit(confirmed: Boolean = false, confirmTimeout: Int = 60, persist: String = "", - persistId: String = ""): DeviceResponse - - /** - * Cancels an ongoing confirmed commit. If the parameter is not given, - * the operation MUST be issued on the same session that issued - * the confirmed commit. - * - * @param persistId Cancels a persistent confirmed commit. The value MUST be equal - * to the value given in the parameter to the operation. - * If the value does not match, the operation fails with an "invalid-value" error. - */ - fun cancelCommit(persistId: String = ""): DeviceResponse - - /** - * Unlock - * - * @param configTarget running or candidate, default candidate - * @return Device response - */ - fun unLock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse - - /** - * Discard config - * - * @return Device response - */ - fun discardConfig(): DeviceResponse - - /** - * Close session - * - * @param force force closeSession - * @return Device response - */ - fun closeSession(force: Boolean): DeviceResponse - - /** - * Executes an RPC request to the netconf server. - * - * @param request the XML containing the RPC request for the server. - * @return Device response - */ - fun asyncRpc(request: String, messageId: String): DeviceResponse -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt deleted file mode 100644 index 6a655d91f..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api - -import java.util.concurrent.CompletableFuture - -interface NetconfSession { - - /** - * Establish netconf session - */ - fun connect() - - - /** - * Disconnect netconf session - */ - fun disconnect() - - /** - * Reconnect netconf session - */ - fun reconnect() - - /** - * Executes an synchronous RPC request. - * - * @param request the XML request - * @param messageId message id of the request. - * @return Response - */ - @Throws(NetconfException::class) - fun syncRpc(request: String, messageId: String): String - - /** - * Executes an asynchronous RPC request. - * - * @param request the XML request - * @param messageId message id of the request. - * @return Response - */ - @Throws(NetconfException::class) - fun asyncRpc(request: String, messageId: String): CompletableFuture - - /** - * Checks the state of the underlying SSH session and connection and if necessary it reestablishes - * it. - */ - @Throws(NetconfException::class) - fun checkAndReestablish() - - /** - * Get the device information for initialised session. - * - * @return DeviceInfo as device information - */ - fun getDeviceInfo(): DeviceInfo - - /** - * Gets the session ID of the Netconf session. - * - * @return Session ID as a string. - */ - fun getSessionId(): String - - /** - * Gets the capabilities of the remote Netconf device associated to this session. - * - * @return Network capabilities as strings in a Set. - */ - fun getDeviceCapabilitiesSet(): Set -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt deleted file mode 100644 index 8854894fa..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.api - -interface NetconfSessionListener { - - fun notify(event: NetconfReceivedEvent) -} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt deleted file mode 100644 index 694756195..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.core - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils -import org.slf4j.LoggerFactory -import java.io.BufferedReader -import java.io.IOException -import java.io.InputStream -import java.io.InputStreamReader -import java.io.OutputStream -import java.io.OutputStreamWriter -import java.nio.charset.StandardCharsets -import java.util.concurrent.CompletableFuture - -class NetconfDeviceCommunicator(private var inputStream: InputStream, - private var out: OutputStream, - private val deviceInfo: DeviceInfo, - private val sessionListener: NetconfSessionListener, - private var replies: MutableMap>) : Thread() { - - private val log = LoggerFactory.getLogger(NetconfDeviceCommunicator::class.java) - private var state = NetconfMessageState.NO_MATCHING_PATTERN - - init { - start() - } - - override fun run() { - var bufferReader: BufferedReader? = null - while (bufferReader == null) { - bufferReader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) - } - - try { - var socketClosed = false - val deviceReplyBuilder = StringBuilder() - while (!socketClosed) { - val cInt = bufferReader.read() - if (cInt == -1) { - log.error("$deviceInfo: Received cInt = -1") -// bufferReader.close() - socketClosed = true -// sessionListener.notify(NetconfReceivedEvent( -// NetconfReceivedEvent.Type.SESSION_CLOSED, -// deviceInfo = deviceInfo)) - } - val c = cInt.toChar() - state = state.evaluateChar(c) - deviceReplyBuilder.append(c) - if (state === NetconfMessageState.END_PATTERN) { - var deviceReply = deviceReplyBuilder.toString() - if (deviceReply == RpcMessageUtils.END_PATTERN) { - socketClosed = true - bufferReader.close() - sessionListener.notify(NetconfReceivedEvent( - NetconfReceivedEvent.Type.DEVICE_UNREGISTERED, - deviceInfo = deviceInfo)) - } else { - deviceReply = deviceReply.replace(RpcMessageUtils.END_PATTERN, "") - receivedMessage(deviceReply) - deviceReplyBuilder.setLength(0) - } - } else if (state === NetconfMessageState.END_CHUNKED_PATTERN) { - var deviceReply = deviceReplyBuilder.toString() - if (!NetconfMessageUtils.validateChunkedFraming(deviceReply)) { - log.debug("$deviceInfo: Received badly framed message $deviceReply") - socketClosed = true - sessionListener.notify(NetconfReceivedEvent( - NetconfReceivedEvent.Type.DEVICE_ERROR, - deviceInfo = deviceInfo)) - } else { - deviceReply = deviceReply.replace(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex(), "") - deviceReply = deviceReply.replace(NetconfMessageUtils.CHUNKED_END_REGEX_PATTERN.toRegex(), "") - receivedMessage(deviceReply) - deviceReplyBuilder.setLength(0) - } - } - } - - } catch (e: IOException) { - log.warn("$deviceInfo: Fail while reading from channel", e) - sessionListener.notify(NetconfReceivedEvent( - NetconfReceivedEvent.Type.DEVICE_ERROR, - deviceInfo = deviceInfo)) - } - - } - - private enum class NetconfMessageState { - NO_MATCHING_PATTERN { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == ']') { - FIRST_BRACKET - } else if (c == '\n') { - FIRST_LF - } else { - this - } - } - }, - FIRST_BRACKET { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == ']') { - SECOND_BRACKET - } else { - NO_MATCHING_PATTERN - } - } - }, - SECOND_BRACKET { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == '>') { - FIRST_BIGGER - } else { - NO_MATCHING_PATTERN - } - } - }, - FIRST_BIGGER { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == ']') { - THIRD_BRACKET - } else { - NO_MATCHING_PATTERN - } - } - }, - THIRD_BRACKET { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == ']') { - ENDING_BIGGER - } else { - NO_MATCHING_PATTERN - } - } - }, - ENDING_BIGGER { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == '>') { - END_PATTERN - } else { - NO_MATCHING_PATTERN - } - } - }, - FIRST_LF { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == '#') { - FIRST_HASH - } else if (c == ']') { - FIRST_BRACKET - } else if (c == '\n') { - this - } else { - NO_MATCHING_PATTERN - } - } - }, - FIRST_HASH { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == '#') { - SECOND_HASH - } else { - NO_MATCHING_PATTERN - } - } - }, - SECOND_HASH { - override fun evaluateChar(c: Char): NetconfMessageState { - return if (c == '\n') { - END_CHUNKED_PATTERN - } else { - NO_MATCHING_PATTERN - } - } - }, - END_CHUNKED_PATTERN { - override fun evaluateChar(c: Char): NetconfMessageState { - return NO_MATCHING_PATTERN - } - }, - END_PATTERN { - override fun evaluateChar(c: Char): NetconfMessageState { - return NO_MATCHING_PATTERN - } - }; - - internal abstract fun evaluateChar(c: Char): NetconfMessageState - } - - fun sendMessage(request: String, messageId: String): CompletableFuture { - log.info("$deviceInfo: Sending message: \n $request") - val future = CompletableFuture() - replies.put(messageId, future) - val outputStream = OutputStreamWriter(out, StandardCharsets.UTF_8) - synchronized(this) { - try { - outputStream.write(request) - outputStream.flush() - } catch (e: IOException) { - log.error("$deviceInfo: Failed to send message : \n $request", e) - future.completeExceptionally(e) - } - - } - return future - } - - private fun receivedMessage(deviceReply: String) { - if (deviceReply.contains(RpcMessageUtils.RPC_REPLY) || deviceReply.contains(RpcMessageUtils.RPC_ERROR) - || deviceReply.contains(RpcMessageUtils.HELLO)) { - log.info("$deviceInfo: Received message with messageId: {} \n $deviceReply", - NetconfMessageUtils.getMsgId(deviceReply)) - - } else { - log.error("$deviceInfo: Invalid message received: \n $deviceReply") - } - sessionListener.notify(NetconfReceivedEvent( - NetconfReceivedEvent.Type.DEVICE_REPLY, - deviceReply, - NetconfMessageUtils.getMsgId(deviceReply), - deviceInfo)) - } -} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt deleted file mode 100644 index 15fb3122c..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.core - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceResponse -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfException -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSession -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus -import org.slf4j.LoggerFactory -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicInteger - -class NetconfRpcServiceImpl(private var deviceInfo: DeviceInfo) : NetconfRpcService { - - private val log = LoggerFactory.getLogger(NetconfRpcService::class.java) - - private var responseTimeout: Int = deviceInfo.replyTimeout - - private lateinit var netconfSession: NetconfSession - - private val messageIdInteger = AtomicInteger(1) - - fun setNetconfSession(netconfSession: NetconfSession) { - this.netconfSession = netconfSession - } - - override fun invokeRpc(rpc: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: invokeRpc: messageId($messageId)") - try { - output = asyncRpc(rpc, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in invokeRpc command $e.message" - } - return output - } - - override fun getConfig(filter: String, configTarget: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: getConfig: messageId($messageId)") - try { - val message = NetconfMessageUtils.getConfig(messageId, configTarget, filter) - output = asyncRpc(message, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in get-config command $e.message" - } - return output - } - - override fun deleteConfig(configTarget: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: deleteConfig: messageId($messageId)") - try { - val deleteConfigMessage = NetconfMessageUtils.deleteConfig(messageId, configTarget) - output.requestMessage = deleteConfigMessage - output = asyncRpc(deleteConfigMessage, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in delete config command $e.message" - } - return output - } - - override fun lock(configTarget: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: lock: messageId($messageId)") - try { - val lockMessage = NetconfMessageUtils.lock(messageId, configTarget) - output.requestMessage = lockMessage - output = asyncRpc(lockMessage, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in lock command $e.message" - } - - return output - } - - override fun unLock(configTarget: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: unLock: messageId($messageId)") - try { - val unlockMessage = NetconfMessageUtils.unlock(messageId, configTarget) - output.requestMessage = unlockMessage - output = asyncRpc(unlockMessage, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in lock command $e.message" - } - return output - } - - override fun commit(confirmed: Boolean, confirmTimeout: Int, persist: String, persistId: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: commit: messageId($messageId)") - try { - val messageContent = NetconfMessageUtils.commit(messageId, confirmed, confirmTimeout, persist, persistId) - output = asyncRpc(messageContent, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in commit command $e.message" - } - return output - } - - override fun cancelCommit(persistId: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: cancelCommit: messageId($messageId)") - try { - val messageContent = NetconfMessageUtils.cancelCommit(messageId, persistId) - output = asyncRpc(messageContent, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in cancelCommit command $e.message" - } - return output - } - - override fun discardConfig(): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: discard: messageId($messageId)") - try { - val discardChangesMessage = NetconfMessageUtils.discardChanges(messageId) - output.requestMessage = discardChangesMessage - output = asyncRpc(discardChangesMessage, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in discard changes command " + e.message - } - return output - } - - override fun editConfig(messageContent: String, configTarget: String, - editDefaultOperation: String): DeviceResponse { - var response = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: editConfig: messageId($messageId)") - try { - val editMessage = - NetconfMessageUtils.editConfig(messageId, configTarget, editDefaultOperation, messageContent) - response.requestMessage = editMessage - response = asyncRpc(editMessage, messageId) - } catch (e: Exception) { - response.status = RpcStatus.FAILURE - response.errorMessage = e.message - } - return response - } - - override fun validate(configTarget: String): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - try { - val validateMessage = NetconfMessageUtils.validate(messageId, configTarget) - output.requestMessage = validateMessage - output = asyncRpc(validateMessage, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in validate command " + e.message - } - return output - } - - override fun closeSession(force: Boolean): DeviceResponse { - var output = DeviceResponse() - val messageId = messageIdInteger.getAndIncrement().toString() - log.info("$deviceInfo: closeSession: messageId($messageId)") - try { - val messageContent = NetconfMessageUtils.closeSession(messageId, force) - output = asyncRpc(messageContent, messageId) - } catch (e: Exception) { - output.status = RpcStatus.FAILURE - output.errorMessage = "$deviceInfo: failed in closeSession command " + e.message - } - return output - } - - @Throws(NetconfException::class) - override fun asyncRpc(request: String, messageId: String): DeviceResponse { - val response = DeviceResponse() - log.info("$deviceInfo: send asyncRpc with messageId($messageId)") - response.requestMessage = request - - val rpcResponse = netconfSession.asyncRpc(request, messageId).get(responseTimeout.toLong(), TimeUnit.SECONDS) - if (!NetconfMessageUtils.checkReply(rpcResponse)) { - throw NetconfException(rpcResponse) - } - response.responseMessage = rpcResponse - response.status = RpcStatus.SUCCESS - response.errorMessage = null - return response - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt deleted file mode 100644 index 2dd73ef18..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.core - -import com.google.common.collect.ImmutableList -import com.google.common.collect.ImmutableSet -import org.apache.sshd.client.SshClient -import org.apache.sshd.client.channel.ChannelSubsystem -import org.apache.sshd.client.channel.ClientChannel -import org.apache.sshd.client.session.ClientSession -import org.apache.sshd.client.session.ClientSessionImpl -import org.apache.sshd.common.FactoryManager -import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfException -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSession -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus -import org.slf4j.LoggerFactory -import java.io.IOException -import java.util.* -import java.util.concurrent.CompletableFuture -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.ExecutionException -import java.util.concurrent.TimeUnit -import java.util.concurrent.TimeoutException -import java.util.concurrent.atomic.AtomicReference - -class NetconfSessionImpl(private val deviceInfo: DeviceInfo, private val rpcService: NetconfRpcService) : - NetconfSession { - - private val log = LoggerFactory.getLogger(NetconfSessionImpl::class.java) - - private val errorReplies: MutableList = Collections.synchronizedList(listOf()) - private val replies: MutableMap> = ConcurrentHashMap() - private val deviceCapabilities = setOf() - - private var connectionTimeout: Long = 0 - private var replyTimeout: Int = 0 - private var idleTimeout: Int = 0 - private var sessionId: String? = null - - private lateinit var session: ClientSession - private lateinit var client: SshClient - private lateinit var channel: ClientChannel - private lateinit var streamHandler: NetconfDeviceCommunicator - - private var capabilities = - ImmutableList.of(RpcMessageUtils.NETCONF_10_CAPABILITY, RpcMessageUtils.NETCONF_11_CAPABILITY) - - override fun connect() { - try { - log.info("$deviceInfo: Connecting to Netconf Device with timeouts C:${deviceInfo.connectTimeout}, " + - "R:${deviceInfo.replyTimeout}, I:${deviceInfo.idleTimeout}") - startConnection() - log.info("$deviceInfo: Connected to Netconf Device") - } catch (e: NetconfException) { - log.error("$deviceInfo: Netconf Device Connection Failed. ${e.message}") - throw NetconfException(e) - } - } - - override fun disconnect() { - if (rpcService.closeSession(false).status.equals( - RpcStatus.FAILURE, true)) { - rpcService.closeSession(true) - } - - session.close() - // Closes the socket which should interrupt the streamHandler - channel.close() - client.close() - } - - override fun reconnect() { - disconnect() - connect() - } - - override fun syncRpc(request: String, messageId: String): String { - val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities) - - checkAndReestablish() - - try { - return streamHandler.sendMessage(formattedRequest, messageId).get(replyTimeout.toLong(), TimeUnit.SECONDS) -// replies.remove(messageId) - } catch (e: InterruptedException) { - Thread.currentThread().interrupt() - throw NetconfException("$deviceInfo: Interrupted while waiting for reply for request: $formattedRequest", e) - } catch (e: TimeoutException) { - throw NetconfException("$deviceInfo: Timed out while waiting for reply for request $formattedRequest after $replyTimeout sec.", - e) - } catch (e: ExecutionException) { - log.warn("$deviceInfo: Closing session($sessionId) due to unexpected Error", e) - try { - session.close() - // Closes the socket which should interrupt the streamHandler - channel.close() - client.close() - } catch (ioe: IOException) { - log.warn("$deviceInfo: Error closing session($sessionId) for host($deviceInfo)", ioe) - } - -// NetconfReceivedEvent(NetconfReceivedEvent.Type.SESSION_CLOSED, "", -// "Closed due to unexpected error " + e.cause, "-1", deviceInfo) - errorReplies.clear() // move to cleanUp()? - replies.clear() - - throw NetconfException("$deviceInfo: Closing session $sessionId for request $formattedRequest", e) - } - } - - override fun asyncRpc(request: String, messageId: String): CompletableFuture { - val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities) - - checkAndReestablish() - - return streamHandler.sendMessage(formattedRequest, messageId).handleAsync { reply, t -> - if (t != null) { - throw NetconfException(messageId, t) - } - reply - } - } - - override fun checkAndReestablish() { - try { - if (client.isClosed) { - log.info("Trying to restart the whole SSH connection with {}", deviceInfo) - replies.clear() - startConnection() - } else if (session.isClosed) { - log.info("Trying to restart the session with {}", deviceInfo) - replies.clear() - startSession() - } else if (channel.isClosed) { - log.info("Trying to reopen the channel with {}", deviceInfo) - replies.clear() - openChannel() - } else { - return - } - } catch (e: IOException) { - log.error("Can't reopen connection for device {}", e.message) - throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e) - } catch (e: IllegalStateException) { - log.error("Can't reopen connection for device {}", e.message) - throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e) - } - - } - - override fun getDeviceInfo(): DeviceInfo { - return deviceInfo - } - - override fun getSessionId(): String { - return this.sessionId!! - } - - override fun getDeviceCapabilitiesSet(): Set { - return Collections.unmodifiableSet(deviceCapabilities) - } - - private fun startConnection() { - connectionTimeout = deviceInfo.connectTimeout - replyTimeout = deviceInfo.replyTimeout - idleTimeout = deviceInfo.idleTimeout - try { - startClient() - } catch (e: Exception) { - throw NetconfException("$deviceInfo: Failed to establish SSH session", e) - } - - } - - private fun startClient() { - client = SshClient.setUpDefaultClient() - client.properties.putIfAbsent(FactoryManager.IDLE_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout.toLong())) - client.properties.putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout + 15L)) - client.keyPairProvider = SimpleGeneratorHostKeyProvider() - client.start() - - startSession() - } - - private fun startSession() { - log.info("$deviceInfo: Starting SSH session") - val connectFuture = client.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port) - .verify(connectionTimeout, TimeUnit.SECONDS) - session = connectFuture.session - log.info("$deviceInfo: SSH session created") - - authSession() - } - - private fun authSession() { - session.addPasswordIdentity(deviceInfo.password) - session.auth().verify(connectionTimeout, TimeUnit.SECONDS) - val event = session.waitFor(ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, - ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0) - if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) { - throw NetconfException("$deviceInfo: Failed to authenticate session.") - } - log.info("$deviceInfo: SSH session authenticated") - - openChannel() - } - - private fun openChannel() { - channel = session.createSubsystemChannel("netconf") - val channelFuture = channel.open() - if (channelFuture.await(connectionTimeout, TimeUnit.SECONDS) && channelFuture.isOpened) { - log.info("$deviceInfo: SSH NETCONF subsystem channel opened") - setupHandler() - } else { - throw NetconfException("$deviceInfo: Failed to open SSH subsystem channel") - } - } - - private fun setupHandler() { - val sessionListener: NetconfSessionListener = NetconfSessionListenerImpl() - streamHandler = NetconfDeviceCommunicator(channel.invertedOut, channel.invertedIn, deviceInfo, - sessionListener, replies) - - exchangeHelloMessage() - } - - private fun exchangeHelloMessage() { - sessionId = "-1" - val messageId = "-1" - - val serverHelloResponse = syncRpc(NetconfMessageUtils.createHelloString(capabilities), messageId) - val sessionIDMatcher = NetconfMessageUtils.SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse) - - if (sessionIDMatcher.find()) { - sessionId = sessionIDMatcher.group(1) - } else { - throw NetconfException("$deviceInfo: Missing sessionId in server hello message: $serverHelloResponse") - } - - val capabilityMatcher = NetconfMessageUtils.CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse) - while (capabilityMatcher.find()) { - deviceCapabilities.plus(capabilityMatcher.group(1)) - } - } - - inner class NetconfSessionListenerImpl : NetconfSessionListener { - override fun notify(event: NetconfReceivedEvent) { - val messageId = event.getMessageID() - - when (event.getType()) { - NetconfReceivedEvent.Type.DEVICE_UNREGISTERED -> disconnect() - NetconfReceivedEvent.Type.DEVICE_ERROR -> errorReplies.add(event.getMessagePayload()) - NetconfReceivedEvent.Type.DEVICE_REPLY -> replies[messageId]?.complete(event.getMessagePayload()) - NetconfReceivedEvent.Type.SESSION_CLOSED -> disconnect() - } - } - } - - fun sessionstatus(state:String): Boolean{ - return when (state){ - "Close" -> channel.isClosed - "Open" -> channel.isOpen - else -> false - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt deleted file mode 100644 index 3b3b0c025..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.utils - -enum class NetconfDatastore(val datastore: String) { - RUNNING("running"), - CANDIDATE("candidate"); -} - -enum class ModifyAction(val action: String) { - MERGE("merge"), - REPLACE("replace"), - NONE("none") -} - -object RpcStatus { - const val SUCCESS = "success" - const val FAILURE = "failure" -} - -object RpcMessageUtils { - const val OPEN = "<" - const val CLOSE = ">" - const val EQUAL = "=" - - const val HASH = "#" - const val HASH_CHAR = '#' - - const val LF_CHAR = '\n' - const val NEW_LINE = "\n" - - const val QUOTE = "\"" - const val QUOTE_SPACE = "\" " - - const val TAG_CLOSE = "/>" - const val END_OF_RPC_OPEN_TAG = "\">" - const val END_PATTERN = "]]>]]>" - - const val HELLO = "hello" - const val RPC_REPLY = "rpc-reply" - const val RPC_ERROR = "rpc-error" - - const val RPC_OPEN = "" - const val SUBTREE_FILTER_CLOSE = "" - const val TARGET_OPEN = "" - const val TARGET_CLOSE = "" - const val SOURCE_OPEN = "" - const val SOURCE_CLOSE = "" - const val CONFIG_OPEN = "" - const val CONFIG_CLOSE = "" - const val MSGLEN_REGEX_PATTERN = "\n#\\d+\n" - - const val NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"" - - const val XML_HEADER = "" - const val NETCONF_BASE_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" - const val NETCONF_WITH_DEFAULTS_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"" - const val SUBSCRIPTION_SUBTREE_FILTER_OPEN = - "" - - const val INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0" - - const val CAPABILITY_REGEX = "capability>\\s*(.*?)\\s*capability>" - - const val SESSION_ID_REGEX = "session-id>\\s*(.*?)\\s*session-id>" - - const val MESSAGE_ID_STRING = "message-id" - - const val NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0" - const val NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1" -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt deleted file mode 100644 index 4de3860c5..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.functions.netconf.executor.utils - -import org.apache.commons.lang3.StringUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfException -import org.slf4j.LoggerFactory -import org.xml.sax.InputSource -import java.io.StringReader -import java.nio.charset.StandardCharsets -import java.util.regex.MatchResult -import java.util.regex.Pattern -import javax.xml.XMLConstants -import javax.xml.parsers.DocumentBuilderFactory -import kotlin.text.Charsets.UTF_8 - - -class NetconfMessageUtils { - - companion object { - val log = LoggerFactory.getLogger(NetconfMessageUtils::class.java) - - const val NEW_LINE = "\n" - const val CHUNKED_END_REGEX_PATTERN = "\n##\n" - - val CAPABILITY_REGEX_PATTERN: Pattern = Pattern.compile(RpcMessageUtils.CAPABILITY_REGEX) - val SESSION_ID_REGEX_PATTERN: Pattern = Pattern.compile(RpcMessageUtils.SESSION_ID_REGEX) - - private val CHUNKED_FRAMING_PATTERN: Pattern = - Pattern.compile("(\\n#([1-9][0-9]*)\\n(.+))+\\n##\\n", Pattern.DOTALL) - private val CHUNKED_SIZE_PATTERN: Pattern = Pattern.compile("\\n#([1-9][0-9]*)\\n") - private val MSG_ID_STRING_PATTERN = Pattern.compile("${RpcMessageUtils.MESSAGE_ID_STRING}=\"(.*?)\"") - - fun getConfig(messageId: String, configType: String, filterContent: String?): String { - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.SOURCE_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.SOURCE_CLOSE).append(NEW_LINE) - - if (!filterContent.isNullOrEmpty()) { - request.append(RpcMessageUtils.SUBTREE_FILTER_OPEN).append(NEW_LINE) - request.append(filterContent).append(NEW_LINE) - request.append(RpcMessageUtils.SUBTREE_FILTER_CLOSE).append(NEW_LINE) - } - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun doWrappedRpc(messageId: String, request: String): String { - val rpc = StringBuilder(RpcMessageUtils.XML_HEADER).append(NEW_LINE) - rpc.append(RpcMessageUtils.RPC_OPEN) - rpc.append(RpcMessageUtils.MESSAGE_ID_STRING).append(RpcMessageUtils.EQUAL) - rpc.append(RpcMessageUtils.QUOTE).append(messageId).append(RpcMessageUtils.QUOTE_SPACE) - rpc.append(RpcMessageUtils.NETCONF_BASE_NAMESPACE).append(RpcMessageUtils.CLOSE) - .append(NEW_LINE) - rpc.append(request) - rpc.append(RpcMessageUtils.RPC_CLOSE) - // rpc.append(NEW_LINE).append(END_PATTERN); - - return rpc.toString() - } - - fun editConfig(messageId: String, configType: String, defaultOperation: String?, - newConfiguration: String): String { - - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) - - if (defaultOperation != null) { - request.append(RpcMessageUtils.DEFAULT_OPERATION_OPEN).append(defaultOperation) - .append(RpcMessageUtils.DEFAULT_OPERATION_CLOSE) - request.append(NEW_LINE) - } - - request.append(RpcMessageUtils.CONFIG_OPEN).append(NEW_LINE) - request.append(newConfiguration.trim { it <= ' ' }).append(NEW_LINE) - request.append(RpcMessageUtils.CONFIG_CLOSE).append(NEW_LINE) - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun validate(messageId: String, configType: String): String { - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.SOURCE_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.SOURCE_CLOSE).append(NEW_LINE) - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun commit(messageId: String, confirmed: Boolean, confirmTimeout: Int, persist: String, - persistId: String): String { - - if (!persist.isEmpty() && !persistId.isEmpty()) { - throw NetconfException("Can't proceed with both persist($persist) and " + - "persistId($persistId) specified. Only one should be specified.") - } - if (confirmed && !persistId.isEmpty()) { - throw NetconfException("Can't proceed with both confirmed flag and " + - "persistId($persistId) specified. Only one should be specified.") - } - - val request = StringBuilder() - request.append("").append(NEW_LINE) - if (confirmed) { - request.append("") - request.append("$confirmTimeout") - if (!persist.isEmpty()) { - request.append("$persist") - } - } - if (!persistId.isEmpty()) { - request.append("$persistId") - } - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun cancelCommit(messageId: String, persistId: String): String { - val request = StringBuilder() - request.append("").append(NEW_LINE) - if (!persistId.isEmpty()) { - request.append("$persistId") - } - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun unlock(messageId: String, configType: String): String { - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - @Throws(NetconfException::class) - fun deleteConfig(messageId: String, configType: String): String { - if (configType == NetconfDatastore.RUNNING.datastore) { - log.warn("Target configuration for delete operation can't be \"running\" {}", configType) - throw NetconfException("Target configuration for delete operation can't be running") - } - - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType) - .append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun discardChanges(messageId: String): String { - val request = StringBuilder() - request.append("").append(NEW_LINE) - return doWrappedRpc(messageId, request.toString()) - } - - fun lock(messageId: String, configType: String): String { - val request = StringBuilder() - - request.append("").append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) - request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) - .append(NEW_LINE) - request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) - request.append("").append(NEW_LINE) - - return doWrappedRpc(messageId, request.toString()) - } - - fun closeSession(messageId: String, force: Boolean): String { - val request = StringBuilder() - - if (force) { - request.append("").append(NEW_LINE) - } else { - request.append("").append(NEW_LINE) - } - - return doWrappedRpc(messageId, request.toString()) - } - - fun validateRPCXML(rpcRequest: String): Boolean { - try { - if (StringUtils.isBlank(rpcRequest)) { - return false - } - val dbf = DocumentBuilderFactory.newInstance() - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) - dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) - dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false) - dbf.newDocumentBuilder() - .parse(InputSource(StringReader(rpcRequest.replace(RpcMessageUtils.END_PATTERN, "")))) - return true - } catch (e: Exception) { - return false - } - - } - - fun getMsgId(message: String): String { - val matcher = MSG_ID_STRING_PATTERN.matcher(message) - if (matcher.find()) { - return matcher.group(1) - } - return if (message.contains(RpcMessageUtils.HELLO)) { - (-1).toString() - } else "" - } - - fun validateChunkedFraming(reply: String): Boolean { - val matcher = CHUNKED_FRAMING_PATTERN.matcher(reply) - if (!matcher.matches()) { - log.debug("Error Reply: {}", reply) - return false - } - val chunkM = CHUNKED_SIZE_PATTERN.matcher(reply) - val chunks = ArrayList() - var chunkdataStr = "" - while (chunkM.find()) { - chunks.add(chunkM.toMatchResult()) - // extract chunk-data (and later) in bytes - val bytes = Integer.parseInt(chunkM.group(1)) - val chunkdata = reply.substring(chunkM.end()).toByteArray(StandardCharsets.UTF_8) - if (bytes > chunkdata.size) { - log.debug("Error Reply - wrong chunk size {}", reply) - return false - } - // convert (only) chunk-data part into String - chunkdataStr = String(chunkdata, 0, bytes, StandardCharsets.UTF_8) - // skip chunk-data part from next match - chunkM.region(chunkM.end() + chunkdataStr.length, reply.length) - } - if (!CHUNKED_END_REGEX_PATTERN.equals(reply.substring(chunks[chunks.size - 1].end() + chunkdataStr.length))) { - log.debug("Error Reply: {}", reply) - return false - } - return true - } - - fun createHelloString(capabilities: List): String { - val helloMessage = StringBuilder() - helloMessage.append(RpcMessageUtils.XML_HEADER).append(NEW_LINE) - helloMessage.append("").append(NEW_LINE) - helloMessage.append(" ").append(NEW_LINE) - if (capabilities.isNotEmpty()) { - capabilities.forEach { cap -> - helloMessage.append(" ").append(cap).append("").append(NEW_LINE) - } - } - helloMessage.append(" ").append(NEW_LINE) - helloMessage.append("").append(NEW_LINE) - helloMessage.append(RpcMessageUtils.END_PATTERN) - return helloMessage.toString() - } - - fun formatRPCRequest(request: String, messageId: String, deviceCapabilities: Set): String { - var request = request - request = NetconfMessageUtils.formatNetconfMessage(deviceCapabilities, request) - request = NetconfMessageUtils.formatXmlHeader(request) - request = NetconfMessageUtils.formatRequestMessageId(request, messageId) - - return request - } - - /** - * Validate and format netconf message. - NC1.0 if no EOM sequence present on `message`, - * append. - NC1.1 chunk-encode given message unless it already is chunk encoded - * - * @param deviceCapabilities Set containing Device Capabilities - * @param message to format - * @return formated message - */ - fun formatNetconfMessage(deviceCapabilities: Set, message: String): String { - var message = message - if (deviceCapabilities.contains(RpcMessageUtils.NETCONF_11_CAPABILITY)) { - message = formatChunkedMessage(message) - } else if (!message.endsWith(RpcMessageUtils.END_PATTERN)) { - message = message + NEW_LINE + RpcMessageUtils.END_PATTERN - } - return message - } - - /** - * Validate and format message according to chunked framing mechanism. - * - * @param message to format - * @return formated message - */ - fun formatChunkedMessage(message: String): String { - var message = message - if (message.endsWith(RpcMessageUtils.END_PATTERN)) { - // message given had Netconf 1.0 EOM pattern -> remove - message = message.substring(0, message.length - RpcMessageUtils.END_PATTERN.length) - } - if (!message.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) { - // chunk encode message - message = - (RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + message.toByteArray(UTF_8).size + RpcMessageUtils.NEW_LINE + message + RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH - + RpcMessageUtils.NEW_LINE) - } - return message - } - - /** - * Ensures xml start directive/declaration appears in the `request`. - * - * @param request RPC request message - * @return XML RPC message - */ - fun formatXmlHeader(request: String): String { - var request = request - if (!request.contains(RpcMessageUtils.XML_HEADER)) { - if (request.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) { - request = - request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] + RpcMessageUtils.XML_HEADER + request.substring( - request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].length) - } else { - request = RpcMessageUtils.XML_HEADER + "\n" + request - } - } - return request - } - - fun formatRequestMessageId(request: String, messageId: String): String { - var request = request - if (request.contains(RpcMessageUtils.MESSAGE_ID_STRING)) { - request = - request.replaceFirst((RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.NUMBER_BETWEEN_QUOTES_MATCHER).toRegex(), - RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE) - } else if (!request.contains(RpcMessageUtils.MESSAGE_ID_STRING) && !request.contains( - RpcMessageUtils.HELLO)) { - request = request.replaceFirst(RpcMessageUtils.END_OF_RPC_OPEN_TAG.toRegex(), - RpcMessageUtils.QUOTE_SPACE + RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE + ">") - } - return updateRequestLength(request) - } - - fun updateRequestLength(request: String): String { - if (request.contains(NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE)) { - val oldLen = - Integer.parseInt(request.split(RpcMessageUtils.HASH.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split( - NEW_LINE.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0]) - val rpcWithEnding = request.substring(request.indexOf('<')) - val firstBlock = - request.split(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split( - (NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE).toRegex()).dropLastWhile( - { it.isEmpty() }).toTypedArray()[0] - var newLen = 0 - newLen = firstBlock.toByteArray(UTF_8).size - if (oldLen != newLen) { - return NEW_LINE + RpcMessageUtils.HASH + newLen + NEW_LINE + rpcWithEnding - } - } - return request - } - - fun checkReply(reply: String?): Boolean { - return if (reply != null) { - !reply.contains("rpc-error>") || reply.contains("warning") || reply.contains("ok/>") - } else false - } - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt new file mode 100644 index 000000000..2980de98a --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutor.kt @@ -0,0 +1,75 @@ +/* + * 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.blueprintsprocessor.functions.netconf.executor + +import com.fasterxml.jackson.databind.node.ArrayNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService +import org.onap.ccsdk.cds.controllerblueprints.core.getAsString +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component + +@Component("component-netconf-executor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class ComponentNetconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) + : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(ComponentNetconfExecutor::class.java) + + companion object { + const val SCRIPT_TYPE = "script-type" + const val SCRIPT_CLASS_REFERENCE = "script-class-reference" + const val INSTANCE_DEPENDENCIES = "instance-dependencies" + } + + + lateinit var scriptComponent: NetconfComponentFunction + + override fun process(executionRequest: ExecutionServiceInput) { + + val scriptType = operationInputs.getAsString(SCRIPT_TYPE) + val scriptClassReference = operationInputs.getAsString(SCRIPT_CLASS_REFERENCE) + val instanceDependenciesNode = operationInputs.get(INSTANCE_DEPENDENCIES) as? ArrayNode + + val scriptDependencies: MutableList = arrayListOf() + scriptDependencies.add(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) + + instanceDependenciesNode?.forEach { instanceName -> + scriptDependencies.add(instanceName.textValue()) + } + + scriptComponent = componentFunctionScriptingService.scriptInstance(this, scriptType, + scriptClassReference, scriptDependencies) + + + checkNotNull(scriptComponent) { "failed to get netconf script component" } + + scriptComponent.process(executionServiceInput) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + scriptComponent.recover(runtimeException, executionRequest) + } + + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt new file mode 100644 index 000000000..73c82acb2 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/JsonParserService.kt @@ -0,0 +1,24 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor + +import org.springframework.stereotype.Service + +@Service("json-parser-service") +class JsonParserService { + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt new file mode 100644 index 000000000..4b08ce8e2 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfComponentFunction.kt @@ -0,0 +1,70 @@ +/* + * 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.blueprintsprocessor.functions.netconf.executor + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils + +abstract class NetconfComponentFunction : AbstractScriptComponentFunction() { + + open fun resourceResolutionService(): ResourceResolutionService = + functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) + + // Called from python script + fun initializeNetconfConnection(requirementName: String): NetconfDevice { + val deviceInfo = deviceProperties(requirementName) + return NetconfDevice(deviceInfo) + } + + fun generateMessage(artifactName: String): String { + return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) + } + + fun resolveFromDatabase(resolutionKey: String, artifactName: String): String { + return resourceResolutionService().resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey) + } + + fun resolveAndGenerateMessage(artifactMapping: String, artifactTemplate: String): String { + return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, + artifactMapping, artifactTemplate) + } + + fun resolveAndGenerateMessage(artifactPrefix: String): String { + return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, + artifactPrefix, mapOf()) + } + + private fun deviceProperties(requirementName: String): DeviceInfo { + + val blueprintContext = bluePrintRuntimeService.bluePrintContext() + + val requirement = blueprintContext.nodeTemplateRequirement(nodeTemplateName, requirementName) + + val capabilityProperties = bluePrintRuntimeService.resolveNodeTemplateCapabilityProperties(requirement + .node!!, requirement.capability!!) + + return deviceProperties(capabilityProperties) + } + + private fun deviceProperties(capabilityProperty: MutableMap): DeviceInfo { + return JacksonUtils.getInstanceFromMap(capabilityProperty, DeviceInfo::class.java) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt new file mode 100644 index 000000000..61090f485 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfDevice.kt @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSession +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core.NetconfRpcServiceImpl +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core.NetconfSessionImpl + +data class NetconfDevice(val deviceInfo: DeviceInfo) { + val netconfRpcService = NetconfRpcServiceImpl(deviceInfo) + val netconfSession: NetconfSession + + init { + netconfSession = NetconfSessionImpl(deviceInfo, netconfRpcService) + netconfRpcService.setNetconfSession(netconfSession) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt new file mode 100644 index 000000000..5eeaf6046 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/DeviceInfo.kt @@ -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.blueprintsprocessor.functions.netconf.executor.api + +import com.fasterxml.jackson.annotation.JsonIgnore +import com.fasterxml.jackson.annotation.JsonProperty + +class DeviceInfo { + @get:JsonProperty("login-account") + var username: String? = null + @get:JsonProperty("login-key") + var password: String? = null + @get:JsonProperty("target-ip-address") + var ipAddress: String? = null + @get:JsonProperty("port-number") + var port: Int = 0 + @get:JsonProperty("connection-time-out") + var connectTimeout: Long = 5 + @get:JsonIgnore + var source: String? = null + @get:JsonIgnore + var replyTimeout: Int = 5 + @get:JsonIgnore + var idleTimeout: Int = 99999 + + override fun toString(): String { + return "$ipAddress:$port" + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt new file mode 100644 index 000000000..7e6a88b48 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfException.kt @@ -0,0 +1,24 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api + +class NetconfException : Exception { + + constructor(cause: Throwable) : super(cause) + constructor(message: String) : super(message) + constructor(message: String, cause: Throwable) : super(message, cause) + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt new file mode 100644 index 000000000..ef3605c66 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfMessage.kt @@ -0,0 +1,74 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus + +class DeviceResponse { + var status: String? = null + var errorMessage: String? = null + var responseMessage: String? = null + var requestMessage: String? = null + private var subDeviceResponse: MutableMap? = null + + fun addSubDeviceResponse(key: String, subDeviceResponse: DeviceResponse) { + if (this.subDeviceResponse == null) { + this.subDeviceResponse = hashMapOf() + } + this.subDeviceResponse!![key] = subDeviceResponse + } + + fun isSuccess(): Boolean { + if (this.status != RpcStatus.SUCCESS && !this.errorMessage.isNullOrEmpty()) { + return false + } + return true + } +} + + +/** + * Creates an event of a given type and for the specified subject and the current time. + * + * @param type event type + * @param payload message from the device + * @param messageId id of the message related to the event + * @param deviceInfo device of event + */ +class NetconfReceivedEvent + (private var type: Type, private var payload: String = "", private var messageId: String = "", + private var deviceInfo: DeviceInfo) { + + enum class Type { + DEVICE_REPLY, + DEVICE_UNREGISTERED, + DEVICE_ERROR, + SESSION_CLOSED + } + + fun getType(): Type { + return type + } + + fun getMessagePayload(): String { + return payload + } + + fun getMessageID(): String { + return messageId + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt new file mode 100644 index 000000000..60345b5a6 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfRpcService.kt @@ -0,0 +1,142 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.ModifyAction +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfDatastore + +interface NetconfRpcService { + + /** + * Lock + * + * @param configTarget running or candidate, default candidate + * @return Device response + */ + fun lock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse + + /** + * Get-config + * + * @param filter filter content, default empty + * @param configTarget running or candidate, default running + * @return Device response + */ + fun getConfig(filter: String = "", configTarget: String = NetconfDatastore.RUNNING.datastore): DeviceResponse + + /** + * Delete config + * + * @param configTarget running or candidate, default candidate + * @return Device response + */ + fun deleteConfig(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse + + /** + * Edit-config + * + * @param messageContent edit config content. + * @param configTarget running or candidate, default candidate + * @param editDefaultOperation, default set to none. Valid values: merge, replace, create, delete, none + * @return Device response + */ + fun editConfig(messageContent: String, configTarget: String = NetconfDatastore.CANDIDATE.datastore, + editDefaultOperation: String = ModifyAction.NONE.action): DeviceResponse + + /** + * Invoke custom RPC as provided as input. + * + * Some use cases might required one to directly invoke a device + * specific RPC. The RPC must be correctly formatted. + * + * Ex: in order to rollback last submitted configuration + * for JUNOS devices, such RPC can be use: + * + * <rpc> + * <load-configuration rollback="1"/> + * </rpc> + * + * + * @param rpc the rpc content. + */ + fun invokeRpc(rpc: String): DeviceResponse + + /** + * Validate + * + * @param configTarget running or candidate, default candidate + * @return Device response + */ + fun validate(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse + + /** + * Commit + * + * @param confirmed Perform a confirmed operation. If flag set to true, + * then it is expected to have a follow-up operation to confirm the request + * @param confirmTimeout Timeout period for confirmed commit, in seconds. + * @param persist Make the confirmed commit survive a session termination, and + * set a token on the ongoing confirmed commit. + * @param persistId Used to issue a follow-up confirmed commit or a confirming + * commit from any session, with the token from the previous operation. + * If unspecified, the confirm timeout defaults to 600 seconds. + * @return Device response + */ + fun commit(confirmed: Boolean = false, confirmTimeout: Int = 60, persist: String = "", + persistId: String = ""): DeviceResponse + + /** + * Cancels an ongoing confirmed commit. If the parameter is not given, + * the operation MUST be issued on the same session that issued + * the confirmed commit. + * + * @param persistId Cancels a persistent confirmed commit. The value MUST be equal + * to the value given in the parameter to the operation. + * If the value does not match, the operation fails with an "invalid-value" error. + */ + fun cancelCommit(persistId: String = ""): DeviceResponse + + /** + * Unlock + * + * @param configTarget running or candidate, default candidate + * @return Device response + */ + fun unLock(configTarget: String = NetconfDatastore.CANDIDATE.datastore): DeviceResponse + + /** + * Discard config + * + * @return Device response + */ + fun discardConfig(): DeviceResponse + + /** + * Close session + * + * @param force force closeSession + * @return Device response + */ + fun closeSession(force: Boolean): DeviceResponse + + /** + * Executes an RPC request to the netconf server. + * + * @param request the XML containing the RPC request for the server. + * @return Device response + */ + fun asyncRpc(request: String, messageId: String): DeviceResponse +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt new file mode 100644 index 000000000..0272d1a19 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSession.kt @@ -0,0 +1,86 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api + +import java.util.concurrent.CompletableFuture + +interface NetconfSession { + + /** + * Establish netconf session + */ + fun connect() + + + /** + * Disconnect netconf session + */ + fun disconnect() + + /** + * Reconnect netconf session + */ + fun reconnect() + + /** + * Executes an synchronous RPC request. + * + * @param request the XML request + * @param messageId message id of the request. + * @return Response + */ + @Throws(NetconfException::class) + fun syncRpc(request: String, messageId: String): String + + /** + * Executes an asynchronous RPC request. + * + * @param request the XML request + * @param messageId message id of the request. + * @return Response + */ + @Throws(NetconfException::class) + fun asyncRpc(request: String, messageId: String): CompletableFuture + + /** + * Checks the state of the underlying SSH session and connection and if necessary it reestablishes + * it. + */ + @Throws(NetconfException::class) + fun checkAndReestablish() + + /** + * Get the device information for initialised session. + * + * @return DeviceInfo as device information + */ + fun getDeviceInfo(): DeviceInfo + + /** + * Gets the session ID of the Netconf session. + * + * @return Session ID as a string. + */ + fun getSessionId(): String + + /** + * Gets the capabilities of the remote Netconf device associated to this session. + * + * @return Network capabilities as strings in a Set. + */ + fun getDeviceCapabilitiesSet(): Set +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt new file mode 100644 index 000000000..cfdd0104c --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/api/NetconfSessionListener.kt @@ -0,0 +1,21 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api + +interface NetconfSessionListener { + + fun notify(event: NetconfReceivedEvent) +} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt new file mode 100644 index 000000000..4199998a8 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfDeviceCommunicator.kt @@ -0,0 +1,243 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils +import org.slf4j.LoggerFactory +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStream +import java.io.InputStreamReader +import java.io.OutputStream +import java.io.OutputStreamWriter +import java.nio.charset.StandardCharsets +import java.util.concurrent.CompletableFuture + +class NetconfDeviceCommunicator(private var inputStream: InputStream, + private var out: OutputStream, + private val deviceInfo: DeviceInfo, + private val sessionListener: NetconfSessionListener, + private var replies: MutableMap>) : Thread() { + + private val log = LoggerFactory.getLogger(NetconfDeviceCommunicator::class.java) + private var state = NetconfMessageState.NO_MATCHING_PATTERN + + init { + start() + } + + override fun run() { + var bufferReader: BufferedReader? = null + while (bufferReader == null) { + bufferReader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8)) + } + + try { + var socketClosed = false + val deviceReplyBuilder = StringBuilder() + while (!socketClosed) { + val cInt = bufferReader.read() + if (cInt == -1) { + log.error("$deviceInfo: Received cInt = -1") +// bufferReader.close() + socketClosed = true +// sessionListener.notify(NetconfReceivedEvent( +// NetconfReceivedEvent.Type.SESSION_CLOSED, +// deviceInfo = deviceInfo)) + } + val c = cInt.toChar() + state = state.evaluateChar(c) + deviceReplyBuilder.append(c) + if (state === NetconfMessageState.END_PATTERN) { + var deviceReply = deviceReplyBuilder.toString() + if (deviceReply == RpcMessageUtils.END_PATTERN) { + socketClosed = true + bufferReader.close() + sessionListener.notify(NetconfReceivedEvent( + NetconfReceivedEvent.Type.DEVICE_UNREGISTERED, + deviceInfo = deviceInfo)) + } else { + deviceReply = deviceReply.replace(RpcMessageUtils.END_PATTERN, "") + receivedMessage(deviceReply) + deviceReplyBuilder.setLength(0) + } + } else if (state === NetconfMessageState.END_CHUNKED_PATTERN) { + var deviceReply = deviceReplyBuilder.toString() + if (!NetconfMessageUtils.validateChunkedFraming(deviceReply)) { + log.debug("$deviceInfo: Received badly framed message $deviceReply") + socketClosed = true + sessionListener.notify(NetconfReceivedEvent( + NetconfReceivedEvent.Type.DEVICE_ERROR, + deviceInfo = deviceInfo)) + } else { + deviceReply = deviceReply.replace(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex(), "") + deviceReply = deviceReply.replace(NetconfMessageUtils.CHUNKED_END_REGEX_PATTERN.toRegex(), "") + receivedMessage(deviceReply) + deviceReplyBuilder.setLength(0) + } + } + } + + } catch (e: IOException) { + log.warn("$deviceInfo: Fail while reading from channel", e) + sessionListener.notify(NetconfReceivedEvent( + NetconfReceivedEvent.Type.DEVICE_ERROR, + deviceInfo = deviceInfo)) + } + + } + + private enum class NetconfMessageState { + NO_MATCHING_PATTERN { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == ']') { + FIRST_BRACKET + } else if (c == '\n') { + FIRST_LF + } else { + this + } + } + }, + FIRST_BRACKET { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == ']') { + SECOND_BRACKET + } else { + NO_MATCHING_PATTERN + } + } + }, + SECOND_BRACKET { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == '>') { + FIRST_BIGGER + } else { + NO_MATCHING_PATTERN + } + } + }, + FIRST_BIGGER { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == ']') { + THIRD_BRACKET + } else { + NO_MATCHING_PATTERN + } + } + }, + THIRD_BRACKET { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == ']') { + ENDING_BIGGER + } else { + NO_MATCHING_PATTERN + } + } + }, + ENDING_BIGGER { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == '>') { + END_PATTERN + } else { + NO_MATCHING_PATTERN + } + } + }, + FIRST_LF { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == '#') { + FIRST_HASH + } else if (c == ']') { + FIRST_BRACKET + } else if (c == '\n') { + this + } else { + NO_MATCHING_PATTERN + } + } + }, + FIRST_HASH { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == '#') { + SECOND_HASH + } else { + NO_MATCHING_PATTERN + } + } + }, + SECOND_HASH { + override fun evaluateChar(c: Char): NetconfMessageState { + return if (c == '\n') { + END_CHUNKED_PATTERN + } else { + NO_MATCHING_PATTERN + } + } + }, + END_CHUNKED_PATTERN { + override fun evaluateChar(c: Char): NetconfMessageState { + return NO_MATCHING_PATTERN + } + }, + END_PATTERN { + override fun evaluateChar(c: Char): NetconfMessageState { + return NO_MATCHING_PATTERN + } + }; + + internal abstract fun evaluateChar(c: Char): NetconfMessageState + } + + fun sendMessage(request: String, messageId: String): CompletableFuture { + log.info("$deviceInfo: Sending message: \n $request") + val future = CompletableFuture() + replies.put(messageId, future) + val outputStream = OutputStreamWriter(out, StandardCharsets.UTF_8) + synchronized(this) { + try { + outputStream.write(request) + outputStream.flush() + } catch (e: IOException) { + log.error("$deviceInfo: Failed to send message : \n $request", e) + future.completeExceptionally(e) + } + + } + return future + } + + private fun receivedMessage(deviceReply: String) { + if (deviceReply.contains(RpcMessageUtils.RPC_REPLY) || deviceReply.contains(RpcMessageUtils.RPC_ERROR) + || deviceReply.contains(RpcMessageUtils.HELLO)) { + log.info("$deviceInfo: Received message with messageId: {} \n $deviceReply", + NetconfMessageUtils.getMsgId(deviceReply)) + + } else { + log.error("$deviceInfo: Invalid message received: \n $deviceReply") + } + sessionListener.notify(NetconfReceivedEvent( + NetconfReceivedEvent.Type.DEVICE_REPLY, + deviceReply, + NetconfMessageUtils.getMsgId(deviceReply), + deviceInfo)) + } +} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt new file mode 100644 index 000000000..4619460e3 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImpl.kt @@ -0,0 +1,220 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceResponse +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSession +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus +import org.slf4j.LoggerFactory +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +class NetconfRpcServiceImpl(private var deviceInfo: DeviceInfo) : NetconfRpcService { + + private val log = LoggerFactory.getLogger(NetconfRpcService::class.java) + + private var responseTimeout: Int = deviceInfo.replyTimeout + + private lateinit var netconfSession: NetconfSession + + private val messageIdInteger = AtomicInteger(1) + + fun setNetconfSession(netconfSession: NetconfSession) { + this.netconfSession = netconfSession + } + + override fun invokeRpc(rpc: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: invokeRpc: messageId($messageId)") + try { + output = asyncRpc(rpc, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in invokeRpc command $e.message" + } + return output + } + + override fun getConfig(filter: String, configTarget: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: getConfig: messageId($messageId)") + try { + val message = NetconfMessageUtils.getConfig(messageId, configTarget, filter) + output = asyncRpc(message, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in get-config command $e.message" + } + return output + } + + override fun deleteConfig(configTarget: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: deleteConfig: messageId($messageId)") + try { + val deleteConfigMessage = NetconfMessageUtils.deleteConfig(messageId, configTarget) + output.requestMessage = deleteConfigMessage + output = asyncRpc(deleteConfigMessage, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in delete config command $e.message" + } + return output + } + + override fun lock(configTarget: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: lock: messageId($messageId)") + try { + val lockMessage = NetconfMessageUtils.lock(messageId, configTarget) + output.requestMessage = lockMessage + output = asyncRpc(lockMessage, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in lock command $e.message" + } + + return output + } + + override fun unLock(configTarget: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: unLock: messageId($messageId)") + try { + val unlockMessage = NetconfMessageUtils.unlock(messageId, configTarget) + output.requestMessage = unlockMessage + output = asyncRpc(unlockMessage, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in lock command $e.message" + } + return output + } + + override fun commit(confirmed: Boolean, confirmTimeout: Int, persist: String, persistId: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: commit: messageId($messageId)") + try { + val messageContent = NetconfMessageUtils.commit(messageId, confirmed, confirmTimeout, persist, persistId) + output = asyncRpc(messageContent, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in commit command $e.message" + } + return output + } + + override fun cancelCommit(persistId: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: cancelCommit: messageId($messageId)") + try { + val messageContent = NetconfMessageUtils.cancelCommit(messageId, persistId) + output = asyncRpc(messageContent, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in cancelCommit command $e.message" + } + return output + } + + override fun discardConfig(): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: discard: messageId($messageId)") + try { + val discardChangesMessage = NetconfMessageUtils.discardChanges(messageId) + output.requestMessage = discardChangesMessage + output = asyncRpc(discardChangesMessage, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in discard changes command " + e.message + } + return output + } + + override fun editConfig(messageContent: String, configTarget: String, + editDefaultOperation: String): DeviceResponse { + var response = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: editConfig: messageId($messageId)") + try { + val editMessage = + NetconfMessageUtils.editConfig(messageId, configTarget, editDefaultOperation, messageContent) + response.requestMessage = editMessage + response = asyncRpc(editMessage, messageId) + } catch (e: Exception) { + response.status = RpcStatus.FAILURE + response.errorMessage = e.message + } + return response + } + + override fun validate(configTarget: String): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + try { + val validateMessage = NetconfMessageUtils.validate(messageId, configTarget) + output.requestMessage = validateMessage + output = asyncRpc(validateMessage, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in validate command " + e.message + } + return output + } + + override fun closeSession(force: Boolean): DeviceResponse { + var output = DeviceResponse() + val messageId = messageIdInteger.getAndIncrement().toString() + log.info("$deviceInfo: closeSession: messageId($messageId)") + try { + val messageContent = NetconfMessageUtils.closeSession(messageId, force) + output = asyncRpc(messageContent, messageId) + } catch (e: Exception) { + output.status = RpcStatus.FAILURE + output.errorMessage = "$deviceInfo: failed in closeSession command " + e.message + } + return output + } + + @Throws(NetconfException::class) + override fun asyncRpc(request: String, messageId: String): DeviceResponse { + val response = DeviceResponse() + log.info("$deviceInfo: send asyncRpc with messageId($messageId)") + response.requestMessage = request + + val rpcResponse = netconfSession.asyncRpc(request, messageId).get(responseTimeout.toLong(), TimeUnit.SECONDS) + if (!NetconfMessageUtils.checkReply(rpcResponse)) { + throw NetconfException(rpcResponse) + } + response.responseMessage = rpcResponse + response.status = RpcStatus.SUCCESS + response.errorMessage = null + return response + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt new file mode 100644 index 000000000..d1ecb4f75 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfSessionImpl.kt @@ -0,0 +1,287 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSet +import org.apache.sshd.client.SshClient +import org.apache.sshd.client.channel.ChannelSubsystem +import org.apache.sshd.client.channel.ClientChannel +import org.apache.sshd.client.session.ClientSession +import org.apache.sshd.client.session.ClientSessionImpl +import org.apache.sshd.common.FactoryManager +import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfReceivedEvent +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfRpcService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSession +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfSessionListener +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfMessageUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcMessageUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.RpcStatus +import org.slf4j.LoggerFactory +import java.io.IOException +import java.util.* +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutionException +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicReference + +class NetconfSessionImpl(private val deviceInfo: DeviceInfo, private val rpcService: NetconfRpcService) : + NetconfSession { + + private val log = LoggerFactory.getLogger(NetconfSessionImpl::class.java) + + private val errorReplies: MutableList = Collections.synchronizedList(listOf()) + private val replies: MutableMap> = ConcurrentHashMap() + private val deviceCapabilities = setOf() + + private var connectionTimeout: Long = 0 + private var replyTimeout: Int = 0 + private var idleTimeout: Int = 0 + private var sessionId: String? = null + + private lateinit var session: ClientSession + private lateinit var client: SshClient + private lateinit var channel: ClientChannel + private lateinit var streamHandler: NetconfDeviceCommunicator + + private var capabilities = + ImmutableList.of(RpcMessageUtils.NETCONF_10_CAPABILITY, RpcMessageUtils.NETCONF_11_CAPABILITY) + + override fun connect() { + try { + log.info("$deviceInfo: Connecting to Netconf Device with timeouts C:${deviceInfo.connectTimeout}, " + + "R:${deviceInfo.replyTimeout}, I:${deviceInfo.idleTimeout}") + startConnection() + log.info("$deviceInfo: Connected to Netconf Device") + } catch (e: NetconfException) { + log.error("$deviceInfo: Netconf Device Connection Failed. ${e.message}") + throw NetconfException(e) + } + } + + override fun disconnect() { + if (rpcService.closeSession(false).status.equals( + RpcStatus.FAILURE, true)) { + rpcService.closeSession(true) + } + + session.close() + // Closes the socket which should interrupt the streamHandler + channel.close() + client.close() + } + + override fun reconnect() { + disconnect() + connect() + } + + override fun syncRpc(request: String, messageId: String): String { + val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities) + + checkAndReestablish() + + try { + return streamHandler.sendMessage(formattedRequest, messageId).get(replyTimeout.toLong(), TimeUnit.SECONDS) +// replies.remove(messageId) + } catch (e: InterruptedException) { + Thread.currentThread().interrupt() + throw NetconfException("$deviceInfo: Interrupted while waiting for reply for request: $formattedRequest", e) + } catch (e: TimeoutException) { + throw NetconfException("$deviceInfo: Timed out while waiting for reply for request $formattedRequest after $replyTimeout sec.", + e) + } catch (e: ExecutionException) { + log.warn("$deviceInfo: Closing session($sessionId) due to unexpected Error", e) + try { + session.close() + // Closes the socket which should interrupt the streamHandler + channel.close() + client.close() + } catch (ioe: IOException) { + log.warn("$deviceInfo: Error closing session($sessionId) for host($deviceInfo)", ioe) + } + +// NetconfReceivedEvent(NetconfReceivedEvent.Type.SESSION_CLOSED, "", +// "Closed due to unexpected error " + e.cause, "-1", deviceInfo) + errorReplies.clear() // move to cleanUp()? + replies.clear() + + throw NetconfException("$deviceInfo: Closing session $sessionId for request $formattedRequest", e) + } + } + + override fun asyncRpc(request: String, messageId: String): CompletableFuture { + val formattedRequest = NetconfMessageUtils.formatRPCRequest(request, messageId, deviceCapabilities) + + checkAndReestablish() + + return streamHandler.sendMessage(formattedRequest, messageId).handleAsync { reply, t -> + if (t != null) { + throw NetconfException(messageId, t) + } + reply + } + } + + override fun checkAndReestablish() { + try { + if (client.isClosed) { + log.info("Trying to restart the whole SSH connection with {}", deviceInfo) + replies.clear() + startConnection() + } else if (session.isClosed) { + log.info("Trying to restart the session with {}", deviceInfo) + replies.clear() + startSession() + } else if (channel.isClosed) { + log.info("Trying to reopen the channel with {}", deviceInfo) + replies.clear() + openChannel() + } else { + return + } + } catch (e: IOException) { + log.error("Can't reopen connection for device {}", e.message) + throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e) + } catch (e: IllegalStateException) { + log.error("Can't reopen connection for device {}", e.message) + throw NetconfException(String.format("Cannot re-open the connection with device (%s)", deviceInfo), e) + } + + } + + override fun getDeviceInfo(): DeviceInfo { + return deviceInfo + } + + override fun getSessionId(): String { + return this.sessionId!! + } + + override fun getDeviceCapabilitiesSet(): Set { + return Collections.unmodifiableSet(deviceCapabilities) + } + + private fun startConnection() { + connectionTimeout = deviceInfo.connectTimeout + replyTimeout = deviceInfo.replyTimeout + idleTimeout = deviceInfo.idleTimeout + try { + startClient() + } catch (e: Exception) { + throw NetconfException("$deviceInfo: Failed to establish SSH session", e) + } + + } + + private fun startClient() { + client = SshClient.setUpDefaultClient() + client.properties.putIfAbsent(FactoryManager.IDLE_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout.toLong())) + client.properties.putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT, TimeUnit.SECONDS.toMillis(idleTimeout + 15L)) + client.keyPairProvider = SimpleGeneratorHostKeyProvider() + client.start() + + startSession() + } + + private fun startSession() { + log.info("$deviceInfo: Starting SSH session") + val connectFuture = client.connect(deviceInfo.username, deviceInfo.ipAddress, deviceInfo.port) + .verify(connectionTimeout, TimeUnit.SECONDS) + session = connectFuture.session + log.info("$deviceInfo: SSH session created") + + authSession() + } + + private fun authSession() { + session.addPasswordIdentity(deviceInfo.password) + session.auth().verify(connectionTimeout, TimeUnit.SECONDS) + val event = session.waitFor(ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH, + ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED), 0) + if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) { + throw NetconfException("$deviceInfo: Failed to authenticate session.") + } + log.info("$deviceInfo: SSH session authenticated") + + openChannel() + } + + private fun openChannel() { + channel = session.createSubsystemChannel("netconf") + val channelFuture = channel.open() + if (channelFuture.await(connectionTimeout, TimeUnit.SECONDS) && channelFuture.isOpened) { + log.info("$deviceInfo: SSH NETCONF subsystem channel opened") + setupHandler() + } else { + throw NetconfException("$deviceInfo: Failed to open SSH subsystem channel") + } + } + + private fun setupHandler() { + val sessionListener: NetconfSessionListener = NetconfSessionListenerImpl() + streamHandler = NetconfDeviceCommunicator(channel.invertedOut, channel.invertedIn, deviceInfo, + sessionListener, replies) + + exchangeHelloMessage() + } + + private fun exchangeHelloMessage() { + sessionId = "-1" + val messageId = "-1" + + val serverHelloResponse = syncRpc(NetconfMessageUtils.createHelloString(capabilities), messageId) + val sessionIDMatcher = NetconfMessageUtils.SESSION_ID_REGEX_PATTERN.matcher(serverHelloResponse) + + if (sessionIDMatcher.find()) { + sessionId = sessionIDMatcher.group(1) + } else { + throw NetconfException("$deviceInfo: Missing sessionId in server hello message: $serverHelloResponse") + } + + val capabilityMatcher = NetconfMessageUtils.CAPABILITY_REGEX_PATTERN.matcher(serverHelloResponse) + while (capabilityMatcher.find()) { + deviceCapabilities.plus(capabilityMatcher.group(1)) + } + } + + inner class NetconfSessionListenerImpl : NetconfSessionListener { + override fun notify(event: NetconfReceivedEvent) { + val messageId = event.getMessageID() + + when (event.getType()) { + NetconfReceivedEvent.Type.DEVICE_UNREGISTERED -> disconnect() + NetconfReceivedEvent.Type.DEVICE_ERROR -> errorReplies.add(event.getMessagePayload()) + NetconfReceivedEvent.Type.DEVICE_REPLY -> replies[messageId]?.complete(event.getMessagePayload()) + NetconfReceivedEvent.Type.SESSION_CLOSED -> disconnect() + } + } + } + + fun sessionstatus(state:String): Boolean{ + return when (state){ + "Close" -> channel.isClosed + "Open" -> channel.isOpen + else -> false + } + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt new file mode 100644 index 000000000..8722bb031 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfConstant.kt @@ -0,0 +1,90 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils + +enum class NetconfDatastore(val datastore: String) { + RUNNING("running"), + CANDIDATE("candidate"); +} + +enum class ModifyAction(val action: String) { + MERGE("merge"), + REPLACE("replace"), + NONE("none") +} + +object RpcStatus { + const val SUCCESS = "success" + const val FAILURE = "failure" +} + +object RpcMessageUtils { + const val OPEN = "<" + const val CLOSE = ">" + const val EQUAL = "=" + + const val HASH = "#" + const val HASH_CHAR = '#' + + const val LF_CHAR = '\n' + const val NEW_LINE = "\n" + + const val QUOTE = "\"" + const val QUOTE_SPACE = "\" " + + const val TAG_CLOSE = "/>" + const val END_OF_RPC_OPEN_TAG = "\">" + const val END_PATTERN = "]]>]]>" + + const val HELLO = "hello" + const val RPC_REPLY = "rpc-reply" + const val RPC_ERROR = "rpc-error" + + const val RPC_OPEN = "" + const val SUBTREE_FILTER_CLOSE = "" + const val TARGET_OPEN = "" + const val TARGET_CLOSE = "" + const val SOURCE_OPEN = "" + const val SOURCE_CLOSE = "" + const val CONFIG_OPEN = "" + const val CONFIG_CLOSE = "" + const val MSGLEN_REGEX_PATTERN = "\n#\\d+\n" + + const val NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"" + + const val XML_HEADER = "" + const val NETCONF_BASE_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" + const val NETCONF_WITH_DEFAULTS_NAMESPACE = "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"" + const val SUBSCRIPTION_SUBTREE_FILTER_OPEN = + "" + + const val INTERLEAVE_CAPABILITY_STRING = "urn:ietf:params:netconf:capability:interleave:1.0" + + const val CAPABILITY_REGEX = "capability>\\s*(.*?)\\s*capability>" + + const val SESSION_ID_REGEX = "session-id>\\s*(.*?)\\s*session-id>" + + const val MESSAGE_ID_STRING = "message-id" + + const val NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0" + const val NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1" +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt new file mode 100644 index 000000000..1ffc9a68c --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/NetconfMessageUtils.kt @@ -0,0 +1,404 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils + +import org.apache.commons.lang3.StringUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException +import org.slf4j.LoggerFactory +import org.xml.sax.InputSource +import java.io.StringReader +import java.nio.charset.StandardCharsets +import java.util.regex.MatchResult +import java.util.regex.Pattern +import javax.xml.XMLConstants +import javax.xml.parsers.DocumentBuilderFactory +import kotlin.text.Charsets.UTF_8 + + +class NetconfMessageUtils { + + companion object { + val log = LoggerFactory.getLogger(NetconfMessageUtils::class.java) + + const val NEW_LINE = "\n" + const val CHUNKED_END_REGEX_PATTERN = "\n##\n" + + val CAPABILITY_REGEX_PATTERN: Pattern = Pattern.compile(RpcMessageUtils.CAPABILITY_REGEX) + val SESSION_ID_REGEX_PATTERN: Pattern = Pattern.compile(RpcMessageUtils.SESSION_ID_REGEX) + + private val CHUNKED_FRAMING_PATTERN: Pattern = + Pattern.compile("(\\n#([1-9][0-9]*)\\n(.+))+\\n##\\n", Pattern.DOTALL) + private val CHUNKED_SIZE_PATTERN: Pattern = Pattern.compile("\\n#([1-9][0-9]*)\\n") + private val MSG_ID_STRING_PATTERN = Pattern.compile("${RpcMessageUtils.MESSAGE_ID_STRING}=\"(.*?)\"") + + fun getConfig(messageId: String, configType: String, filterContent: String?): String { + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.SOURCE_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.SOURCE_CLOSE).append(NEW_LINE) + + if (!filterContent.isNullOrEmpty()) { + request.append(RpcMessageUtils.SUBTREE_FILTER_OPEN).append(NEW_LINE) + request.append(filterContent).append(NEW_LINE) + request.append(RpcMessageUtils.SUBTREE_FILTER_CLOSE).append(NEW_LINE) + } + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun doWrappedRpc(messageId: String, request: String): String { + val rpc = StringBuilder(RpcMessageUtils.XML_HEADER).append(NEW_LINE) + rpc.append(RpcMessageUtils.RPC_OPEN) + rpc.append(RpcMessageUtils.MESSAGE_ID_STRING).append(RpcMessageUtils.EQUAL) + rpc.append(RpcMessageUtils.QUOTE).append(messageId).append(RpcMessageUtils.QUOTE_SPACE) + rpc.append(RpcMessageUtils.NETCONF_BASE_NAMESPACE).append(RpcMessageUtils.CLOSE) + .append(NEW_LINE) + rpc.append(request) + rpc.append(RpcMessageUtils.RPC_CLOSE) + // rpc.append(NEW_LINE).append(END_PATTERN); + + return rpc.toString() + } + + fun editConfig(messageId: String, configType: String, defaultOperation: String?, + newConfiguration: String): String { + + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) + + if (defaultOperation != null) { + request.append(RpcMessageUtils.DEFAULT_OPERATION_OPEN).append(defaultOperation) + .append(RpcMessageUtils.DEFAULT_OPERATION_CLOSE) + request.append(NEW_LINE) + } + + request.append(RpcMessageUtils.CONFIG_OPEN).append(NEW_LINE) + request.append(newConfiguration.trim { it <= ' ' }).append(NEW_LINE) + request.append(RpcMessageUtils.CONFIG_CLOSE).append(NEW_LINE) + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun validate(messageId: String, configType: String): String { + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.SOURCE_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.SOURCE_CLOSE).append(NEW_LINE) + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun commit(messageId: String, confirmed: Boolean, confirmTimeout: Int, persist: String, + persistId: String): String { + + if (!persist.isEmpty() && !persistId.isEmpty()) { + throw NetconfException("Can't proceed with both persist($persist) and " + + "persistId($persistId) specified. Only one should be specified.") + } + if (confirmed && !persistId.isEmpty()) { + throw NetconfException("Can't proceed with both confirmed flag and " + + "persistId($persistId) specified. Only one should be specified.") + } + + val request = StringBuilder() + request.append("").append(NEW_LINE) + if (confirmed) { + request.append("") + request.append("$confirmTimeout") + if (!persist.isEmpty()) { + request.append("$persist") + } + } + if (!persistId.isEmpty()) { + request.append("$persistId") + } + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun cancelCommit(messageId: String, persistId: String): String { + val request = StringBuilder() + request.append("").append(NEW_LINE) + if (!persistId.isEmpty()) { + request.append("$persistId") + } + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun unlock(messageId: String, configType: String): String { + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + @Throws(NetconfException::class) + fun deleteConfig(messageId: String, configType: String): String { + if (configType == NetconfDatastore.RUNNING.datastore) { + log.warn("Target configuration for delete operation can't be \"running\" {}", configType) + throw NetconfException("Target configuration for delete operation can't be running") + } + + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType) + .append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun discardChanges(messageId: String): String { + val request = StringBuilder() + request.append("").append(NEW_LINE) + return doWrappedRpc(messageId, request.toString()) + } + + fun lock(messageId: String, configType: String): String { + val request = StringBuilder() + + request.append("").append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_OPEN).append(NEW_LINE) + request.append(RpcMessageUtils.OPEN).append(configType).append(RpcMessageUtils.TAG_CLOSE) + .append(NEW_LINE) + request.append(RpcMessageUtils.TARGET_CLOSE).append(NEW_LINE) + request.append("").append(NEW_LINE) + + return doWrappedRpc(messageId, request.toString()) + } + + fun closeSession(messageId: String, force: Boolean): String { + val request = StringBuilder() + + if (force) { + request.append("").append(NEW_LINE) + } else { + request.append("").append(NEW_LINE) + } + + return doWrappedRpc(messageId, request.toString()) + } + + fun validateRPCXML(rpcRequest: String): Boolean { + try { + if (StringUtils.isBlank(rpcRequest)) { + return false + } + val dbf = DocumentBuilderFactory.newInstance() + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) + dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false) + dbf.newDocumentBuilder() + .parse(InputSource(StringReader(rpcRequest.replace(RpcMessageUtils.END_PATTERN, "")))) + return true + } catch (e: Exception) { + return false + } + + } + + fun getMsgId(message: String): String { + val matcher = MSG_ID_STRING_PATTERN.matcher(message) + if (matcher.find()) { + return matcher.group(1) + } + return if (message.contains(RpcMessageUtils.HELLO)) { + (-1).toString() + } else "" + } + + fun validateChunkedFraming(reply: String): Boolean { + val matcher = CHUNKED_FRAMING_PATTERN.matcher(reply) + if (!matcher.matches()) { + log.debug("Error Reply: {}", reply) + return false + } + val chunkM = CHUNKED_SIZE_PATTERN.matcher(reply) + val chunks = ArrayList() + var chunkdataStr = "" + while (chunkM.find()) { + chunks.add(chunkM.toMatchResult()) + // extract chunk-data (and later) in bytes + val bytes = Integer.parseInt(chunkM.group(1)) + val chunkdata = reply.substring(chunkM.end()).toByteArray(StandardCharsets.UTF_8) + if (bytes > chunkdata.size) { + log.debug("Error Reply - wrong chunk size {}", reply) + return false + } + // convert (only) chunk-data part into String + chunkdataStr = String(chunkdata, 0, bytes, StandardCharsets.UTF_8) + // skip chunk-data part from next match + chunkM.region(chunkM.end() + chunkdataStr.length, reply.length) + } + if (!CHUNKED_END_REGEX_PATTERN.equals(reply.substring(chunks[chunks.size - 1].end() + chunkdataStr.length))) { + log.debug("Error Reply: {}", reply) + return false + } + return true + } + + fun createHelloString(capabilities: List): String { + val helloMessage = StringBuilder() + helloMessage.append(RpcMessageUtils.XML_HEADER).append(NEW_LINE) + helloMessage.append("").append(NEW_LINE) + helloMessage.append(" ").append(NEW_LINE) + if (capabilities.isNotEmpty()) { + capabilities.forEach { cap -> + helloMessage.append(" ").append(cap).append("").append(NEW_LINE) + } + } + helloMessage.append(" ").append(NEW_LINE) + helloMessage.append("").append(NEW_LINE) + helloMessage.append(RpcMessageUtils.END_PATTERN) + return helloMessage.toString() + } + + fun formatRPCRequest(request: String, messageId: String, deviceCapabilities: Set): String { + var request = request + request = NetconfMessageUtils.formatNetconfMessage(deviceCapabilities, request) + request = NetconfMessageUtils.formatXmlHeader(request) + request = NetconfMessageUtils.formatRequestMessageId(request, messageId) + + return request + } + + /** + * Validate and format netconf message. - NC1.0 if no EOM sequence present on `message`, + * append. - NC1.1 chunk-encode given message unless it already is chunk encoded + * + * @param deviceCapabilities Set containing Device Capabilities + * @param message to format + * @return formated message + */ + fun formatNetconfMessage(deviceCapabilities: Set, message: String): String { + var message = message + if (deviceCapabilities.contains(RpcMessageUtils.NETCONF_11_CAPABILITY)) { + message = formatChunkedMessage(message) + } else if (!message.endsWith(RpcMessageUtils.END_PATTERN)) { + message = message + NEW_LINE + RpcMessageUtils.END_PATTERN + } + return message + } + + /** + * Validate and format message according to chunked framing mechanism. + * + * @param message to format + * @return formated message + */ + fun formatChunkedMessage(message: String): String { + var message = message + if (message.endsWith(RpcMessageUtils.END_PATTERN)) { + // message given had Netconf 1.0 EOM pattern -> remove + message = message.substring(0, message.length - RpcMessageUtils.END_PATTERN.length) + } + if (!message.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) { + // chunk encode message + message = + (RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + message.toByteArray(UTF_8).size + RpcMessageUtils.NEW_LINE + message + RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + + RpcMessageUtils.NEW_LINE) + } + return message + } + + /** + * Ensures xml start directive/declaration appears in the `request`. + * + * @param request RPC request message + * @return XML RPC message + */ + fun formatXmlHeader(request: String): String { + var request = request + if (!request.contains(RpcMessageUtils.XML_HEADER)) { + if (request.startsWith(RpcMessageUtils.NEW_LINE + RpcMessageUtils.HASH)) { + request = + request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] + RpcMessageUtils.XML_HEADER + request.substring( + request.split("<".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0].length) + } else { + request = RpcMessageUtils.XML_HEADER + "\n" + request + } + } + return request + } + + fun formatRequestMessageId(request: String, messageId: String): String { + var request = request + if (request.contains(RpcMessageUtils.MESSAGE_ID_STRING)) { + request = + request.replaceFirst((RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.NUMBER_BETWEEN_QUOTES_MATCHER).toRegex(), + RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE) + } else if (!request.contains(RpcMessageUtils.MESSAGE_ID_STRING) && !request.contains( + RpcMessageUtils.HELLO)) { + request = request.replaceFirst(RpcMessageUtils.END_OF_RPC_OPEN_TAG.toRegex(), + RpcMessageUtils.QUOTE_SPACE + RpcMessageUtils.MESSAGE_ID_STRING + RpcMessageUtils.EQUAL + RpcMessageUtils.QUOTE + messageId + RpcMessageUtils.QUOTE + ">") + } + return updateRequestLength(request) + } + + fun updateRequestLength(request: String): String { + if (request.contains(NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE)) { + val oldLen = + Integer.parseInt(request.split(RpcMessageUtils.HASH.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split( + NEW_LINE.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[0]) + val rpcWithEnding = request.substring(request.indexOf('<')) + val firstBlock = + request.split(RpcMessageUtils.MSGLEN_REGEX_PATTERN.toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()[1].split( + (NEW_LINE + RpcMessageUtils.HASH + RpcMessageUtils.HASH + NEW_LINE).toRegex()).dropLastWhile( + { it.isEmpty() }).toTypedArray()[0] + var newLen = 0 + newLen = firstBlock.toByteArray(UTF_8).size + if (oldLen != newLen) { + return NEW_LINE + RpcMessageUtils.HASH + newLen + NEW_LINE + rpcWithEnding + } + } + return request + } + + fun checkReply(reply: String?): Boolean { + return if (reply != null) { + !reply.contains("rpc-error>") || reply.contains("warning") || reply.contains("ok/>") + } else false + } + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt deleted file mode 100644 index e2b901998..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor - -import com.fasterxml.jackson.databind.JsonNode -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -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.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner - -@RunWith(SpringRunner::class) -@EnableAutoConfiguration -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@DirtiesContext -@TestPropertySource(properties = -["blueprints.processor.functions.python.executor.modulePaths=./../../../../components/scripts/python/ccsdk_netconf,./../../../../components/scripts/python/ccsdk_blueprints", - "blueprints.processor.functions.python.executor.executionPath=./../../../../components/scripts/python/ccsdk_netconf"], - locations = ["classpath:application-test.properties"]) -class ComponentNetconfExecutorTest { - - @Autowired - lateinit var componentNetconfExecutor: ComponentNetconfExecutor - - - @Test - fun testComponentNetconfExecutor() { - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("requests/sample-activate-request.json", - ExecutionServiceInput::class.java)!! - - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val executionContext = bluePrintRuntimeService.getExecutionContext() - - - componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService - - //TODO("Set Attribute properties") - val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-netconf") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentNetconfExecutor") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") - // Set Step Inputs in Blueprint Runtime Service - bluePrintRuntimeService.put("activate-netconf-step-inputs", stepMetaData.asJsonNode()) - - componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService - componentNetconfExecutor.stepName = "activate-netconf" - componentNetconfExecutor.apply(executionServiceInput) - - } -} - diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt deleted file mode 100644 index e7a514347..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor - -import org.apache.sshd.client.channel.ChannelSubsystem -import org.apache.sshd.client.session.ClientSessionImpl -import org.junit.After -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core.NetconfRpcServiceImpl -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core.NetconfSessionImpl -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.mocks.NetconfDeviceSimulator -import java.util.concurrent.atomic.AtomicReference -import kotlin.script.experimental.api.asSuccess - -class NetconfSessionImplTest { - - private var device: NetconfDeviceSimulator? = null - private var deviceInfo: DeviceInfo? = null - - @Before - fun before() { - deviceInfo = DeviceInfo().apply { - username = "username" - password = "password" - ipAddress = "localhost" - port = 2224 - connectTimeout = 10 - } - - device = NetconfDeviceSimulator(deviceInfo!!.port) - device!!.start() - } - - @After - fun after() { - device!!.stop() - } - - @Throws(Exception::class) - fun testNetconfSession() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(DeviceInfo())) - - Assert.assertNotNull(netconfSession.getSessionId()) - Assert.assertEquals("localhost:2224", netconfSession.getDeviceInfo().toString()) - - netconfSession.checkAndReestablish() - - Assert.assertNotNull(netconfSession.getSessionId()) - Assert.assertEquals("localhost:2224", netconfSession.getDeviceInfo().toString()) - - Assert.assertTrue(!netconfSession.getDeviceCapabilitiesSet().isEmpty()) - } - - @Test - fun testNetconfSessionconnect() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) - netconfSession.connect() - Assert.assertTrue(netconfSession.sessionstatus("Open")) - } - - @Test - fun testNetconfSessionreconnect() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) - netconfSession.connect() - netconfSession.reconnect() - Assert.assertTrue(netconfSession.sessionstatus("Open")) - - } - @Test - fun testNetconfSessiondisconnect() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) - netconfSession.connect() - netconfSession.disconnect() - Assert.assertTrue(netconfSession.sessionstatus("Close")) - - } - @Test - fun testNetconfSessioncheckAndReestablish() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) - netconfSession.connect() - netconfSession.checkAndReestablish() - Assert.assertTrue(netconfSession.sessionstatus("Open")) - - - } - @Test - fun testNetconfSessionconnecgetDeviceInfo() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) - netconfSession.connect() - Assert.assertNotNull(netconfSession.getDeviceInfo()) - Assert.assertFalse(!netconfSession.getDeviceCapabilitiesSet().isEmpty()) - } - - -} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt deleted file mode 100644 index 8f1f71501..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt +++ /dev/null @@ -1,124 +0,0 @@ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.core - -import org.junit.After -import org.junit.Assert -import org.junit.Before -import org.junit.Test - -import org.junit.Assert.* -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.mocks.NetconfDeviceSimulator - -class NetconfRpcServiceImplTest { - - private var device: NetconfDeviceSimulator? = null - private var deviceInfo: DeviceInfo? = null - - @Before - fun before() { - deviceInfo = DeviceInfo().apply { - username = "username" - password = "password" - ipAddress = "localhost" - port = 2224 - connectTimeout = 10 - } - - device = NetconfDeviceSimulator(deviceInfo!!.port) - device!!.start() - } - - @After - fun after() { - device!!.stop() - } - - @Test - fun setNetconfSession() { - - } - - @Test - fun getConfig() { - - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.getConfig("filter","target").status.equals("failure")) - } - - - @Test - fun deleteConfig() { - - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.deleteConfig("target").status.equals("failure")) - } - - @Test - fun lock() { - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.lock("target").status.equals("failure")) - } - - @Test - fun unLock() { - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.unLock("target").status.equals("failure")) - } - - @Test - fun commit() { - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.commit(true,60,"persist","1").status.equals("failure")) - - } - - @Test - fun cancelCommit() { - val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(DeviceInfo())) - val netconfRpcServiceImpl = NetconfRpcServiceImpl(DeviceInfo()) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - - Assert.assertNotNull(netconfRpcServiceImpl.cancelCommit("1")) - } - - @Test - fun discardConfig() { - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.discardConfig().status.equals("failure")) - - } - - @Test - fun editConfig() { - } - - @Test - fun validate() { - val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) - val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) - netconfRpcServiceImpl.setNetconfSession(netconfSession) - netconfSession.connect() - Assert.assertTrue(netconfRpcServiceImpl.validate("target").status.equals("failure")) - - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt deleted file mode 100644 index a2a3946db..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.mocks - - -import org.apache.sshd.common.NamedFactory -import org.apache.sshd.server.Command -import org.apache.sshd.server.SshServer -import org.apache.sshd.server.auth.UserAuth -import org.apache.sshd.server.auth.UserAuthNoneFactory -import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils.NetconfSubsystemFactory -import java.util.* - - -class NetconfDeviceSimulator(private val port: Int) { - - private var sshd: SshServer? = null - - fun start() { - sshd = SshServer.setUpDefaultServer() - sshd!!.port = port - sshd!!.keyPairProvider = SimpleGeneratorHostKeyProvider() - - val userAuthFactories = ArrayList>() - userAuthFactories.add(UserAuthNoneFactory()) - sshd!!.userAuthFactories = userAuthFactories - - val namedFactoryList = ArrayList>() - namedFactoryList.add(NetconfSubsystemFactory()) - sshd!!.subsystemFactories = namedFactoryList - - try { - sshd!!.start() - } catch (e: Exception) { - e.printStackTrace() - } - - } - - fun stop() { - try { - sshd!!.stop(true) - } catch (e: Exception) { - e.printStackTrace() - } - - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt deleted file mode 100644 index 7eaef030b..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils - - -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.server.Command; -import org.apache.sshd.server.Environment; -import org.apache.sshd.server.ExitCallback; - - -class NetconfSubsystemFactory : NamedFactory { - - private val END_CHAR_SEQUENCE = "]]>]]>" - - override fun create(): Command { - return NetconfSubsystem() - } - - override fun getName(): String { - return "netconf" - } - - /** - * Simple implementation of netconf reading 1 request, sending a 'hello' response and quitting - */ - inner class NetconfSubsystem : Command { - private var input: InputStream? = null - private var out: OutputStream? = null - private var clientThread: Thread? = null - private var r: Int = 0 - - @Throws(IOException::class) - override fun start(env: Environment) { - clientThread = Thread(object : Runnable { - - override fun run() { - try { - val message = StringBuilder() - while (true) { - process(createHelloString()) - r = input!!.read() - if (r == -1) { - break - } else { - val c = r.toChar() - message.append(c) - val messageString = message.toString() - if (messageString.endsWith(END_CHAR_SEQUENCE)) { - println("Detected end message:\n$messageString") - process(createHelloString()) - message.setLength(0) - break - } - } - } - } catch (e: IOException) { - e.printStackTrace() - } - - } - - @Throws(IOException::class) - private fun process(xmlMessage: String) { - println("Sending message:\n$xmlMessage") - out!!.write(xmlMessage.toByteArray(charset("UTF-8"))) - out!!.write((END_CHAR_SEQUENCE + "\n").toByteArray(charset("UTF-8"))) - out!!.flush() - } - - private fun createHelloString(): String { - val sessionId = "" + (Math.random() * Integer.MAX_VALUE).toInt() - return ("\n" - + "\nurn:ietf:params:netconf:base:1.0\n" - + "urn:ietf:params:netconf:base:1.1\n\n" - + "" + sessionId + "\n") - } - }) - - clientThread!!.start() - } - - @Throws(Exception::class) - override fun destroy() { - try { - clientThread!!.join(2000) - } catch (e: InterruptedException) { - // log.warn("Error joining Client thread" + e.getMessage()); - } - - clientThread!!.interrupt() - } - - override fun setInputStream(input: InputStream) { - this.input = input - } - - override fun setOutputStream(out: OutputStream) { - this.out = out - } - - override fun setErrorStream(err: OutputStream) {} - - override fun setExitCallback(callback: ExitCallback) {} - - - - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt deleted file mode 100644 index 8a60d8097..000000000 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.utils - -import org.junit.Assert -import org.junit.Assert.assertTrue -import org.junit.Test -import org.onap.ccsdk.apps.blueprintsprocessor.functions.netconf.executor.api.NetconfException -import kotlin.test.fail - -class RpcMessageUtilsTest { - - @Test - fun getConfig() { - val checkString = ("" - + "" - + "Test-Filter-Content" - + "") - - val messageId = "Test-Message-ID" - val configType = NetconfDatastore.CANDIDATE.datastore - val filterContent = "Test-Filter-Content" - - val result = - NetconfMessageUtils.getConfig(messageId, configType, filterContent).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - - @Test - fun editConfig() { - val checkString = ("" - + "" - + "Test-Default-Operation" - + "Test-Filter-Content") - - val messageId = "Test-Message-ID" - val configType = NetconfDatastore.CANDIDATE.datastore - val filterContent = "Test-Filter-Content" - val defaultOperation = "Test-Default-Operation" - - val result = - NetconfMessageUtils.editConfig(messageId, configType, defaultOperation, filterContent).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun validate() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - val configType = NetconfDatastore.CANDIDATE.datastore - - val result = NetconfMessageUtils.validate(messageId, configType).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun cancelCommit() { - val checkString = - ("" + - "" + - "" + - "1234" + - "") - - val messageId = "Test-Message-ID" - - val cancelCommitPersistId = - NetconfMessageUtils.cancelCommit(messageId, "1234").replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(cancelCommitPersistId)) - Assert.assertEquals(checkString, cancelCommitPersistId) - } - - @Test - fun cancelCommitNoPersistId() { - val checkString = - ("" + - "" + - "" + - "") - - val messageId = "Test-Message-ID" - - val cancelCommitNoPersistId = NetconfMessageUtils.cancelCommit(messageId, "").replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(cancelCommitNoPersistId)) - Assert.assertEquals(checkString, cancelCommitNoPersistId) - } - - @Test - fun commit() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - - val commit = NetconfMessageUtils.commit(messageId, false, 0, "", "").replace("[\n\r\t]".toRegex(), "") - - val commitWithPersistButNotConfirmed = - NetconfMessageUtils.commit(messageId, false, 0, "1234", "").replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(commit)) - Assert.assertEquals(checkString, commit) - Assert.assertEquals(checkString, commitWithPersistButNotConfirmed) - - } - - @Test - fun commitPersistId() { - val checkString = - ("" + - "" + - "" + - "1234" + - "") - - val messageId = "Test-Message-ID" - - val result = NetconfMessageUtils.commit(messageId, false, 30, "", "1234").replace("[\n\r\t]".toRegex(), "") - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - - try { - NetconfMessageUtils.commit(messageId, true, 30, "", "1234").replace("[\n\r\t]".toRegex(), "") - } catch (e: NetconfException) { - Assert.assertEquals("Can't proceed with both confirmed flag and persistId(1234) specified. Only one should be specified.", - e.message) - return - } - - fail() - } - - @Test - fun commitPersist() { - val checkString = - ("" + - "" + - "" + - "" + - "30" + - "1234" + - "") - - val messageId = "Test-Message-ID" - - val result = NetconfMessageUtils.commit(messageId, true, 30, "1234", "").replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - - try { - NetconfMessageUtils.commit(messageId, false, 30, "1234", "1234").replace("[\n\r\t]".toRegex(), "") - } catch (e: NetconfException) { - Assert.assertEquals("Can't proceed with both persist(1234) and persistId(1234) specified. Only one should be specified.", - e.message) - return - } - fail() - } - - @Test - fun unlock() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - val configType = NetconfDatastore.CANDIDATE.datastore - - val result = NetconfMessageUtils.unlock(messageId, configType).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun deleteConfig() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - val netconfTargetConfig = NetconfDatastore.CANDIDATE.datastore - - val result = NetconfMessageUtils.deleteConfig(messageId, netconfTargetConfig).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun discardChanges() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - - val result = NetconfMessageUtils.discardChanges(messageId).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun lock() { - val checkString = ("" - + "" - + "") - - val messageId = "Test-Message-ID" - val configType = NetconfDatastore.CANDIDATE.datastore - val result = NetconfMessageUtils.lock(messageId, configType).replace("[\n\r\t]".toRegex(), "") - - assertTrue(NetconfMessageUtils.validateRPCXML(result)) - Assert.assertEquals(checkString, result) - } - - @Test - fun getMsgId() { - val checkString = ("testmessage") - - var messageId = "message-id=\"testmessage\"" - var result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") - Assert.assertEquals(checkString, result) - - messageId = "message-id=\"hello\"" - result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") - Assert.assertEquals("hello", result) - - messageId = "message-id" - result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") - Assert.assertEquals("", result) - } - - @Test - fun createHelloString() { - val checkString = (" " - +" hi hello ]]>]]>") - - val capability = listOf("hi", "hello") - - val result = NetconfMessageUtils.createHelloString(capability).replace("[\n\r\t]".toRegex(), "") - Assert.assertEquals(checkString, result) - } - - @Test - fun validateChunkedFraming() { - val reply = ("hello") - val result = NetconfMessageUtils.validateChunkedFraming(reply) - Assert.assertFalse(result) - } - - @Test - fun checkReply(){ - assertTrue(NetconfMessageUtils.checkReply("ok")) - } - - @Test - fun formatRPCRequest(){ - val checkString = ("#199" + - " hi hello " + - "##") - - val request = (" " - +" hi hello ]]>]]>") - - val messageId = "Test-Message-ID" - - val capabilities = setOf("hi", "hello","urn:ietf:params:netconf:base:1.1") - - val result = NetconfMessageUtils.formatRPCRequest(request,messageId,capabilities).replace("[\n\r\t]".toRegex(), "") - Assert.assertEquals(checkString, result) - - - } - - - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt new file mode 100644 index 000000000..b84c2d1ae --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/ComponentNetconfExecutorTest.kt @@ -0,0 +1,79 @@ +/* + * 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.blueprintsprocessor.functions.netconf.executor + +import com.fasterxml.jackson.databind.JsonNode +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +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.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner + +@RunWith(SpringRunner::class) +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@DirtiesContext +@TestPropertySource(properties = +["blueprints.processor.functions.python.executor.modulePaths=./../../../../components/scripts/python/ccsdk_netconf,./../../../../components/scripts/python/ccsdk_blueprints", + "blueprints.processor.functions.python.executor.executionPath=./../../../../components/scripts/python/ccsdk_netconf"], + locations = ["classpath:application-test.properties"]) +class ComponentNetconfExecutorTest { + + @Autowired + lateinit var componentNetconfExecutor: ComponentNetconfExecutor + + + @Test + fun testComponentNetconfExecutor() { + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("requests/sample-activate-request.json", + ExecutionServiceInput::class.java)!! + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", + "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val executionContext = bluePrintRuntimeService.getExecutionContext() + + + componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService + + //TODO("Set Attribute properties") + val stepMetaData: MutableMap = hashMapOf() + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-netconf") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentNetconfExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") + // Set Step Inputs in Blueprint Runtime Service + bluePrintRuntimeService.put("activate-netconf-step-inputs", stepMetaData.asJsonNode()) + + componentNetconfExecutor.bluePrintRuntimeService = bluePrintRuntimeService + componentNetconfExecutor.stepName = "activate-netconf" + componentNetconfExecutor.apply(executionServiceInput) + + } +} + diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt new file mode 100644 index 000000000..b462ad0e8 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/NetconfSessionImplTest.kt @@ -0,0 +1,111 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor + +import org.apache.sshd.client.channel.ChannelSubsystem +import org.apache.sshd.client.session.ClientSessionImpl +import org.junit.After +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core.NetconfRpcServiceImpl +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core.NetconfSessionImpl +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.mocks.NetconfDeviceSimulator +import java.util.concurrent.atomic.AtomicReference +import kotlin.script.experimental.api.asSuccess + +class NetconfSessionImplTest { + + private var device: NetconfDeviceSimulator? = null + private var deviceInfo: DeviceInfo? = null + + @Before + fun before() { + deviceInfo = DeviceInfo().apply { + username = "username" + password = "password" + ipAddress = "localhost" + port = 2224 + connectTimeout = 10 + } + + device = NetconfDeviceSimulator(deviceInfo!!.port) + device!!.start() + } + + @After + fun after() { + device!!.stop() + } + + @Throws(Exception::class) + fun testNetconfSession() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(DeviceInfo())) + + Assert.assertNotNull(netconfSession.getSessionId()) + Assert.assertEquals("localhost:2224", netconfSession.getDeviceInfo().toString()) + + netconfSession.checkAndReestablish() + + Assert.assertNotNull(netconfSession.getSessionId()) + Assert.assertEquals("localhost:2224", netconfSession.getDeviceInfo().toString()) + + Assert.assertTrue(!netconfSession.getDeviceCapabilitiesSet().isEmpty()) + } + + @Test + fun testNetconfSessionconnect() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) + netconfSession.connect() + Assert.assertTrue(netconfSession.sessionstatus("Open")) + } + + @Test + fun testNetconfSessionreconnect() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) + netconfSession.connect() + netconfSession.reconnect() + Assert.assertTrue(netconfSession.sessionstatus("Open")) + + } + @Test + fun testNetconfSessiondisconnect() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) + netconfSession.connect() + netconfSession.disconnect() + Assert.assertTrue(netconfSession.sessionstatus("Close")) + + } + @Test + fun testNetconfSessioncheckAndReestablish() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) + netconfSession.connect() + netconfSession.checkAndReestablish() + Assert.assertTrue(netconfSession.sessionstatus("Open")) + + + } + @Test + fun testNetconfSessionconnecgetDeviceInfo() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(deviceInfo!!)) + netconfSession.connect() + Assert.assertNotNull(netconfSession.getDeviceInfo()) + Assert.assertFalse(!netconfSession.getDeviceCapabilitiesSet().isEmpty()) + } + + +} diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt new file mode 100644 index 000000000..68d3e246f --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/core/NetconfRpcServiceImplTest.kt @@ -0,0 +1,124 @@ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.core + +import org.junit.After +import org.junit.Assert +import org.junit.Before +import org.junit.Test + +import org.junit.Assert.* +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.DeviceInfo +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.mocks.NetconfDeviceSimulator + +class NetconfRpcServiceImplTest { + + private var device: NetconfDeviceSimulator? = null + private var deviceInfo: DeviceInfo? = null + + @Before + fun before() { + deviceInfo = DeviceInfo().apply { + username = "username" + password = "password" + ipAddress = "localhost" + port = 2224 + connectTimeout = 10 + } + + device = NetconfDeviceSimulator(deviceInfo!!.port) + device!!.start() + } + + @After + fun after() { + device!!.stop() + } + + @Test + fun setNetconfSession() { + + } + + @Test + fun getConfig() { + + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.getConfig("filter","target").status.equals("failure")) + } + + + @Test + fun deleteConfig() { + + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.deleteConfig("target").status.equals("failure")) + } + + @Test + fun lock() { + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.lock("target").status.equals("failure")) + } + + @Test + fun unLock() { + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.unLock("target").status.equals("failure")) + } + + @Test + fun commit() { + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.commit(true,60,"persist","1").status.equals("failure")) + + } + + @Test + fun cancelCommit() { + val netconfSession = NetconfSessionImpl(deviceInfo!!, NetconfRpcServiceImpl(DeviceInfo())) + val netconfRpcServiceImpl = NetconfRpcServiceImpl(DeviceInfo()) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + + Assert.assertNotNull(netconfRpcServiceImpl.cancelCommit("1")) + } + + @Test + fun discardConfig() { + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.discardConfig().status.equals("failure")) + + } + + @Test + fun editConfig() { + } + + @Test + fun validate() { + val netconfRpcServiceImpl = NetconfRpcServiceImpl(deviceInfo!!) + val netconfSession = NetconfSessionImpl(deviceInfo!!, netconfRpcServiceImpl) + netconfRpcServiceImpl.setNetconfSession(netconfSession) + netconfSession.connect() + Assert.assertTrue(netconfRpcServiceImpl.validate("target").status.equals("failure")) + + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt new file mode 100644 index 000000000..c6d6308ab --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfDeviceSimulator.kt @@ -0,0 +1,62 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.mocks + + +import org.apache.sshd.common.NamedFactory +import org.apache.sshd.server.Command +import org.apache.sshd.server.SshServer +import org.apache.sshd.server.auth.UserAuth +import org.apache.sshd.server.auth.UserAuthNoneFactory +import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils.NetconfSubsystemFactory +import java.util.* + + +class NetconfDeviceSimulator(private val port: Int) { + + private var sshd: SshServer? = null + + fun start() { + sshd = SshServer.setUpDefaultServer() + sshd!!.port = port + sshd!!.keyPairProvider = SimpleGeneratorHostKeyProvider() + + val userAuthFactories = ArrayList>() + userAuthFactories.add(UserAuthNoneFactory()) + sshd!!.userAuthFactories = userAuthFactories + + val namedFactoryList = ArrayList>() + namedFactoryList.add(NetconfSubsystemFactory()) + sshd!!.subsystemFactories = namedFactoryList + + try { + sshd!!.start() + } catch (e: Exception) { + e.printStackTrace() + } + + } + + fun stop() { + try { + sshd!!.stop(true) + } catch (e: Exception) { + e.printStackTrace() + } + + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.kt new file mode 100644 index 000000000..de0a5d016 --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/mocks/NetconfSubsystemFactory.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.blueprintsprocessor.functions.netconf.executor.utils + + +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.Environment; +import org.apache.sshd.server.ExitCallback; + + +class NetconfSubsystemFactory : NamedFactory { + + private val END_CHAR_SEQUENCE = "]]>]]>" + + override fun create(): Command { + return NetconfSubsystem() + } + + override fun getName(): String { + return "netconf" + } + + /** + * Simple implementation of netconf reading 1 request, sending a 'hello' response and quitting + */ + inner class NetconfSubsystem : Command { + private var input: InputStream? = null + private var out: OutputStream? = null + private var clientThread: Thread? = null + private var r: Int = 0 + + @Throws(IOException::class) + override fun start(env: Environment) { + clientThread = Thread(object : Runnable { + + override fun run() { + try { + val message = StringBuilder() + while (true) { + process(createHelloString()) + r = input!!.read() + if (r == -1) { + break + } else { + val c = r.toChar() + message.append(c) + val messageString = message.toString() + if (messageString.endsWith(END_CHAR_SEQUENCE)) { + println("Detected end message:\n$messageString") + process(createHelloString()) + message.setLength(0) + break + } + } + } + } catch (e: IOException) { + e.printStackTrace() + } + + } + + @Throws(IOException::class) + private fun process(xmlMessage: String) { + println("Sending message:\n$xmlMessage") + out!!.write(xmlMessage.toByteArray(charset("UTF-8"))) + out!!.write((END_CHAR_SEQUENCE + "\n").toByteArray(charset("UTF-8"))) + out!!.flush() + } + + private fun createHelloString(): String { + val sessionId = "" + (Math.random() * Integer.MAX_VALUE).toInt() + return ("\n" + + "\nurn:ietf:params:netconf:base:1.0\n" + + "urn:ietf:params:netconf:base:1.1\n\n" + + "" + sessionId + "\n") + } + }) + + clientThread!!.start() + } + + @Throws(Exception::class) + override fun destroy() { + try { + clientThread!!.join(2000) + } catch (e: InterruptedException) { + // log.warn("Error joining Client thread" + e.getMessage()); + } + + clientThread!!.interrupt() + } + + override fun setInputStream(input: InputStream) { + this.input = input + } + + override fun setOutputStream(out: OutputStream) { + this.out = out + } + + override fun setErrorStream(err: OutputStream) {} + + override fun setExitCallback(callback: ExitCallback) {} + + + + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt new file mode 100644 index 000000000..a4ef4410a --- /dev/null +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/netconf/executor/utils/RpcMessageUtilsTest.kt @@ -0,0 +1,306 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.utils + +import org.junit.Assert +import org.junit.Assert.assertTrue +import org.junit.Test +import org.onap.ccsdk.cds.blueprintsprocessor.functions.netconf.executor.api.NetconfException +import kotlin.test.fail + +class RpcMessageUtilsTest { + + @Test + fun getConfig() { + val checkString = ("" + + "" + + "Test-Filter-Content" + + "") + + val messageId = "Test-Message-ID" + val configType = NetconfDatastore.CANDIDATE.datastore + val filterContent = "Test-Filter-Content" + + val result = + NetconfMessageUtils.getConfig(messageId, configType, filterContent).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + + @Test + fun editConfig() { + val checkString = ("" + + "" + + "Test-Default-Operation" + + "Test-Filter-Content") + + val messageId = "Test-Message-ID" + val configType = NetconfDatastore.CANDIDATE.datastore + val filterContent = "Test-Filter-Content" + val defaultOperation = "Test-Default-Operation" + + val result = + NetconfMessageUtils.editConfig(messageId, configType, defaultOperation, filterContent).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun validate() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + val configType = NetconfDatastore.CANDIDATE.datastore + + val result = NetconfMessageUtils.validate(messageId, configType).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun cancelCommit() { + val checkString = + ("" + + "" + + "" + + "1234" + + "") + + val messageId = "Test-Message-ID" + + val cancelCommitPersistId = + NetconfMessageUtils.cancelCommit(messageId, "1234").replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(cancelCommitPersistId)) + Assert.assertEquals(checkString, cancelCommitPersistId) + } + + @Test + fun cancelCommitNoPersistId() { + val checkString = + ("" + + "" + + "" + + "") + + val messageId = "Test-Message-ID" + + val cancelCommitNoPersistId = NetconfMessageUtils.cancelCommit(messageId, "").replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(cancelCommitNoPersistId)) + Assert.assertEquals(checkString, cancelCommitNoPersistId) + } + + @Test + fun commit() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + + val commit = NetconfMessageUtils.commit(messageId, false, 0, "", "").replace("[\n\r\t]".toRegex(), "") + + val commitWithPersistButNotConfirmed = + NetconfMessageUtils.commit(messageId, false, 0, "1234", "").replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(commit)) + Assert.assertEquals(checkString, commit) + Assert.assertEquals(checkString, commitWithPersistButNotConfirmed) + + } + + @Test + fun commitPersistId() { + val checkString = + ("" + + "" + + "" + + "1234" + + "") + + val messageId = "Test-Message-ID" + + val result = NetconfMessageUtils.commit(messageId, false, 30, "", "1234").replace("[\n\r\t]".toRegex(), "") + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + + try { + NetconfMessageUtils.commit(messageId, true, 30, "", "1234").replace("[\n\r\t]".toRegex(), "") + } catch (e: NetconfException) { + Assert.assertEquals("Can't proceed with both confirmed flag and persistId(1234) specified. Only one should be specified.", + e.message) + return + } + + fail() + } + + @Test + fun commitPersist() { + val checkString = + ("" + + "" + + "" + + "" + + "30" + + "1234" + + "") + + val messageId = "Test-Message-ID" + + val result = NetconfMessageUtils.commit(messageId, true, 30, "1234", "").replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + + try { + NetconfMessageUtils.commit(messageId, false, 30, "1234", "1234").replace("[\n\r\t]".toRegex(), "") + } catch (e: NetconfException) { + Assert.assertEquals("Can't proceed with both persist(1234) and persistId(1234) specified. Only one should be specified.", + e.message) + return + } + fail() + } + + @Test + fun unlock() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + val configType = NetconfDatastore.CANDIDATE.datastore + + val result = NetconfMessageUtils.unlock(messageId, configType).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun deleteConfig() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + val netconfTargetConfig = NetconfDatastore.CANDIDATE.datastore + + val result = NetconfMessageUtils.deleteConfig(messageId, netconfTargetConfig).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun discardChanges() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + + val result = NetconfMessageUtils.discardChanges(messageId).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun lock() { + val checkString = ("" + + "" + + "") + + val messageId = "Test-Message-ID" + val configType = NetconfDatastore.CANDIDATE.datastore + val result = NetconfMessageUtils.lock(messageId, configType).replace("[\n\r\t]".toRegex(), "") + + assertTrue(NetconfMessageUtils.validateRPCXML(result)) + Assert.assertEquals(checkString, result) + } + + @Test + fun getMsgId() { + val checkString = ("testmessage") + + var messageId = "message-id=\"testmessage\"" + var result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") + Assert.assertEquals(checkString, result) + + messageId = "message-id=\"hello\"" + result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") + Assert.assertEquals("hello", result) + + messageId = "message-id" + result = NetconfMessageUtils.getMsgId(messageId).replace("[\n\r\t]".toRegex(), "") + Assert.assertEquals("", result) + } + + @Test + fun createHelloString() { + val checkString = (" " + +" hi hello ]]>]]>") + + val capability = listOf("hi", "hello") + + val result = NetconfMessageUtils.createHelloString(capability).replace("[\n\r\t]".toRegex(), "") + Assert.assertEquals(checkString, result) + } + + @Test + fun validateChunkedFraming() { + val reply = ("hello") + val result = NetconfMessageUtils.validateChunkedFraming(reply) + Assert.assertFalse(result) + } + + @Test + fun checkReply(){ + assertTrue(NetconfMessageUtils.checkReply("ok")) + } + + @Test + fun formatRPCRequest(){ + val checkString = ("#199" + + " hi hello " + + "##") + + val request = (" " + +" hi hello ]]>]]>") + + val messageId = "Test-Message-ID" + + val capabilities = setOf("hi", "hello","urn:ietf:params:netconf:base:1.1") + + val result = NetconfMessageUtils.formatRPCRequest(request,messageId,capabilities).replace("[\n\r\t]".toRegex(), "") + Assert.assertEquals(checkString, result) + + + } + + + + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/netconf-executor/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/functions/netconf-executor/src/test/resources/logback-test.xml index f9ec9fe57..355cd3ace 100644 --- a/ms/blueprintsprocessor/functions/netconf-executor/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/functions/netconf-executor/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/functions/pom.xml b/ms/blueprintsprocessor/functions/pom.xml index 5bc26d5f4..24cc352c9 100755 --- a/ms/blueprintsprocessor/functions/pom.xml +++ b/ms/blueprintsprocessor/functions/pom.xml @@ -17,7 +17,7 @@ --> - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor parent 0.4.2-SNAPSHOT ../parent @@ -37,7 +37,7 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor execution-service diff --git a/ms/blueprintsprocessor/functions/python-executor/pom.xml b/ms/blueprintsprocessor/functions/python-executor/pom.xml index e0c617493..af9d1987a 100644 --- a/ms/blueprintsprocessor/functions/python-executor/pom.xml +++ b/ms/blueprintsprocessor/functions/python-executor/pom.xml @@ -17,12 +17,12 @@ functions - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor 0.4.2-SNAPSHOT 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions python-executor Blueprints Processor Function - Python Executor Blueprints Processor Function - Python Executor diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt deleted file mode 100644 index b7f77719e..000000000 --- a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor - -import com.fasterxml.jackson.databind.node.ArrayNode -import org.apache.commons.io.FilenameUtils -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.BlueprintJythonService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.PythonExecutorConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.data.OperationAssignment -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.ApplicationContext -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component - -@Component("component-jython-executor") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class ComponentJythonExecutor(private var applicationContext: ApplicationContext, - private val blueprintJythonService: BlueprintJythonService) : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(ComponentJythonExecutor::class.java) - - private var componentFunction: AbstractComponentFunction? = null - - override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { - val request = super.prepareRequest(executionRequest) - // Populate Component Instance - populateJythonComponentInstance() - return request - } - - override fun process(executionRequest: ExecutionServiceInput) { - log.info("Processing : $operationInputs") - // Invoke Jython Component Script - componentFunction!!.process(executionServiceInput) - - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - componentFunction!!.recover(runtimeException, executionRequest) - } - - private fun populateJythonComponentInstance() { - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val operationAssignment: OperationAssignment = bluePrintContext - .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName) - - val artifactName: String = operationAssignment.implementation?.primary - ?: 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)") - - val pythonClassName = FilenameUtils.getBaseName(pythonFileName) - - val content: String? = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - - checkNotEmptyOrThrow(content, "artifact ($artifactName) content is empty") - - val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode - ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") - - val jythonInstance: MutableMap = hashMapOf() - jythonInstance["log"] = LoggerFactory.getLogger(pythonClassName) - jythonInstance["bluePrintRuntimeService"] = bluePrintRuntimeService - - instanceDependenciesNode.forEach { instanceName -> - jythonInstance[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue()) - } - - // Setup componentFunction - componentFunction = blueprintJythonService.jythonInstance(bluePrintContext, pythonClassName, - content!!, jythonInstance) - componentFunction?.bluePrintRuntimeService = bluePrintRuntimeService - componentFunction?.executionServiceInput = executionServiceInput - componentFunction?.stepName = stepName - componentFunction?.interfaceName = interfaceName - componentFunction?.operationName = operationName - componentFunction?.processId = processId - componentFunction?.workflowName = workflowName - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt new file mode 100644 index 000000000..527f9dcc0 --- /dev/null +++ b/ms/blueprintsprocessor/functions/python-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutor.kt @@ -0,0 +1,105 @@ +/* + * 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.blueprintsprocessor.functions.python.executor + +import com.fasterxml.jackson.databind.node.ArrayNode +import org.apache.commons.io.FilenameUtils +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.scripts.BlueprintJythonService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.PythonExecutorConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmptyOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.ApplicationContext +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component + +@Component("component-jython-executor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class ComponentJythonExecutor(private var applicationContext: ApplicationContext, + private val blueprintJythonService: BlueprintJythonService) : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(ComponentJythonExecutor::class.java) + + private var componentFunction: AbstractComponentFunction? = null + + override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { + val request = super.prepareRequest(executionRequest) + // Populate Component Instance + populateJythonComponentInstance() + return request + } + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing : $operationInputs") + // Invoke Jython Component Script + componentFunction!!.process(executionServiceInput) + + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + componentFunction!!.recover(runtimeException, executionRequest) + } + + private fun populateJythonComponentInstance() { + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val operationAssignment: OperationAssignment = bluePrintContext + .nodeTemplateInterfaceOperation(nodeTemplateName, interfaceName, operationName) + + val artifactName: String = operationAssignment.implementation?.primary + ?: 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)") + + val pythonClassName = FilenameUtils.getBaseName(pythonFileName) + + val content: String? = bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) + + checkNotEmptyOrThrow(content, "artifact ($artifactName) content is empty") + + val instanceDependenciesNode: ArrayNode = operationInputs[PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES] as? ArrayNode + ?: throw BluePrintProcessorException("Failed to get property(${PythonExecutorConstants.INPUT_INSTANCE_DEPENDENCIES})") + + val jythonInstance: MutableMap = hashMapOf() + jythonInstance["log"] = LoggerFactory.getLogger(pythonClassName) + jythonInstance["bluePrintRuntimeService"] = bluePrintRuntimeService + + instanceDependenciesNode.forEach { instanceName -> + jythonInstance[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue()) + } + + // Setup componentFunction + componentFunction = blueprintJythonService.jythonInstance(bluePrintContext, pythonClassName, + content!!, jythonInstance) + componentFunction?.bluePrintRuntimeService = bluePrintRuntimeService + componentFunction?.executionServiceInput = executionServiceInput + componentFunction?.stepName = stepName + componentFunction?.interfaceName = interfaceName + componentFunction?.operationName = operationName + componentFunction?.processId = processId + componentFunction?.workflowName = workflowName + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt deleted file mode 100644 index dd8eb5033..000000000 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor - -import com.fasterxml.jackson.databind.JsonNode -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor.mock.MockInstanceConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.PythonExecutorConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.PythonExecutorProperty -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.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 - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [PythonExecutorConfiguration::class, PythonExecutorProperty::class, - ComponentJythonExecutor::class, MockInstanceConfiguration::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"]) -class ComponentJythonExecutorTest { - - @Autowired - lateinit var componentJythonExecutor: ComponentJythonExecutor - - @Test - fun testPythonComponentInjection() { - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-activate-request.json", - ExecutionServiceInput::class.java)!! - - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-jython") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentJythonExecutor") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") - bluePrintRuntimeService.put("activate-jython-step-inputs", stepMetaData.asJsonNode()) - - componentJythonExecutor.bluePrintRuntimeService = bluePrintRuntimeService - componentJythonExecutor.stepName = "activate-jython" - - - componentJythonExecutor.apply(executionServiceInput) - - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt deleted file mode 100644 index 41250e0ca..000000000 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.python.executor.mock - -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration - -@Configuration -open class MockInstanceConfiguration { - @Bean(name = ["json-parser-service", "netconf-rpc-service"]) - open fun createComponentFunction(): MockJythonService { - return MockJythonService() - } -} - -class MockJythonService { - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt new file mode 100644 index 000000000..07aa9a9e7 --- /dev/null +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/ComponentJythonExecutorTest.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor + +import com.fasterxml.jackson.databind.JsonNode +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.mock.MockInstanceConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.PythonExecutorConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.PythonExecutorProperty +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.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 + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [PythonExecutorConfiguration::class, PythonExecutorProperty::class, + ComponentJythonExecutor::class, MockInstanceConfiguration::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"]) +class ComponentJythonExecutorTest { + + @Autowired + lateinit var componentJythonExecutor: ComponentJythonExecutor + + @Test + fun testPythonComponentInjection() { + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-activate-request.json", + ExecutionServiceInput::class.java)!! + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", + "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val stepMetaData: MutableMap = hashMapOf() + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "activate-jython") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ComponentJythonExecutor") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") + bluePrintRuntimeService.put("activate-jython-step-inputs", stepMetaData.asJsonNode()) + + componentJythonExecutor.bluePrintRuntimeService = bluePrintRuntimeService + componentJythonExecutor.stepName = "activate-jython" + + + componentJythonExecutor.apply(executionServiceInput) + + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt new file mode 100644 index 000000000..33f68e273 --- /dev/null +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/python/executor/mock/MockInstanceConfiguration.kt @@ -0,0 +1,32 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.python.executor.mock + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +@Configuration +open class MockInstanceConfiguration { + @Bean(name = ["json-parser-service", "netconf-rpc-service"]) + open fun createComponentFunction(): MockJythonService { + return MockJythonService() + } +} + +class MockJythonService { + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/python-executor/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/functions/python-executor/src/test/resources/logback-test.xml index a816a06c5..0c8d93bf0 100644 --- a/ms/blueprintsprocessor/functions/python-executor/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/functions/python-executor/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/functions/resource-resolution/pom.xml b/ms/blueprintsprocessor/functions/resource-resolution/pom.xml index eafdb9a01..b4bbd50f9 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/pom.xml +++ b/ms/blueprintsprocessor/functions/resource-resolution/pom.xml @@ -17,11 +17,11 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor functions 0.4.2-SNAPSHOT - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions resource-resolution jar Blueprints Processor Function - Resource Resolution @@ -29,11 +29,11 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor db-lib - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions python-executor diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt deleted file mode 100644 index ffe09e4df..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import org.jetbrains.kotlin.script.util.DependsOn -import org.jetbrains.kotlin.script.util.Repository -import kotlin.script.experimental.annotations.KotlinScript -import kotlin.script.experimental.api.ScriptCompilationConfiguration -import kotlin.script.experimental.api.defaultImports -import kotlin.script.experimental.jvm.dependenciesFromCurrentContext -import kotlin.script.experimental.jvm.jvm - -@KotlinScript(fileExtension = "resourceassignmentprocessor.kts", - compilationConfiguration = ResourceAssignmentProcessorScriptConfiguration::class) -abstract class ResourceAssignmentProcessorScript { - -} - -object ResourceAssignmentProcessorScriptConfiguration : ScriptCompilationConfiguration( - { - defaultImports(DependsOn::class, Repository::class) - jvm { - dependenciesFromCurrentContext( - wholeClasspath = true - ) - } - } -) \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt deleted file mode 100644 index c4ae13975..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt +++ /dev/null @@ -1,88 +0,0 @@ -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext -import org.onap.ccsdk.apps.controllerblueprints.core.service.DefaultBluePrintRuntimeService - -class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) - : DefaultBluePrintRuntimeService(id, bluePrintContext) { - - private lateinit var resolutionId: String - private var resourceStore: MutableMap = hashMapOf() - - fun createUniqueId(key: String) { - resolutionId = "$id-$key" - } - - fun cleanResourceStore() { - resourceStore.clear() - } - - fun putResolutionStore(key: String, value: JsonNode) { - resourceStore[key] = value - } - - fun getResolutionStore(key: String): JsonNode { - return resourceStore[key] - ?: throw BluePrintProcessorException("failed to get execution property ($key)") - } - - fun checkResolutionStore(key: String): Boolean { - return resourceStore.containsKey(key) - } - - fun getJsonNodeFromResolutionStore(key: String): JsonNode { - return getResolutionStore(key) - } - - fun getStringFromResolutionStore(key: String): String? { - return getResolutionStore(key).asText() - } - - fun getBooleanFromResolutionStore(key: String): Boolean? { - return getResolutionStore(key).asBoolean() - } - - fun getIntFromResolutionStore(key: String): Int? { - return getResolutionStore(key).asInt() - } - - fun getDoubleFromResolutionStore(key: String): Double? { - return getResolutionStore(key).asDouble() - } - - fun putDictionaryStore(key: String, value: JsonNode) { - resourceStore["dictionary-$key"] = value - } - - fun getDictionaryStore(key: String): JsonNode { - return resourceStore["dictionary-$key"] - ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)") - } - - fun checkDictionaryStore(key: String): Boolean { - return resourceStore.containsKey("dictionary-$key") - } - - fun getJsonNodeFromDictionaryStore(key: String): JsonNode { - return getResolutionStore("dictionary-$key") - } - - fun getStringFromDictionaryStore(key: String): String? { - return getResolutionStore("dictionary-$key").asText() - } - - fun getBooleanFromDictionaryStore(key: String): Boolean? { - return getResolutionStore("dictionary-$key").asBoolean() - } - - fun getIntFromDictionaryStore(key: String): Int? { - return getResolutionStore("dictionary-$key").asInt() - } - - fun getDoubleFromDictionaryStore(key: String): Double? { - return getResolutionStore("dictionary-$key").asDouble() - } - -} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt deleted file mode 100644 index 98d8c65db..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component - -@Component("component-resource-resolution") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class ResourceResolutionComponent(private val resourceResolutionService: ResourceResolutionService) : - AbstractComponentFunction() { - - override fun process(executionRequest: ExecutionServiceInput) { - - val properties: MutableMap = mutableMapOf() - - try { - val key = getOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY) - val storeResult = getOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY] = key.asText() - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = storeResult.asBoolean() - } catch (e: BluePrintProcessorException) { - // NoOp - these property aren't mandatory, so don't fail the process if not provided. - } - - val artifactPrefixNamesNode = getOperationInput(ResourceResolutionConstants.INPUT_ARTIFACT_PREFIX_NAMES) - val artifactPrefixNames = JacksonUtils.getListFromJsonNode(artifactPrefixNamesNode, String::class.java) - - val resolvedParamContents = resourceResolutionService.resolveResources(bluePrintRuntimeService, - nodeTemplateName, - artifactPrefixNames, - properties) - - // Set Output Attributes - bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, - ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, resolvedParamContents.asJsonNode()) - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - bluePrintRuntimeService.getBluePrintError().addError(runtimeException.message!!) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt deleted file mode 100644 index 4c24ac695..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -open class ResourceResolutionConfiguration - - diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt deleted file mode 100644 index b57b88b7b..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -object ResourceResolutionConstants { - - const val SERVICE_RESOURCE_RESOLUTION = "resource-resolution-service" - const val PREFIX_RESOURCE_RESOLUTION_PROCESSOR = "rr-processor-" - const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names" - const val OUTPUT_ASSIGNMENT_PARAMS = "assignment-params" - const val FILE_NAME_RESOURCE_DEFINITION_TYPES = "resources_definition_types.json" - const val RESOURCE_RESOLUTION_INPUT_KEY = "resolution-key"; - const val RESOURCE_RESOLUTION_INPUT_STORE_RESULT = "store-result"; - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt deleted file mode 100644 index 620696f86..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionResultService -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintTemplateService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDefinition -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils -import org.slf4j.LoggerFactory -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service -import java.io.File - -interface ResourceResolutionService { - - fun registeredResourceSources(): List - - fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, - resolutionKey: String): String - - fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactNames: List, properties: Map): MutableMap - - fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactPrefix: String, properties: Map): String - - fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactMapping: String, artifactTemplate: String?): String - - fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>, - resourceDictionaries: MutableMap, - resourceAssignments: MutableList, - identifierName: String) -} - -@Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) -open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext, - private var resolutionResultService: ResourceResolutionResultService) : - ResourceResolutionService { - - private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java) - - override fun registeredResourceSources(): List { - return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java) - .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) } - .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) } - } - - override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactNames: List, - properties: Map): MutableMap { - - val resolvedParams: MutableMap = hashMapOf() - artifactNames.forEach { artifactName -> - val resolvedContent = resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactName, properties) - resolvedParams[artifactName] = resolvedContent - } - return resolvedParams - } - - override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactPrefix: String, properties: Map): String { - - // Velocity Artifact Definition Name - val artifactTemplate = "$artifactPrefix-template" - // Resource Assignment Artifact Definition Name - val artifactMapping = "$artifactPrefix-mapping" - - val result = resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactMapping, artifactTemplate) - - if (properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) - && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean) { - resolutionResultService.write(properties, result, bluePrintRuntimeService, artifactPrefix) - } - - return result - } - - override fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, - resolutionKey: String): String { - return resolutionResultService.read(bluePrintRuntimeService, artifactTemplate, resolutionKey) - } - - override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - artifactMapping: String, artifactTemplate: String?): String { - - var resolvedContent = "" - log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)") - - val identifierName = artifactTemplate ?: "no-template" - - val resourceAssignmentContent = - bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping) - - val resourceAssignments: MutableList = - JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java) - as? MutableList - ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions") - - // Get the Resource Dictionary Name - val dictionaryFile = bluePrintRuntimeService.bluePrintContext().rootPath.plus(File.separator) - .plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator) - .plus(ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES) - - val resourceDictionaries: MutableMap = - JacksonUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java) - ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions") - - // Resolve resources - resolveResourceAssignments(bluePrintRuntimeService, resourceDictionaries, resourceAssignments, identifierName) - - val resolvedParamJsonContent = - ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList()) - - // Check Template is there - if (artifactTemplate != null) { - val templateContent = - bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactTemplate) - resolvedContent = BluePrintTemplateService.generateContent(templateContent, resolvedParamJsonContent) - } else { - resolvedContent = resolvedParamJsonContent - } - - return resolvedContent - } - - /** - * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the - * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the - * request. - */ - override fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>, - resourceDictionaries: MutableMap, - resourceAssignments: MutableList, - identifierName: String) { - - val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments) - val resourceAssignmentRuntimeService = - ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, identifierName) - - bulkSequenced.map { batchResourceAssignments -> - batchResourceAssignments.filter { it.name != "*" && it.name != "start" } - .forEach { resourceAssignment -> - val dictionaryName = resourceAssignment.dictionaryName - val dictionarySource = resourceAssignment.dictionarySource - /** - * Get the Processor name - */ - val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDictionaries) - - val resourceAssignmentProcessor = - applicationContext.getBean(processorName) as? ResourceAssignmentProcessor - ?: throw BluePrintProcessorException("failed to get resource processor for name($processorName) " + - "for resource assignment(${resourceAssignment.name})") - try { - // Set BluePrint Runtime Service - resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService - // Set Resource Dictionaries - resourceAssignmentProcessor.resourceDictionaries = resourceDictionaries - // Invoke Apply Method - resourceAssignmentProcessor.apply(resourceAssignment) - - // Set errors from RA - blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError()) - } catch (e: RuntimeException) { - throw BluePrintProcessorException(e) - } - } - } - } - - - /** - * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can - * derive the default input processor. - */ - private fun processorName(dictionaryName: String, dictionarySource: String, - resourceDictionaries: MutableMap): String { - var processorName: String? = null - when (dictionarySource) { - "input" -> { - processorName = "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input" - } - "default" -> { - processorName = "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default" - } - else -> { - val resourceDefinition = resourceDictionaries[dictionaryName] - ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName") - - val resourceSource = resourceDefinition.sources[dictionarySource] - ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)") - - processorName = ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR - .plus(resourceSource.type) - } - } - checkNotEmptyOrThrow(processorName, - "couldn't get processor name for resource dictionary definition($dictionaryName) source" + - "($dictionarySource)") - - return processorName - - } -} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt deleted file mode 100644 index 25fc8c010..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@file:Suppress("unused") - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import com.fasterxml.jackson.annotation.JsonProperty - -open class ResourceSourceProperties - -open class InputResourceSource : ResourceSourceProperties() { - lateinit var key: String - @get:JsonProperty("key-dependencies") - lateinit var keyDependencies: MutableList -} - -open class DefaultResourceSource : ResourceSourceProperties() { - lateinit var key: String - @get:JsonProperty("key-dependencies") - lateinit var keyDependencies: MutableList -} - -open class DatabaseResourceSource : ResourceSourceProperties() { - lateinit var type: String - @get:JsonProperty("endpoint-selector") - var endpointSelector: String? = null - lateinit var query: String - @get:JsonProperty("input-key-mapping") - var inputKeyMapping: MutableMap? = null - @get:JsonProperty("output-key-mapping") - var outputKeyMapping: MutableMap? = null - @get:JsonProperty("key-dependencies") - lateinit var keyDependencies: MutableList -} - -open class RestResourceSource : ResourceSourceProperties() { - lateinit var verb: String - @get:JsonProperty("payload") - var payload: String? = null - lateinit var type: String - @get:JsonProperty("endpoint-selector") - var endpointSelector: String? = null - @get:JsonProperty("url-path") - lateinit var urlPath: String - lateinit var path: String - @get:JsonProperty("expression-type") - lateinit var expressionType: String - @get:JsonProperty("input-key-mapping") - var inputKeyMapping: MutableMap? = null - @get:JsonProperty("output-key-mapping") - var outputKeyMapping: MutableMap? = null - @get:JsonProperty("key-dependencies") - lateinit var keyDependencies: MutableList -} - -open class CapabilityResourceSource : ResourceSourceProperties() { - @get:JsonProperty("script-type") - lateinit var scriptType: String - @get:JsonProperty("script-class-reference") - lateinit var scriptClassReference: String - @get:JsonProperty("instance-dependencies") - var instanceDependencies: List? = null - @get:JsonProperty("key-dependencies") - lateinit var keyDependencies: MutableList -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt deleted file mode 100644 index e50c578d8..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.functions.resource.resolution.db - -import org.springframework.data.jpa.repository.JpaRepository - -interface ResourceResolutionRepository : JpaRepository { - - fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(key: String, blueprintName: String?, - blueprintVersion: String?, - artifactName: String): ResourceResolutionResult -} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt deleted file mode 100755 index 814fba5ea..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.db - -import com.fasterxml.jackson.annotation.JsonFormat -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.Column -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 - -@EntityListeners(AuditingEntityListener::class) -@Entity -@Table(name = "RESOURCE_RESOLUTION_RESULT") -@Proxy(lazy = false) -class ResourceResolutionResult : Serializable { - - @Id - @Column(name = "resource_resolution_result_id") - var id: String? = null - - @Column(name = "resolution_key", nullable = false) - var resolutionKey: String? = null - - @Column(name = "blueprint_name", nullable = false) - var blueprintName: String? = null - - @Column(name = "blueprint_version", nullable = false) - var blueprintVersion: String? = null - - @Column(name = "artifact_name", nullable = false) - var artifactName: String? = null - - @Lob - @Column(name = "result", nullable = false) - var result: String? = null - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @LastModifiedDate - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "creation_date") - var createdDate = Date() - - companion object { - private const val serialVersionUID = 1L - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt deleted file mode 100644 index 448782a80..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.functions.resource.resolution.db - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.springframework.dao.DataIntegrityViolationException -import org.springframework.stereotype.Service -import java.util.* - -@Service -class ResourceResolutionResultService(private val resourceResolutionRepository: ResourceResolutionRepository) { - - fun write(properties: Map, result: String, bluePrintRuntimeService: BluePrintRuntimeService<*>, - artifactPrefix: String) { - - val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - - val resourceResolutionResult = ResourceResolutionResult() - resourceResolutionResult.id = UUID.randomUUID().toString() - resourceResolutionResult.artifactName = artifactPrefix - resourceResolutionResult.blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] - resourceResolutionResult.blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] - resourceResolutionResult.resolutionKey = - properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY].toString() - resourceResolutionResult.result = result - - try { - resourceResolutionRepository.saveAndFlush(resourceResolutionResult) - } catch (ex: DataIntegrityViolationException) { - throw BluePrintException("Failed to store resource resolution result.", ex) - } - } - - fun read(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactPrefix: String, - resolutionKey: String): String { - - val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! - - val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] - val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] - - return resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName( - resolutionKey, - blueprintName, - blueprintVersion, - artifactPrefix).result!! - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt deleted file mode 100644 index 6469e78da..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.CapabilityResourceSource -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.ApplicationContext -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-capability") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class CapabilityResourceResolutionProcessor(private val applicationContext: ApplicationContext, - private var componentFunctionScriptingService: ComponentFunctionScriptingService) - : ResourceAssignmentProcessor() { - - private val log = LoggerFactory.getLogger(CapabilityResourceResolutionProcessor::class.java) - - var componentResourceAssignmentProcessor: ResourceAssignmentProcessor? = null - - override fun getName(): String { - return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-capability" - } - - override fun process(resourceAssignment: ResourceAssignment) { - - val resourceDefinition = resourceDictionaries[resourceAssignment.dictionaryName] - ?: throw BluePrintProcessorException("couldn't get resource definition for ${resourceAssignment.dictionaryName}") - - val resourceSource = resourceDefinition.sources[resourceAssignment.dictionarySource] - ?: throw BluePrintProcessorException("couldn't get resource definition " + - "${resourceAssignment.dictionaryName} source(${resourceAssignment.dictionarySource})") - - val resourceSourceProps = checkNotNull(resourceSource.properties) { "failed to get $resourceSource properties" } - /** - * Get the Capability Resource Source Info from Property Definitions. - */ - val capabilityResourceSourceProperty = JacksonUtils - .getInstanceFromMap(resourceSourceProps, CapabilityResourceSource::class.java) - - val scriptType = capabilityResourceSourceProperty.scriptType - val scriptClassReference = capabilityResourceSourceProperty.scriptClassReference - val instanceDependencies = capabilityResourceSourceProperty.instanceDependencies ?: listOf() - - componentResourceAssignmentProcessor = scriptInstance(scriptType, scriptClassReference, instanceDependencies) - - checkNotNull(componentResourceAssignmentProcessor) { - "failed to get capability resource assignment processor($scriptClassReference)" - } - - // Assign Current Blueprint runtime and ResourceDictionaries - componentResourceAssignmentProcessor!!.raRuntimeService = raRuntimeService - componentResourceAssignmentProcessor!!.resourceDictionaries = resourceDictionaries - - // Invoke componentResourceAssignmentProcessor - componentResourceAssignmentProcessor!!.apply(resourceAssignment) - } - - override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { - log.info("Recovering for : ${resourceAssignment.name} : ${runtimeException.toString()}") - if (componentResourceAssignmentProcessor != null) { - componentResourceAssignmentProcessor!!.recover(runtimeException, resourceAssignment) - } - } - - fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List) - : ResourceAssignmentProcessor { - - log.info("creating resource resolution of script type($scriptType), reference name($scriptClassReference) and" + - "instanceDependencies($instanceDependencies)") - - val scriptComponent = componentFunctionScriptingService - .scriptInstance(raRuntimeService.bluePrintContext(), scriptType, - scriptClassReference) - - instanceDependencies.forEach { instanceDependency -> - scriptPropertyInstances[instanceDependency] = applicationContext - .getBean(instanceDependency) - } - return scriptComponent - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt deleted file mode 100644 index a192989e5..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt +++ /dev/null @@ -1,190 +0,0 @@ -/* - * 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.apps.blueprintsprocessor.functions.resource.resolution.processor - -import com.fasterxml.jackson.databind.node.JsonNodeFactory -import com.fasterxml.jackson.databind.node.MissingNode -import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibGenericService -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.PrimaryDBLibGenericService -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.controllerblueprints.core.* -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service -import java.util.* - -/** - * DatabaseResourceAssignmentProcessor - * - * @author Kapil Singal - */ -@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class DatabaseResourceAssignmentProcessor(private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice, private val primaryDBLibGenericService: PrimaryDBLibGenericService) - : ResourceAssignmentProcessor() { - - private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java) - - override fun getName(): String { - return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db" - } - - override fun process(resourceAssignment: ResourceAssignment) { - try { - validate(resourceAssignment) - - // Check if It has Input - try { - val value = raRuntimeService.getInputValue(resourceAssignment.name) - if (value !is NullNode && value !is MissingNode) { - logger.info("processor-db source template key (${resourceAssignment.name}) found from input and value is ($value)") - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) - } else { - setValueFromDB(resourceAssignment) - } - } catch (e: BluePrintProcessorException) { - setValueFromDB(resourceAssignment) - } - - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: Exception) { - ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) - } - } - - private fun setValueFromDB(resourceAssignment: ResourceAssignment) { - val dName = resourceAssignment.dictionaryName - val dSource = resourceAssignment.dictionarySource - val resourceDefinition = resourceDictionaries[dName] - ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") - val resourceSource = resourceDefinition.sources[dSource] - ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") - val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } - val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java) - - val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" } - val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } - - logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") - val jdbcTemplate = blueprintDBLibService(sourceProperties) - - val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping)) - if (rows.isNullOrEmpty()) { - logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)") - } else { - populateResource(resourceAssignment, sourceProperties, rows) - } - } - - private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService { - return if (checkNotEmpty(sourceProperties.endpointSelector)) { - val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!) - bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson) - } else { - primaryDBLibGenericService - } - - } - - @Throws(BluePrintProcessorException::class) - private fun validate(resourceAssignment: ResourceAssignment) { - checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") - checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") - checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PROCESSOR_DB, resourceAssignment.dictionarySource) { - "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}" - } - } - - private fun populateNamedParameter(inputKeyMapping: Map): Map { - val namedParameters = HashMap() - inputKeyMapping.forEach { - val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue() - logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)") - namedParameters[it.key] = expressionValue - } - logger.info("Parameter information : ({})", namedParameters) - return namedParameters - } - - @Throws(BluePrintProcessorException::class) - private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List>) { - val dName = resourceAssignment.dictionaryName - val dSource = resourceAssignment.dictionarySource - val type = nullToEmpty(resourceAssignment.property?.type) - - val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } - logger.info("Response processing type($type)") - - // Primitive Types - when (type) { - in BluePrintTypes.validPrimitiveTypes() -> { - val dbColumnValue = rows[0][outputKeyMapping[dName]] - logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)") - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue) - } - in BluePrintTypes.validCollectionTypes() -> { - val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } - val arrayNode = JsonNodeFactory.instance.arrayNode() - rows.forEach { - if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) { - val dbColumnValue = it[outputKeyMapping[dName]] - // Add Array JSON - JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode) - } else { - val arrayChildNode = JsonNodeFactory.instance.objectNode() - for (mapping in outputKeyMapping.entries) { - val dbColumnValue = checkNotNull(it[mapping.key]) - val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key) - JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode) - } - arrayNode.add(arrayChildNode) - } - } - logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") - // Set the List of Complex Values - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) - } - else -> { - // Complex Types - val row = rows[0] - val objectNode = JsonNodeFactory.instance.objectNode() - for (mapping in outputKeyMapping.entries) { - val dbColumnValue = checkNotNull(row[mapping.key]) - val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key) - JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode) - } - logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) - } - } - } - - override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { - raRuntimeService.getBluePrintError().addError(runtimeException.message!!) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt deleted file mode 100644 index 0f51e4bff..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor - -import com.fasterxml.jackson.databind.node.MissingNode -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -/** - * DefaultResourceResolutionProcessor - * - * @author Kapil Singal - */ -@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class DefaultResourceResolutionProcessor : ResourceAssignmentProcessor() { - - private val logger = LoggerFactory.getLogger(DefaultResourceResolutionProcessor::class.java) - - override fun getName(): String { - return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default" - } - - override fun process(resourceAssignment: ResourceAssignment) { - try { - var value = getFromInput(resourceAssignment) - if (value == null || value is MissingNode) { - value = resourceAssignment.property?.defaultValue - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) - } - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: Exception) { - ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", - e) - } - - } - - override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { - raRuntimeService.getBluePrintError().addError(runtimeException.message!!) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt deleted file mode 100644 index 579989a61..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor - -import com.fasterxml.jackson.databind.node.MissingNode -import com.fasterxml.jackson.databind.node.NullNode -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -/** - * InputResourceResolutionProcessor - * - * @author Kapil Singal - */ -@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() { - - private val logger = LoggerFactory.getLogger(InputResourceResolutionProcessor::class.java) - - override fun getName(): String { - return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input" - } - - override fun process(resourceAssignment: ResourceAssignment) { - try { - if (checkNotEmpty(resourceAssignment.name)) { - val value = raRuntimeService.getInputValue(resourceAssignment.name) - // if value is null don't call setResourceDataValue to populate the value - if (value !is MissingNode && value !is NullNode) { - logger.info("input source template key (${resourceAssignment.name}) found from input and value is ($value)") - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) - } - } - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: Exception) { - ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with : (${e.message})", e) - } - } - - override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { - raRuntimeService.getBluePrintError().addError(runtimeException.message!!) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt deleted file mode 100644 index 3f0c1b4ff..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * 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.apps.blueprintsprocessor.functions.resource.resolution.processor - -import com.fasterxml.jackson.databind.JsonNode -import org.apache.commons.collections.MapUtils -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintTemplateService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDefinition -import org.slf4j.LoggerFactory -import java.util.* - -abstract class ResourceAssignmentProcessor : BlueprintFunctionNode { - - private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java) - - lateinit var raRuntimeService: ResourceAssignmentRuntimeService - lateinit var resourceDictionaries: MutableMap - - var scriptPropertyInstances: MutableMap = hashMapOf() - - /** - * This will be called from the scripts to serve instance from runtime to scripts. - */ - open fun scriptPropertyInstanceType(name: String): T { - return scriptPropertyInstances as? T - ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") - } - - open fun getFromInput(resourceAssignment: ResourceAssignment): JsonNode? { - var value: JsonNode? = null - try { - value = raRuntimeService.getInputValue(resourceAssignment.name) - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) - } catch (e: BluePrintProcessorException) { - // NoOp - couldn't find value from input - } - return value - } - - open fun resourceDefinition(name: String): ResourceDefinition { - return resourceDictionaries[name] - ?: throw BluePrintProcessorException("couldn't get resource definition for ($name)") - } - - open fun resolveInputKeyMappingVariables(inputKeyMapping: Map): Map { - val resolvedInputKeyMapping = HashMap() - if (MapUtils.isNotEmpty(inputKeyMapping)) { - for ((key, value) in inputKeyMapping) { - val resultValue = raRuntimeService.getResolutionStore(value) - val expressionValue = JacksonUtils.getValue(resultValue) - log.trace("Reference dictionary key ({}), value ({})", key, expressionValue) - resolvedInputKeyMapping[key] = expressionValue - } - } - return resolvedInputKeyMapping - } - - open fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: Map): String { - if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) { - return valueToResolve - } - return BluePrintTemplateService.generateContent(valueToResolve, additionalContext = keyMapping) - } - - override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment { - log.info("prepareRequest for ${resourceAssignment.name}, dictionary(${resourceAssignment.dictionaryName})," + - "source(${resourceAssignment.dictionarySource})") - return resourceAssignment - } - - override fun prepareResponse(): Boolean { - log.info("Preparing Response...") - return true - } - - override fun apply(resourceAssignment: ResourceAssignment): Boolean { - try { - prepareRequest(resourceAssignment) - process(resourceAssignment) - } catch (runtimeException: RuntimeException) { - recover(runtimeException, resourceAssignment) - } - return prepareResponse() - } - - fun addError(type: String, name: String, error: String) { - raRuntimeService.getBluePrintError().addError(type, name, error) - } - - fun addError(error: String) { - raRuntimeService.getBluePrintError().addError(error) - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt deleted file mode 100644 index 091220b5e..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt +++ /dev/null @@ -1,204 +0,0 @@ -/* - * 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.apps.blueprintsprocessor.functions.resource.resolution.processor - -import com.fasterxml.jackson.databind.node.ArrayNode -import com.fasterxml.jackson.databind.node.JsonNodeFactory -import com.fasterxml.jackson.databind.node.MissingNode -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.RestResourceSource -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils -import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService -import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes -import org.onap.ccsdk.apps.controllerblueprints.core.checkEqualsOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty -import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDictionaryConstants -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Service - -/** - * RestResourceResolutionProcessor - * - * @author Kapil Singal - */ -@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) - : ResourceAssignmentProcessor() { - - private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java) - - override fun getName(): String { - return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest" - } - - override fun process(resourceAssignment: ResourceAssignment) { - try { - validate(resourceAssignment) - - // Check if It has Input - val value = getFromInput(resourceAssignment) - if (value == null || value is MissingNode) { - val dName = resourceAssignment.dictionaryName - val dSource = resourceAssignment.dictionarySource - val resourceDefinition = resourceDictionaries[dName] - ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") - val resourceSource = resourceDefinition.sources[dSource] - ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") - val resourceSourceProperties = - checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } - val sourceProperties = - JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java) - val path = nullToEmpty(sourceProperties.path) - val inputKeyMapping = - checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } - val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping) - - // Resolving content Variables - val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping) - val urlPath = - resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping) - val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping) - - logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") - // Get the Rest Client Service - val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties) - - val response = restClientService.exchangeResource(verb, urlPath, payload) - if (response.isBlank()) { - logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)") - } else { - populateResource(resourceAssignment, sourceProperties, response, path) - } - } - // Check the value has populated for mandatory case - ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) - } catch (e: Exception) { - ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) - throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", - e) - } - } - - private fun blueprintWebClientService(resourceAssignment: ResourceAssignment, - restResourceSource: RestResourceSource): BlueprintWebClientService { - return if (checkNotEmpty(restResourceSource.endpointSelector)) { - val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!) - blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson) - } else { - blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!) - } - } - - @Throws(BluePrintProcessorException::class) - private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, - restResponse: String, path: String) { - val dName = resourceAssignment.dictionaryName - val dSource = resourceAssignment.dictionarySource - val type = nullToEmpty(resourceAssignment.property?.type) - lateinit var entrySchemaType: String - - val outputKeyMapping = - checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } - logger.info("Response processing type($type)") - - val responseNode = - checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" } - logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)") - - - when (type) { - in BluePrintTypes.validPrimitiveTypes() -> { - logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)") - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode) - } - in BluePrintTypes.validCollectionTypes() -> { - // Array Types - entrySchemaType = - returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } - val arrayNode = responseNode as ArrayNode - - if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) { - val responseArrayNode = responseNode.toList() - for (responseSingleJsonNode in responseArrayNode) { - val arrayChildNode = JsonNodeFactory.instance.objectNode() - outputKeyMapping.map { - val responseKeyValue = responseSingleJsonNode.get(it.key) - val propertyTypeForDataType = - ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) - logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") - JacksonUtils.populateJsonNodeValues(it.value, - responseKeyValue, - propertyTypeForDataType, - arrayChildNode) - } - arrayNode.add(arrayChildNode) - } - } - logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") - // Set the List of Complex Values - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) - } - else -> { - // Complex Types - entrySchemaType = - returnNotEmptyOrThrow(resourceAssignment.property?.type) { "Entry schema is not defined for dictionary ($dName) info" } - val objectNode = JsonNodeFactory.instance.objectNode() - outputKeyMapping.map { - val responseKeyValue = responseNode.get(it.key) - val propertyTypeForDataType = - ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) - logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") - JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode) - } - - logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") - // Set the List of Complex Values - ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) - } - } - } - - @Throws(BluePrintProcessorException::class) - private fun validate(resourceAssignment: ResourceAssignment) { - checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") - checkNotEmptyOrThrow(resourceAssignment.dictionaryName, - "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") - checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, - resourceAssignment.dictionarySource) { - "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}" - } - checkNotEmptyOrThrow(resourceAssignment.dictionaryName, - "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") - } - - override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { - raRuntimeService.getBluePrintError().addError(runtimeException.message!!) - } - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt deleted file mode 100644 index d55ccacb2..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.utils - -import com.att.eelf.configuration.EELFLogger -import com.att.eelf.configuration.EELFManager -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import com.fasterxml.jackson.databind.node.NullNode -import com.fasterxml.jackson.databind.node.ObjectNode -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintTypes -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmpty -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.nullToEmpty -import org.onap.ccsdk.apps.controllerblueprints.core.returnNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import java.util.* - -class ResourceAssignmentUtils { - companion object { - - private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils::class.toString()) - - // TODO("Modify Value type from Any to JsonNode") - @Throws(BluePrintProcessorException::class) - fun setResourceDataValue(resourceAssignment: ResourceAssignment, - raRuntimeService: ResourceAssignmentRuntimeService, value: Any?) { - - val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" } - checkNotEmptyOrThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment") - - if (resourceAssignment.dictionaryName.isNullOrEmpty()) { - resourceAssignment.dictionaryName = resourceAssignment.name - logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})") - } - - try { - if (resourceProp.type.isNotEmpty()) { - val convertedValue = convertResourceValue(resourceProp.type, value) - logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})") - setResourceValue(resourceAssignment, raRuntimeService, convertedValue) - resourceAssignment.updatedDate = Date() - resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM - resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS - } - } catch (e: Exception) { - throw BluePrintProcessorException("Failed in setting value for template key (${resourceAssignment.name}) and " + - "dictionary key (${resourceAssignment.dictionaryName}) of type (${resourceProp.type}) with error message (${e.message})", e) - } - } - - private fun setResourceValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) { - raRuntimeService.putResolutionStore(resourceAssignment.name, value) - raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value) - resourceAssignment.property!!.value = value - } - - private fun convertResourceValue(type: String, value: Any?): JsonNode { - - return if (value == null || value is NullNode) { - logger.info("Returning {} value from convertResourceValue", value) - NullNode.instance - } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) { - JacksonUtils.convertPrimitiveResourceValue(type, value) - } else if (value is String) { - JacksonUtils.jsonNode(value) - } else { - JacksonUtils.getJsonNode(value) - } - - } - - fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) { - if (checkNotEmpty(resourceAssignment.name)) { - resourceAssignment.updatedDate = Date() - resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM - resourceAssignment.status = BluePrintConstants.STATUS_FAILURE - resourceAssignment.message = message - } - } - - @Throws(BluePrintProcessorException::class) - fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) { - val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" } - if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) { - logger.error("failed to populate mandatory resource mapping ($resourceAssignment)") - throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)") - } - } - - @Throws(BluePrintProcessorException::class) - fun generateResourceDataForAssignments(assignments: List): String { - val result: String - try { - val mapper = ObjectMapper() - val root: ObjectNode = mapper.createObjectNode() - - assignments.forEach { - if (checkNotEmpty(it.name) && it.property != null) { - val rName = it.name - val type = nullToEmpty(it.property?.type).toLowerCase() - val value = it.property?.value - logger.info("Generating Resource name ($rName), type ($type), value ($value)") - root.set(rName, value) - } - } - result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root) - logger.info("Generated Resource Param Data ($result)") - } catch (e: Exception) { - throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e) - } - - return result - } - - fun transformToRARuntimeService(blueprintRuntimeService: BluePrintRuntimeService<*>, templateArtifactName: String): ResourceAssignmentRuntimeService { - val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(blueprintRuntimeService.id(), blueprintRuntimeService.bluePrintContext()) - resourceAssignmentRuntimeService.createUniqueId(templateArtifactName) - resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap) - - return resourceAssignmentRuntimeService - } - - @Throws(BluePrintProcessorException::class) - fun getPropertyType(raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String, propertyName: String): String { - lateinit var type: String - try { - val dataTypeProps = checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties) - val propertyDefinition = checkNotNull(dataTypeProps[propertyName]) - type = returnNotEmptyOrThrow(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" } - logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type) - } catch (e: Exception) { - logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e") - throw BluePrintProcessorException("${e.message}", e) - } - return type - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt new file mode 100644 index 000000000..5f3a5cdaf --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentProcessorScriptConfiguration.kt @@ -0,0 +1,42 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import org.jetbrains.kotlin.script.util.DependsOn +import org.jetbrains.kotlin.script.util.Repository +import kotlin.script.experimental.annotations.KotlinScript +import kotlin.script.experimental.api.ScriptCompilationConfiguration +import kotlin.script.experimental.api.defaultImports +import kotlin.script.experimental.jvm.dependenciesFromCurrentContext +import kotlin.script.experimental.jvm.jvm + +@KotlinScript(fileExtension = "resourceassignmentprocessor.kts", + compilationConfiguration = ResourceAssignmentProcessorScriptConfiguration::class) +abstract class ResourceAssignmentProcessorScript { + +} + +object ResourceAssignmentProcessorScriptConfiguration : ScriptCompilationConfiguration( + { + defaultImports(DependsOn::class, Repository::class) + jvm { + dependenciesFromCurrentContext( + wholeClasspath = true + ) + } + } +) \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt new file mode 100644 index 000000000..3a3750acb --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceAssignmentRuntimeService.kt @@ -0,0 +1,88 @@ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService + +class ResourceAssignmentRuntimeService(private var id: String, private var bluePrintContext: BluePrintContext) + : DefaultBluePrintRuntimeService(id, bluePrintContext) { + + private lateinit var resolutionId: String + private var resourceStore: MutableMap = hashMapOf() + + fun createUniqueId(key: String) { + resolutionId = "$id-$key" + } + + fun cleanResourceStore() { + resourceStore.clear() + } + + fun putResolutionStore(key: String, value: JsonNode) { + resourceStore[key] = value + } + + fun getResolutionStore(key: String): JsonNode { + return resourceStore[key] + ?: throw BluePrintProcessorException("failed to get execution property ($key)") + } + + fun checkResolutionStore(key: String): Boolean { + return resourceStore.containsKey(key) + } + + fun getJsonNodeFromResolutionStore(key: String): JsonNode { + return getResolutionStore(key) + } + + fun getStringFromResolutionStore(key: String): String? { + return getResolutionStore(key).asText() + } + + fun getBooleanFromResolutionStore(key: String): Boolean? { + return getResolutionStore(key).asBoolean() + } + + fun getIntFromResolutionStore(key: String): Int? { + return getResolutionStore(key).asInt() + } + + fun getDoubleFromResolutionStore(key: String): Double? { + return getResolutionStore(key).asDouble() + } + + fun putDictionaryStore(key: String, value: JsonNode) { + resourceStore["dictionary-$key"] = value + } + + fun getDictionaryStore(key: String): JsonNode { + return resourceStore["dictionary-$key"] + ?: throw BluePrintProcessorException("failed to get execution property (dictionary-$key)") + } + + fun checkDictionaryStore(key: String): Boolean { + return resourceStore.containsKey("dictionary-$key") + } + + fun getJsonNodeFromDictionaryStore(key: String): JsonNode { + return getResolutionStore("dictionary-$key") + } + + fun getStringFromDictionaryStore(key: String): String? { + return getResolutionStore("dictionary-$key").asText() + } + + fun getBooleanFromDictionaryStore(key: String): Boolean? { + return getResolutionStore("dictionary-$key").asBoolean() + } + + fun getIntFromDictionaryStore(key: String): Int? { + return getResolutionStore("dictionary-$key").asInt() + } + + fun getDoubleFromDictionaryStore(key: String): Double? { + return getResolutionStore("dictionary-$key").asDouble() + } + +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt new file mode 100644 index 000000000..0fe638a04 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponent.kt @@ -0,0 +1,62 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component + +@Component("component-resource-resolution") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class ResourceResolutionComponent(private val resourceResolutionService: ResourceResolutionService) : + AbstractComponentFunction() { + + override fun process(executionRequest: ExecutionServiceInput) { + + val properties: MutableMap = mutableMapOf() + + try { + val key = getOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY) + val storeResult = getOperationInput(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY] = key.asText() + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] = storeResult.asBoolean() + } catch (e: BluePrintProcessorException) { + // NoOp - these property aren't mandatory, so don't fail the process if not provided. + } + + val artifactPrefixNamesNode = getOperationInput(ResourceResolutionConstants.INPUT_ARTIFACT_PREFIX_NAMES) + val artifactPrefixNames = JacksonUtils.getListFromJsonNode(artifactPrefixNamesNode, String::class.java) + + val resolvedParamContents = resourceResolutionService.resolveResources(bluePrintRuntimeService, + nodeTemplateName, + artifactPrefixNames, + properties) + + // Set Output Attributes + bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, + ResourceResolutionConstants.OUTPUT_ASSIGNMENT_PARAMS, resolvedParamContents.asJsonNode()) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + bluePrintRuntimeService.getBluePrintError().addError(runtimeException.message!!) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt new file mode 100644 index 000000000..13ff0a73f --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConfiguration.kt @@ -0,0 +1,26 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +open class ResourceResolutionConfiguration + + diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt new file mode 100644 index 000000000..d605c8828 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionConstants.kt @@ -0,0 +1,31 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +object ResourceResolutionConstants { + + const val SERVICE_RESOURCE_RESOLUTION = "resource-resolution-service" + const val PREFIX_RESOURCE_RESOLUTION_PROCESSOR = "rr-processor-" + const val INPUT_ARTIFACT_PREFIX_NAMES = "artifact-prefix-names" + const val OUTPUT_ASSIGNMENT_PARAMS = "assignment-params" + const val FILE_NAME_RESOURCE_DEFINITION_TYPES = "resources_definition_types.json" + const val RESOURCE_RESOLUTION_INPUT_KEY = "resolution-key"; + const val RESOURCE_RESOLUTION_INPUT_STORE_RESULT = "store-result"; + + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt new file mode 100644 index 000000000..ce3aa4d84 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionService.kt @@ -0,0 +1,228 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.ResourceResolutionResultService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmptyOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceDefinition +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.utils.BulkResourceSequencingUtils +import org.slf4j.LoggerFactory +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service +import java.io.File + +interface ResourceResolutionService { + + fun registeredResourceSources(): List + + fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, + resolutionKey: String): String + + fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactNames: List, properties: Map): MutableMap + + fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactPrefix: String, properties: Map): String + + fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactMapping: String, artifactTemplate: String?): String + + fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>, + resourceDictionaries: MutableMap, + resourceAssignments: MutableList, + identifierName: String) +} + +@Service(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) +open class ResourceResolutionServiceImpl(private var applicationContext: ApplicationContext, + private var resolutionResultService: ResourceResolutionResultService) : + ResourceResolutionService { + + private val log = LoggerFactory.getLogger(ResourceResolutionService::class.java) + + override fun registeredResourceSources(): List { + return applicationContext.getBeanNamesForType(ResourceAssignmentProcessor::class.java) + .filter { it.startsWith(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) } + .map { it.substringAfter(ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR) } + } + + override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactNames: List, + properties: Map): MutableMap { + + val resolvedParams: MutableMap = hashMapOf() + artifactNames.forEach { artifactName -> + val resolvedContent = resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactName, properties) + resolvedParams[artifactName] = resolvedContent + } + return resolvedParams + } + + override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactPrefix: String, properties: Map): String { + + // Velocity Artifact Definition Name + val artifactTemplate = "$artifactPrefix-template" + // Resource Assignment Artifact Definition Name + val artifactMapping = "$artifactPrefix-mapping" + + val result = resolveResources(bluePrintRuntimeService, nodeTemplateName, artifactMapping, artifactTemplate) + + if (properties.containsKey(ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT) + && properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_STORE_RESULT] as Boolean) { + resolutionResultService.write(properties, result, bluePrintRuntimeService, artifactPrefix) + } + + return result + } + + override fun resolveFromDatabase(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactTemplate: String, + resolutionKey: String): String { + return resolutionResultService.read(bluePrintRuntimeService, artifactTemplate, resolutionKey) + } + + override fun resolveResources(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + artifactMapping: String, artifactTemplate: String?): String { + + var resolvedContent = "" + log.info("Resolving resource for template artifact($artifactTemplate) with resource assignment artifact($artifactMapping)") + + val identifierName = artifactTemplate ?: "no-template" + + val resourceAssignmentContent = + bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactMapping) + + val resourceAssignments: MutableList = + JacksonUtils.getListFromJson(resourceAssignmentContent, ResourceAssignment::class.java) + as? MutableList + ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions") + + // Get the Resource Dictionary Name + val dictionaryFile = bluePrintRuntimeService.bluePrintContext().rootPath.plus(File.separator) + .plus(BluePrintConstants.TOSCA_DEFINITIONS_DIR).plus(File.separator) + .plus(ResourceResolutionConstants.FILE_NAME_RESOURCE_DEFINITION_TYPES) + + val resourceDictionaries: MutableMap = + JacksonUtils.getMapFromFile(dictionaryFile, ResourceDefinition::class.java) + ?: throw BluePrintProcessorException("couldn't get Dictionary Definitions") + + // Resolve resources + resolveResourceAssignments(bluePrintRuntimeService, resourceDictionaries, resourceAssignments, identifierName) + + val resolvedParamJsonContent = + ResourceAssignmentUtils.generateResourceDataForAssignments(resourceAssignments.toList()) + + // Check Template is there + if (artifactTemplate != null) { + val templateContent = + bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactTemplate) + resolvedContent = BluePrintTemplateService.generateContent(templateContent, resolvedParamJsonContent) + } else { + resolvedContent = resolvedParamJsonContent + } + + return resolvedContent + } + + /** + * Iterate the Batch, get the Resource Assignment, dictionary Name, Look for the Resource definition for the + * name, then get the type of the Resource Definition, Get the instance for the Resource Type and process the + * request. + */ + override fun resolveResourceAssignments(blueprintRuntimeService: BluePrintRuntimeService<*>, + resourceDictionaries: MutableMap, + resourceAssignments: MutableList, + identifierName: String) { + + val bulkSequenced = BulkResourceSequencingUtils.process(resourceAssignments) + val resourceAssignmentRuntimeService = + ResourceAssignmentUtils.transformToRARuntimeService(blueprintRuntimeService, identifierName) + + bulkSequenced.map { batchResourceAssignments -> + batchResourceAssignments.filter { it.name != "*" && it.name != "start" } + .forEach { resourceAssignment -> + val dictionaryName = resourceAssignment.dictionaryName + val dictionarySource = resourceAssignment.dictionarySource + /** + * Get the Processor name + */ + val processorName = processorName(dictionaryName!!, dictionarySource!!, resourceDictionaries) + + val resourceAssignmentProcessor = + applicationContext.getBean(processorName) as? ResourceAssignmentProcessor + ?: throw BluePrintProcessorException("failed to get resource processor for name($processorName) " + + "for resource assignment(${resourceAssignment.name})") + try { + // Set BluePrint Runtime Service + resourceAssignmentProcessor.raRuntimeService = resourceAssignmentRuntimeService + // Set Resource Dictionaries + resourceAssignmentProcessor.resourceDictionaries = resourceDictionaries + // Invoke Apply Method + resourceAssignmentProcessor.apply(resourceAssignment) + + // Set errors from RA + blueprintRuntimeService.setBluePrintError(resourceAssignmentRuntimeService.getBluePrintError()) + } catch (e: RuntimeException) { + throw BluePrintProcessorException(e) + } + } + } + } + + + /** + * If the Source instance is "input", then it is not mandatory to have source Resource Definition, So it can + * derive the default input processor. + */ + private fun processorName(dictionaryName: String, dictionarySource: String, + resourceDictionaries: MutableMap): String { + var processorName: String? = null + when (dictionarySource) { + "input" -> { + processorName = "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input" + } + "default" -> { + processorName = "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default" + } + else -> { + val resourceDefinition = resourceDictionaries[dictionaryName] + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dictionaryName") + + val resourceSource = resourceDefinition.sources[dictionarySource] + ?: throw BluePrintProcessorException("couldn't get resource definition $dictionaryName source($dictionarySource)") + + processorName = ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR + .plus(resourceSource.type) + } + } + checkNotEmptyOrThrow(processorName, + "couldn't get processor name for resource dictionary definition($dictionaryName) source" + + "($dictionarySource)") + + return processorName + + } +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt new file mode 100644 index 000000000..604d4d40b --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceSourceProperties.kt @@ -0,0 +1,79 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution + +import com.fasterxml.jackson.annotation.JsonProperty + +open class ResourceSourceProperties + +open class InputResourceSource : ResourceSourceProperties() { + lateinit var key: String + @get:JsonProperty("key-dependencies") + lateinit var keyDependencies: MutableList +} + +open class DefaultResourceSource : ResourceSourceProperties() { + lateinit var key: String + @get:JsonProperty("key-dependencies") + lateinit var keyDependencies: MutableList +} + +open class DatabaseResourceSource : ResourceSourceProperties() { + lateinit var type: String + @get:JsonProperty("endpoint-selector") + var endpointSelector: String? = null + lateinit var query: String + @get:JsonProperty("input-key-mapping") + var inputKeyMapping: MutableMap? = null + @get:JsonProperty("output-key-mapping") + var outputKeyMapping: MutableMap? = null + @get:JsonProperty("key-dependencies") + lateinit var keyDependencies: MutableList +} + +open class RestResourceSource : ResourceSourceProperties() { + lateinit var verb: String + @get:JsonProperty("payload") + var payload: String? = null + lateinit var type: String + @get:JsonProperty("endpoint-selector") + var endpointSelector: String? = null + @get:JsonProperty("url-path") + lateinit var urlPath: String + lateinit var path: String + @get:JsonProperty("expression-type") + lateinit var expressionType: String + @get:JsonProperty("input-key-mapping") + var inputKeyMapping: MutableMap? = null + @get:JsonProperty("output-key-mapping") + var outputKeyMapping: MutableMap? = null + @get:JsonProperty("key-dependencies") + lateinit var keyDependencies: MutableList +} + +open class CapabilityResourceSource : ResourceSourceProperties() { + @get:JsonProperty("script-type") + lateinit var scriptType: String + @get:JsonProperty("script-class-reference") + lateinit var scriptClassReference: String + @get:JsonProperty("instance-dependencies") + var instanceDependencies: List? = null + @get:JsonProperty("key-dependencies") + lateinit var keyDependencies: MutableList +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt new file mode 100644 index 000000000..72bb4a384 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionRepository.kt @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db + +import org.springframework.data.jpa.repository.JpaRepository + +interface ResourceResolutionRepository : JpaRepository { + + fun findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(key: String, blueprintName: String?, + blueprintVersion: String?, + artifactName: String): ResourceResolutionResult +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt new file mode 100755 index 000000000..c9b747e59 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResult.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db + +import com.fasterxml.jackson.annotation.JsonFormat +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.Column +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 + +@EntityListeners(AuditingEntityListener::class) +@Entity +@Table(name = "RESOURCE_RESOLUTION_RESULT") +@Proxy(lazy = false) +class ResourceResolutionResult : Serializable { + + @Id + @Column(name = "resource_resolution_result_id") + var id: String? = null + + @Column(name = "resolution_key", nullable = false) + var resolutionKey: String? = null + + @Column(name = "blueprint_name", nullable = false) + var blueprintName: String? = null + + @Column(name = "blueprint_version", nullable = false) + var blueprintVersion: String? = null + + @Column(name = "artifact_name", nullable = false) + var artifactName: String? = null + + @Lob + @Column(name = "result", nullable = false) + var result: String? = null + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + @LastModifiedDate + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "creation_date") + var createdDate = Date() + + companion object { + private const val serialVersionUID = 1L + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt new file mode 100644 index 000000000..225251fce --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/db/ResourceResolutionResultService.kt @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.dao.DataIntegrityViolationException +import org.springframework.stereotype.Service +import java.util.* + +@Service +class ResourceResolutionResultService(private val resourceResolutionRepository: ResourceResolutionRepository) { + + fun write(properties: Map, result: String, bluePrintRuntimeService: BluePrintRuntimeService<*>, + artifactPrefix: String) { + + val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! + + val resourceResolutionResult = ResourceResolutionResult() + resourceResolutionResult.id = UUID.randomUUID().toString() + resourceResolutionResult.artifactName = artifactPrefix + resourceResolutionResult.blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] + resourceResolutionResult.blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + resourceResolutionResult.resolutionKey = + properties[ResourceResolutionConstants.RESOURCE_RESOLUTION_INPUT_KEY].toString() + resourceResolutionResult.result = result + + try { + resourceResolutionRepository.saveAndFlush(resourceResolutionResult) + } catch (ex: DataIntegrityViolationException) { + throw BluePrintException("Failed to store resource resolution result.", ex) + } + } + + fun read(bluePrintRuntimeService: BluePrintRuntimeService<*>, artifactPrefix: String, + resolutionKey: String): String { + + val metadata = bluePrintRuntimeService.bluePrintContext().metadata!! + + val blueprintVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] + val blueprintName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + + return resourceResolutionRepository.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName( + resolutionKey, + blueprintName, + blueprintVersion, + artifactPrefix).result!! + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt new file mode 100644 index 000000000..ae08a1cf9 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessor.kt @@ -0,0 +1,104 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution.processor + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.CapabilityResourceSource +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.ApplicationContext +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-capability") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class CapabilityResourceResolutionProcessor(private val applicationContext: ApplicationContext, + private var componentFunctionScriptingService: ComponentFunctionScriptingService) + : ResourceAssignmentProcessor() { + + private val log = LoggerFactory.getLogger(CapabilityResourceResolutionProcessor::class.java) + + var componentResourceAssignmentProcessor: ResourceAssignmentProcessor? = null + + override fun getName(): String { + return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-capability" + } + + override fun process(resourceAssignment: ResourceAssignment) { + + val resourceDefinition = resourceDictionaries[resourceAssignment.dictionaryName] + ?: throw BluePrintProcessorException("couldn't get resource definition for ${resourceAssignment.dictionaryName}") + + val resourceSource = resourceDefinition.sources[resourceAssignment.dictionarySource] + ?: throw BluePrintProcessorException("couldn't get resource definition " + + "${resourceAssignment.dictionaryName} source(${resourceAssignment.dictionarySource})") + + val resourceSourceProps = checkNotNull(resourceSource.properties) { "failed to get $resourceSource properties" } + /** + * Get the Capability Resource Source Info from Property Definitions. + */ + val capabilityResourceSourceProperty = JacksonUtils + .getInstanceFromMap(resourceSourceProps, CapabilityResourceSource::class.java) + + val scriptType = capabilityResourceSourceProperty.scriptType + val scriptClassReference = capabilityResourceSourceProperty.scriptClassReference + val instanceDependencies = capabilityResourceSourceProperty.instanceDependencies ?: listOf() + + componentResourceAssignmentProcessor = scriptInstance(scriptType, scriptClassReference, instanceDependencies) + + checkNotNull(componentResourceAssignmentProcessor) { + "failed to get capability resource assignment processor($scriptClassReference)" + } + + // Assign Current Blueprint runtime and ResourceDictionaries + componentResourceAssignmentProcessor!!.raRuntimeService = raRuntimeService + componentResourceAssignmentProcessor!!.resourceDictionaries = resourceDictionaries + + // Invoke componentResourceAssignmentProcessor + componentResourceAssignmentProcessor!!.apply(resourceAssignment) + } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + log.info("Recovering for : ${resourceAssignment.name} : ${runtimeException.toString()}") + if (componentResourceAssignmentProcessor != null) { + componentResourceAssignmentProcessor!!.recover(runtimeException, resourceAssignment) + } + } + + fun scriptInstance(scriptType: String, scriptClassReference: String, instanceDependencies: List) + : ResourceAssignmentProcessor { + + log.info("creating resource resolution of script type($scriptType), reference name($scriptClassReference) and" + + "instanceDependencies($instanceDependencies)") + + val scriptComponent = componentFunctionScriptingService + .scriptInstance(raRuntimeService.bluePrintContext(), scriptType, + scriptClassReference) + + instanceDependencies.forEach { instanceDependency -> + scriptPropertyInstances[instanceDependency] = applicationContext + .getBean(instanceDependency) + } + return scriptComponent + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt new file mode 100644 index 000000000..d190ee53c --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DatabaseResourceAssignmentProcessor.kt @@ -0,0 +1,190 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution.processor + +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.MissingNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.BluePrintDBLibPropertySevice +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.PrimaryDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.DatabaseResourceSource +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.controllerblueprints.core.* +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.ResourceDictionaryConstants +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service +import java.util.* + +/** + * DatabaseResourceAssignmentProcessor + * + * @author Kapil Singal + */ +@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class DatabaseResourceAssignmentProcessor(private val bluePrintDBLibPropertySevice: BluePrintDBLibPropertySevice, private val primaryDBLibGenericService: PrimaryDBLibGenericService) + : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(DatabaseResourceAssignmentProcessor::class.java) + + override fun getName(): String { + return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-processor-db" + } + + override fun process(resourceAssignment: ResourceAssignment) { + try { + validate(resourceAssignment) + + // Check if It has Input + try { + val value = raRuntimeService.getInputValue(resourceAssignment.name) + if (value !is NullNode && value !is MissingNode) { + logger.info("processor-db source template key (${resourceAssignment.name}) found from input and value is ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } else { + setValueFromDB(resourceAssignment) + } + } catch (e: BluePrintProcessorException) { + setValueFromDB(resourceAssignment) + } + + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", e) + } + } + + private fun setValueFromDB(resourceAssignment: ResourceAssignment) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val resourceDefinition = resourceDictionaries[dName] + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") + val resourceSource = resourceDefinition.sources[dSource] + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") + val resourceSourceProperties = checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } + val sourceProperties = JacksonUtils.getInstanceFromMap(resourceSourceProperties, DatabaseResourceSource::class.java) + + val sql = checkNotNull(sourceProperties.query) { "failed to get request query for $dName under $dSource properties" } + val inputKeyMapping = checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } + + logger.info("$dSource dictionary information : ($sql), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") + val jdbcTemplate = blueprintDBLibService(sourceProperties) + + val rows = jdbcTemplate.query(sql, populateNamedParameter(inputKeyMapping)) + if (rows.isNullOrEmpty()) { + logger.warn("Failed to get $dSource result for dictionary name ($dName) the query ($sql)") + } else { + populateResource(resourceAssignment, sourceProperties, rows) + } + } + + private fun blueprintDBLibService(sourceProperties: DatabaseResourceSource): BluePrintDBLibGenericService { + return if (checkNotEmpty(sourceProperties.endpointSelector)) { + val dbPropertiesJson = raRuntimeService.resolveDSLExpression(sourceProperties.endpointSelector!!) + bluePrintDBLibPropertySevice.JdbcTemplate(dbPropertiesJson) + } else { + primaryDBLibGenericService + } + + } + + @Throws(BluePrintProcessorException::class) + private fun validate(resourceAssignment: ResourceAssignment) { + checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") + checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PROCESSOR_DB, resourceAssignment.dictionarySource) { + "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PROCESSOR_DB} but it is ${resourceAssignment.dictionarySource}" + } + } + + private fun populateNamedParameter(inputKeyMapping: Map): Map { + val namedParameters = HashMap() + inputKeyMapping.forEach { + val expressionValue = raRuntimeService.getDictionaryStore(it.value).textValue() + logger.trace("Reference dictionary key (${it.key}) resulted in value ($expressionValue)") + namedParameters[it.key] = expressionValue + } + logger.info("Parameter information : ({})", namedParameters) + return namedParameters + } + + @Throws(BluePrintProcessorException::class) + private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: DatabaseResourceSource, rows: List>) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val type = nullToEmpty(resourceAssignment.property?.type) + + val outputKeyMapping = checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } + logger.info("Response processing type($type)") + + // Primitive Types + when (type) { + in BluePrintTypes.validPrimitiveTypes() -> { + val dbColumnValue = rows[0][outputKeyMapping[dName]] + logger.info("For template key (${resourceAssignment.name}) setting value as ($dbColumnValue)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, dbColumnValue) + } + in BluePrintTypes.validCollectionTypes() -> { + val entrySchemaType = returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } + val arrayNode = JsonNodeFactory.instance.arrayNode() + rows.forEach { + if (entrySchemaType in BluePrintTypes.validPrimitiveTypes()) { + val dbColumnValue = it[outputKeyMapping[dName]] + // Add Array JSON + JacksonUtils.populatePrimitiveValues(dbColumnValue!!, entrySchemaType, arrayNode) + } else { + val arrayChildNode = JsonNodeFactory.instance.objectNode() + for (mapping in outputKeyMapping.entries) { + val dbColumnValue = checkNotNull(it[mapping.key]) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, mapping.key) + JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, arrayChildNode) + } + arrayNode.add(arrayChildNode) + } + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) + } + else -> { + // Complex Types + val row = rows[0] + val objectNode = JsonNodeFactory.instance.objectNode() + for (mapping in outputKeyMapping.entries) { + val dbColumnValue = checkNotNull(row[mapping.key]) + val propertyTypeForDataType = ResourceAssignmentUtils.getPropertyType(raRuntimeService, type, mapping.key) + JacksonUtils.populatePrimitiveValues(mapping.key, dbColumnValue, propertyTypeForDataType, objectNode) + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) + } + } + } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + raRuntimeService.getBluePrintError().addError(runtimeException.message!!) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt new file mode 100644 index 000000000..ed9024d25 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/DefaultResourceResolutionProcessor.kt @@ -0,0 +1,65 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor + +import com.fasterxml.jackson.databind.node.MissingNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +/** + * DefaultResourceResolutionProcessor + * + * @author Kapil Singal + */ +@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class DefaultResourceResolutionProcessor : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(DefaultResourceResolutionProcessor::class.java) + + override fun getName(): String { + return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-default" + } + + override fun process(resourceAssignment: ResourceAssignment) { + try { + var value = getFromInput(resourceAssignment) + if (value == null || value is MissingNode) { + value = resourceAssignment.property?.defaultValue + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", + e) + } + + } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + raRuntimeService.getBluePrintError().addError(runtimeException.message!!) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt new file mode 100644 index 000000000..9fa72ca94 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/InputResourceResolutionProcessor.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor + +import com.fasterxml.jackson.databind.node.MissingNode +import com.fasterxml.jackson.databind.node.NullNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +/** + * InputResourceResolutionProcessor + * + * @author Kapil Singal + */ +@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class InputResourceResolutionProcessor : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(InputResourceResolutionProcessor::class.java) + + override fun getName(): String { + return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-input" + } + + override fun process(resourceAssignment: ResourceAssignment) { + try { + if (checkNotEmpty(resourceAssignment.name)) { + val value = raRuntimeService.getInputValue(resourceAssignment.name) + // if value is null don't call setResourceDataValue to populate the value + if (value !is MissingNode && value !is NullNode) { + logger.info("input source template key (${resourceAssignment.name}) found from input and value is ($value)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } + } + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with : (${e.message})", e) + } + } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + raRuntimeService.getBluePrintError().addError(runtimeException.message!!) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt new file mode 100644 index 000000000..97e2f2c69 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/ResourceAssignmentProcessor.kt @@ -0,0 +1,115 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution.processor + +import com.fasterxml.jackson.databind.JsonNode +import org.apache.commons.collections.MapUtils +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintTemplateService +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.slf4j.LoggerFactory +import java.util.* + +abstract class ResourceAssignmentProcessor : BlueprintFunctionNode { + + private val log = LoggerFactory.getLogger(ResourceAssignmentProcessor::class.java) + + lateinit var raRuntimeService: ResourceAssignmentRuntimeService + lateinit var resourceDictionaries: MutableMap + + var scriptPropertyInstances: MutableMap = hashMapOf() + + /** + * This will be called from the scripts to serve instance from runtime to scripts. + */ + open fun scriptPropertyInstanceType(name: String): T { + return scriptPropertyInstances as? T + ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") + } + + open fun getFromInput(resourceAssignment: ResourceAssignment): JsonNode? { + var value: JsonNode? = null + try { + value = raRuntimeService.getInputValue(resourceAssignment.name) + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, value) + } catch (e: BluePrintProcessorException) { + // NoOp - couldn't find value from input + } + return value + } + + open fun resourceDefinition(name: String): ResourceDefinition { + return resourceDictionaries[name] + ?: throw BluePrintProcessorException("couldn't get resource definition for ($name)") + } + + open fun resolveInputKeyMappingVariables(inputKeyMapping: Map): Map { + val resolvedInputKeyMapping = HashMap() + if (MapUtils.isNotEmpty(inputKeyMapping)) { + for ((key, value) in inputKeyMapping) { + val resultValue = raRuntimeService.getResolutionStore(value) + val expressionValue = JacksonUtils.getValue(resultValue) + log.trace("Reference dictionary key ({}), value ({})", key, expressionValue) + resolvedInputKeyMapping[key] = expressionValue + } + } + return resolvedInputKeyMapping + } + + open fun resolveFromInputKeyMapping(valueToResolve: String, keyMapping: Map): String { + if (valueToResolve.isEmpty() || !valueToResolve.contains("$")) { + return valueToResolve + } + return BluePrintTemplateService.generateContent(valueToResolve, additionalContext = keyMapping) + } + + override fun prepareRequest(resourceAssignment: ResourceAssignment): ResourceAssignment { + log.info("prepareRequest for ${resourceAssignment.name}, dictionary(${resourceAssignment.dictionaryName})," + + "source(${resourceAssignment.dictionarySource})") + return resourceAssignment + } + + override fun prepareResponse(): Boolean { + log.info("Preparing Response...") + return true + } + + override fun apply(resourceAssignment: ResourceAssignment): Boolean { + try { + prepareRequest(resourceAssignment) + process(resourceAssignment) + } catch (runtimeException: RuntimeException) { + recover(runtimeException, resourceAssignment) + } + return prepareResponse() + } + + fun addError(type: String, name: String, error: String) { + raRuntimeService.getBluePrintError().addError(type, name, error) + } + + fun addError(error: String) { + raRuntimeService.getBluePrintError().addError(error) + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt new file mode 100644 index 000000000..0c36a1e42 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/RestResourceResolutionProcessor.kt @@ -0,0 +1,204 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution.processor + +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import com.fasterxml.jackson.databind.node.MissingNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.checkEqualsOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmptyOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.returnNotEmptyOrThrow +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.ResourceDictionaryConstants +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Service + +/** + * RestResourceResolutionProcessor + * + * @author Kapil Singal + */ +@Service("${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class RestResourceResolutionProcessor(private val blueprintRestLibPropertyService: BluePrintRestLibPropertyService) + : ResourceAssignmentProcessor() { + + private val logger = LoggerFactory.getLogger(RestResourceResolutionProcessor::class.java) + + override fun getName(): String { + return "${PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest" + } + + override fun process(resourceAssignment: ResourceAssignment) { + try { + validate(resourceAssignment) + + // Check if It has Input + val value = getFromInput(resourceAssignment) + if (value == null || value is MissingNode) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val resourceDefinition = resourceDictionaries[dName] + ?: throw BluePrintProcessorException("couldn't get resource dictionary definition for $dName") + val resourceSource = resourceDefinition.sources[dSource] + ?: throw BluePrintProcessorException("couldn't get resource definition $dName source($dSource)") + val resourceSourceProperties = + checkNotNull(resourceSource.properties) { "failed to get source properties for $dName " } + val sourceProperties = + JacksonUtils.getInstanceFromMap(resourceSourceProperties, RestResourceSource::class.java) + val path = nullToEmpty(sourceProperties.path) + val inputKeyMapping = + checkNotNull(sourceProperties.inputKeyMapping) { "failed to get input-key-mappings for $dName under $dSource properties" } + val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping) + + // Resolving content Variables + val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping) + val urlPath = + resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping) + val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping) + + logger.info("$dSource dictionary information : ($urlPath), ($inputKeyMapping), (${sourceProperties.outputKeyMapping})") + // Get the Rest Client Service + val restClientService = blueprintWebClientService(resourceAssignment, sourceProperties) + + val response = restClientService.exchangeResource(verb, urlPath, payload) + if (response.isBlank()) { + logger.warn("Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath)") + } else { + populateResource(resourceAssignment, sourceProperties, response, path) + } + } + // Check the value has populated for mandatory case + ResourceAssignmentUtils.assertTemplateKeyValueNotNull(resourceAssignment) + } catch (e: Exception) { + ResourceAssignmentUtils.setFailedResourceDataValue(resourceAssignment, e.message) + throw BluePrintProcessorException("Failed in template key ($resourceAssignment) assignments with: ${e.message}", + e) + } + } + + private fun blueprintWebClientService(resourceAssignment: ResourceAssignment, + restResourceSource: RestResourceSource): BlueprintWebClientService { + return if (checkNotEmpty(restResourceSource.endpointSelector)) { + val restPropertiesJson = raRuntimeService.resolveDSLExpression(restResourceSource.endpointSelector!!) + blueprintRestLibPropertyService.blueprintWebClientService(restPropertiesJson) + } else { + blueprintRestLibPropertyService.blueprintWebClientService(resourceAssignment.dictionarySource!!) + } + } + + @Throws(BluePrintProcessorException::class) + private fun populateResource(resourceAssignment: ResourceAssignment, sourceProperties: RestResourceSource, + restResponse: String, path: String) { + val dName = resourceAssignment.dictionaryName + val dSource = resourceAssignment.dictionarySource + val type = nullToEmpty(resourceAssignment.property?.type) + lateinit var entrySchemaType: String + + val outputKeyMapping = + checkNotNull(sourceProperties.outputKeyMapping) { "failed to get output-key-mappings for $dName under $dSource properties" } + logger.info("Response processing type($type)") + + val responseNode = + checkNotNull(JacksonUtils.jsonNode(restResponse).at(path)) { "Failed to find path ($path) in response ($restResponse)" } + logger.info("populating value for output mapping ($outputKeyMapping), from json ($responseNode)") + + + when (type) { + in BluePrintTypes.validPrimitiveTypes() -> { + logger.info("For template key (${resourceAssignment.name}) setting value as ($responseNode)") + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode) + } + in BluePrintTypes.validCollectionTypes() -> { + // Array Types + entrySchemaType = + returnNotEmptyOrThrow(resourceAssignment.property?.entrySchema?.type) { "Entry schema is not defined for dictionary ($dName) info" } + val arrayNode = responseNode as ArrayNode + + if (entrySchemaType !in BluePrintTypes.validPrimitiveTypes()) { + val responseArrayNode = responseNode.toList() + for (responseSingleJsonNode in responseArrayNode) { + val arrayChildNode = JsonNodeFactory.instance.objectNode() + outputKeyMapping.map { + val responseKeyValue = responseSingleJsonNode.get(it.key) + val propertyTypeForDataType = + ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) + logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") + JacksonUtils.populateJsonNodeValues(it.value, + responseKeyValue, + propertyTypeForDataType, + arrayChildNode) + } + arrayNode.add(arrayChildNode) + } + } + logger.info("For template key (${resourceAssignment.name}) setting value as ($arrayNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode) + } + else -> { + // Complex Types + entrySchemaType = + returnNotEmptyOrThrow(resourceAssignment.property?.type) { "Entry schema is not defined for dictionary ($dName) info" } + val objectNode = JsonNodeFactory.instance.objectNode() + outputKeyMapping.map { + val responseKeyValue = responseNode.get(it.key) + val propertyTypeForDataType = + ResourceAssignmentUtils.getPropertyType(raRuntimeService, entrySchemaType, it.key) + logger.info("For List Type Resource: key (${it.key}), value ($responseKeyValue), type ({$propertyTypeForDataType})") + JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode) + } + + logger.info("For template key (${resourceAssignment.name}) setting value as ($objectNode)") + // Set the List of Complex Values + ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode) + } + } + } + + @Throws(BluePrintProcessorException::class) + private fun validate(resourceAssignment: ResourceAssignment) { + checkNotEmptyOrThrow(resourceAssignment.name, "resource assignment template key is not defined") + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, + "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") + checkEqualsOrThrow(ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA, + resourceAssignment.dictionarySource) { + "resource assignment source is not ${ResourceDictionaryConstants.SOURCE_PRIMARY_CONFIG_DATA} but it is ${resourceAssignment.dictionarySource}" + } + checkNotEmptyOrThrow(resourceAssignment.dictionaryName, + "resource assignment dictionary name is not defined for template key (${resourceAssignment.name})") + } + + override fun recover(runtimeException: RuntimeException, resourceAssignment: ResourceAssignment) { + raRuntimeService.getBluePrintError().addError(runtimeException.message!!) + } + + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt new file mode 100644 index 000000000..7f4f452ac --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/utils/ResourceAssignmentUtils.kt @@ -0,0 +1,159 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils + +import com.att.eelf.configuration.EELFLogger +import com.att.eelf.configuration.EELFManager +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.node.NullNode +import com.fasterxml.jackson.databind.node.ObjectNode +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintTypes +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmptyOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty +import org.onap.ccsdk.cds.controllerblueprints.core.returnNotEmptyOrThrow +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 java.util.* + +class ResourceAssignmentUtils { + companion object { + + private val logger: EELFLogger = EELFManager.getInstance().getLogger(ResourceAssignmentUtils::class.toString()) + + // TODO("Modify Value type from Any to JsonNode") + @Throws(BluePrintProcessorException::class) + fun setResourceDataValue(resourceAssignment: ResourceAssignment, + raRuntimeService: ResourceAssignmentRuntimeService, value: Any?) { + + val resourceProp = checkNotNull(resourceAssignment.property) { "Failed in setting resource value for resource mapping $resourceAssignment" } + checkNotEmptyOrThrow(resourceAssignment.name, "Failed in setting resource value for resource mapping $resourceAssignment") + + if (resourceAssignment.dictionaryName.isNullOrEmpty()) { + resourceAssignment.dictionaryName = resourceAssignment.name + logger.warn("Missing dictionary key, setting with template key (${resourceAssignment.name}) as dictionary key (${resourceAssignment.dictionaryName})") + } + + try { + if (resourceProp.type.isNotEmpty()) { + val convertedValue = convertResourceValue(resourceProp.type, value) + logger.info("Setting Resource Value ($convertedValue) for Resource Name (${resourceAssignment.dictionaryName}) of type (${resourceProp.type})") + setResourceValue(resourceAssignment, raRuntimeService, convertedValue) + resourceAssignment.updatedDate = Date() + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_SUCCESS + } + } catch (e: Exception) { + throw BluePrintProcessorException("Failed in setting value for template key (${resourceAssignment.name}) and " + + "dictionary key (${resourceAssignment.dictionaryName}) of type (${resourceProp.type}) with error message (${e.message})", e) + } + } + + private fun setResourceValue(resourceAssignment: ResourceAssignment, raRuntimeService: ResourceAssignmentRuntimeService, value: JsonNode) { + raRuntimeService.putResolutionStore(resourceAssignment.name, value) + raRuntimeService.putDictionaryStore(resourceAssignment.dictionaryName!!, value) + resourceAssignment.property!!.value = value + } + + private fun convertResourceValue(type: String, value: Any?): JsonNode { + + return if (value == null || value is NullNode) { + logger.info("Returning {} value from convertResourceValue", value) + NullNode.instance + } else if (BluePrintTypes.validPrimitiveTypes().contains(type) && value is String) { + JacksonUtils.convertPrimitiveResourceValue(type, value) + } else if (value is String) { + JacksonUtils.jsonNode(value) + } else { + JacksonUtils.getJsonNode(value) + } + + } + + fun setFailedResourceDataValue(resourceAssignment: ResourceAssignment, message: String?) { + if (checkNotEmpty(resourceAssignment.name)) { + resourceAssignment.updatedDate = Date() + resourceAssignment.updatedBy = BluePrintConstants.USER_SYSTEM + resourceAssignment.status = BluePrintConstants.STATUS_FAILURE + resourceAssignment.message = message + } + } + + @Throws(BluePrintProcessorException::class) + fun assertTemplateKeyValueNotNull(resourceAssignment: ResourceAssignment) { + val resourceProp = checkNotNull(resourceAssignment.property) { "Failed to populate mandatory resource resource mapping $resourceAssignment" } + if (resourceProp.required != null && resourceProp.required!! && (resourceProp.value == null || resourceProp.value !is NullNode)) { + logger.error("failed to populate mandatory resource mapping ($resourceAssignment)") + throw BluePrintProcessorException("failed to populate mandatory resource mapping ($resourceAssignment)") + } + } + + @Throws(BluePrintProcessorException::class) + fun generateResourceDataForAssignments(assignments: List): String { + val result: String + try { + val mapper = ObjectMapper() + val root: ObjectNode = mapper.createObjectNode() + + assignments.forEach { + if (checkNotEmpty(it.name) && it.property != null) { + val rName = it.name + val type = nullToEmpty(it.property?.type).toLowerCase() + val value = it.property?.value + logger.info("Generating Resource name ($rName), type ($type), value ($value)") + root.set(rName, value) + } + } + result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root) + logger.info("Generated Resource Param Data ($result)") + } catch (e: Exception) { + throw BluePrintProcessorException("Resource Assignment is failed with $e.message", e) + } + + return result + } + + fun transformToRARuntimeService(blueprintRuntimeService: BluePrintRuntimeService<*>, templateArtifactName: String): ResourceAssignmentRuntimeService { + val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService(blueprintRuntimeService.id(), blueprintRuntimeService.bluePrintContext()) + resourceAssignmentRuntimeService.createUniqueId(templateArtifactName) + resourceAssignmentRuntimeService.setExecutionContext(blueprintRuntimeService.getExecutionContext() as MutableMap) + + return resourceAssignmentRuntimeService + } + + @Throws(BluePrintProcessorException::class) + fun getPropertyType(raRuntimeService: ResourceAssignmentRuntimeService, dataTypeName: String, propertyName: String): String { + lateinit var type: String + try { + val dataTypeProps = checkNotNull(raRuntimeService.bluePrintContext().dataTypeByName(dataTypeName)?.properties) + val propertyDefinition = checkNotNull(dataTypeProps[propertyName]) + type = returnNotEmptyOrThrow(propertyDefinition.type) { "Couldn't get data type ($dataTypeName)" } + logger.trace("Data type({})'s property ({}) is ({})", dataTypeName, propertyName, type) + } catch (e: Exception) { + logger.error("couldn't get data type($dataTypeName)'s property ($propertyName), error message $e") + throw BluePrintProcessorException("${e.message}", e) + } + return type + } + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt deleted file mode 100644 index 91997e34a..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import com.fasterxml.jackson.databind.JsonNode -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration -import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -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 - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [ResourceResolutionServiceImpl::class, - InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class, - DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class, - CapabilityResourceResolutionProcessor::class, - BlueprintPropertyConfiguration::class, BluePrintProperties::class, - BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@EnableAutoConfiguration -class ResourceResolutionComponentTest { - - @Autowired - lateinit var resourceResolutionComponent: ResourceResolutionComponent - - @Test - fun testProcess() { - - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json", - ExecutionServiceInput::class.java)!! - - // Prepare Inputs - PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService, executionServiceInput.payload, "resource-assignment") - - val stepMetaData: MutableMap = hashMapOf() - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "resource-assignment") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ResourceResolutionComponent") - stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") - bluePrintRuntimeService.put("resource-assignment-step-inputs", stepMetaData.asJsonNode()) - - resourceResolutionComponent.bluePrintRuntimeService = bluePrintRuntimeService - resourceResolutionComponent.stepName = "resource-assignment" - resourceResolutionComponent.apply(executionServiceInput) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt deleted file mode 100644 index d560e8c35..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution - -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.utils.PayloadUtils -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.* -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -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.context.ContextConfiguration -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -/** - * ResourceResolutionServiceTest - * - * @author Brinda Santh DATE : 8/15/2018 - */ -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [ResourceResolutionServiceImpl::class, - InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class, - DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class, - CapabilityResourceResolutionProcessor::class, - BlueprintPropertyConfiguration::class, BluePrintProperties::class, - BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@EnableAutoConfiguration -class ResourceResolutionServiceTest { - - private val log = LoggerFactory.getLogger(ResourceResolutionServiceTest::class.java) - - @Autowired - lateinit var resourceResolutionService: ResourceResolutionService - - @Test - fun testRegisteredSource() { - val sources = resourceResolutionService.registeredResourceSources() - assertNotNull(sources, "failed to get registered sources") - assertTrue(sources.containsAll(arrayListOf("source-input", "source-default", "source-processor-db", - "source-rest")), "failed to get registered sources : $sources") - } - - @Test - @Throws(Exception::class) - fun testResolveResource() { - - Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) - - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json", - ExecutionServiceInput::class.java)!! - - // Prepare Inputs - PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService, executionServiceInput.payload, "resource-assignment") - - resourceResolutionService.resolveResources(bluePrintRuntimeService, "resource-assignment", "baseconfig", mapOf()) - - } - -} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt deleted file mode 100644 index 5a14a2964..000000000 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor - -import org.junit.Ignore -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.BlueprintJythonService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.PythonExecutorProperty -import org.onap.ccsdk.apps.controllerblueprints.core.data.PropertyDefinition -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceAssignment -import org.onap.ccsdk.apps.controllerblueprints.resource.dict.ResourceDefinition -import org.onap.ccsdk.apps.controllerblueprints.scripts.BluePrintScriptsServiceImpl -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 - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [CapabilityResourceResolutionProcessor::class, ComponentFunctionScriptingService::class, - BluePrintScriptsServiceImpl::class, - BlueprintJythonService::class, PythonExecutorProperty::class, MockCapabilityService::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"]) -class CapabilityResourceResolutionProcessorTest { - - @Autowired - lateinit var capabilityResourceResolutionProcessor: CapabilityResourceResolutionProcessor - - @Ignore - @Test - fun `test kotlin capability`() { - - val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( - "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) - - capabilityResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService - capabilityResourceResolutionProcessor.resourceDictionaries = hashMapOf() - - - val scriptPropertyInstances: MutableMap = mutableMapOf() - scriptPropertyInstances["mock-service1"] = MockCapabilityService() - scriptPropertyInstances["mock-service2"] = MockCapabilityService() - - val instanceDependencies: List = listOf() - - val resourceAssignmentProcessor = capabilityResourceResolutionProcessor - .scriptInstance("kotlin", - "ResourceAssignmentProcessor_cba\$ScriptResourceAssignmentProcessor", instanceDependencies) - - assertNotNull(resourceAssignmentProcessor, "couldn't get kotlin script resource assignment processor") - - val resourceAssignment = ResourceAssignment().apply { - name = "ra-name" - dictionaryName = "ra-dict-name" - dictionarySource = "capability" - property = PropertyDefinition().apply { - type = "string" - } - } - - val processorName = resourceAssignmentProcessor.apply(resourceAssignment) - assertNotNull(processorName, "couldn't get kotlin script resource assignment processor name") - println(processorName) - } - - @Test - fun `test jython capability`() { - - val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( - "./../../../../components/model-catalog/blueprint-model/test-blueprint/capability_python") - - val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) - - capabilityResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService - - val resourceDefinition = JacksonUtils - .readValueFromClassPathFile("mapping/capability/jython-resource-definitions.json", - ResourceDefinition::class.java)!! - val resourceDefinitions: MutableMap = mutableMapOf() - resourceDefinitions[resourceDefinition.name] = resourceDefinition - capabilityResourceResolutionProcessor.resourceDictionaries = resourceDefinitions - - val resourceAssignment = ResourceAssignment().apply { - name = "service-instance-id" - dictionaryName = "service-instance-id" - dictionarySource = "capability" - property = PropertyDefinition().apply { - type = "string" - } - } - - val processorName = capabilityResourceResolutionProcessor.apply(resourceAssignment) - assertNotNull(processorName, "couldn't get Jython script resource assignment processor name") - - } - -} - -open class MockCapabilityService { - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt new file mode 100644 index 000000000..8a5ffac76 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionComponentTest.kt @@ -0,0 +1,79 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import com.fasterxml.jackson.databind.JsonNode +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.* +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +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 + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [ResourceResolutionServiceImpl::class, + InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class, + DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class, + CapabilityResourceResolutionProcessor::class, + BlueprintPropertyConfiguration::class, BluePrintProperties::class, + BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@EnableAutoConfiguration +class ResourceResolutionComponentTest { + + @Autowired + lateinit var resourceResolutionComponent: ResourceResolutionComponent + + @Test + fun testProcess() { + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", + "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json", + ExecutionServiceInput::class.java)!! + + // Prepare Inputs + PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService, executionServiceInput.payload, "resource-assignment") + + val stepMetaData: MutableMap = hashMapOf() + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, "resource-assignment") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, "ResourceResolutionComponent") + stepMetaData.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, "process") + bluePrintRuntimeService.put("resource-assignment-step-inputs", stepMetaData.asJsonNode()) + + resourceResolutionComponent.bluePrintRuntimeService = bluePrintRuntimeService + resourceResolutionComponent.stepName = "resource-assignment" + resourceResolutionComponent.apply(executionServiceInput) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt new file mode 100644 index 000000000..433ee1d85 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/ResourceResolutionServiceTest.kt @@ -0,0 +1,91 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution + +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.utils.PayloadUtils +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.* +import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +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.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * ResourceResolutionServiceTest + * + * @author Brinda Santh DATE : 8/15/2018 + */ +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [ResourceResolutionServiceImpl::class, + InputResourceResolutionProcessor::class, DefaultResourceResolutionProcessor::class, + DatabaseResourceAssignmentProcessor::class, RestResourceResolutionProcessor::class, + CapabilityResourceResolutionProcessor::class, + BlueprintPropertyConfiguration::class, BluePrintProperties::class, + BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@EnableAutoConfiguration +class ResourceResolutionServiceTest { + + private val log = LoggerFactory.getLogger(ResourceResolutionServiceTest::class.java) + + @Autowired + lateinit var resourceResolutionService: ResourceResolutionService + + @Test + fun testRegisteredSource() { + val sources = resourceResolutionService.registeredResourceSources() + assertNotNull(sources, "failed to get registered sources") + assertTrue(sources.containsAll(arrayListOf("source-input", "source-default", "source-processor-db", + "source-rest")), "failed to get registered sources : $sources") + } + + @Test + @Throws(Exception::class) + fun testResolveResource() { + + Assert.assertNotNull("failed to create ResourceResolutionService", resourceResolutionService) + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", + "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("payload/requests/sample-resourceresolution-request.json", + ExecutionServiceInput::class.java)!! + + // Prepare Inputs + PayloadUtils.prepareInputsFromWorkflowPayload(bluePrintRuntimeService, executionServiceInput.payload, "resource-assignment") + + resourceResolutionService.resolveResources(bluePrintRuntimeService, "resource-assignment", "baseconfig", mapOf()) + + } + +} diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt new file mode 100644 index 000000000..8ab47b910 --- /dev/null +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/processor/CapabilityResourceResolutionProcessorTest.kt @@ -0,0 +1,126 @@ +/* + * 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.blueprintsprocessor.functions.resource.resolution.processor + +import org.junit.Ignore +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceAssignmentRuntimeService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.BlueprintJythonService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.PythonExecutorProperty +import org.onap.ccsdk.cds.controllerblueprints.core.data.PropertyDefinition +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.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.scripts.BluePrintScriptsServiceImpl +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 + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [CapabilityResourceResolutionProcessor::class, ComponentFunctionScriptingService::class, + BluePrintScriptsServiceImpl::class, + BlueprintJythonService::class, PythonExecutorProperty::class, MockCapabilityService::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"]) +class CapabilityResourceResolutionProcessorTest { + + @Autowired + lateinit var capabilityResourceResolutionProcessor: CapabilityResourceResolutionProcessor + + @Ignore + @Test + fun `test kotlin capability`() { + + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( + "./../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) + + capabilityResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService + capabilityResourceResolutionProcessor.resourceDictionaries = hashMapOf() + + + val scriptPropertyInstances: MutableMap = mutableMapOf() + scriptPropertyInstances["mock-service1"] = MockCapabilityService() + scriptPropertyInstances["mock-service2"] = MockCapabilityService() + + val instanceDependencies: List = listOf() + + val resourceAssignmentProcessor = capabilityResourceResolutionProcessor + .scriptInstance("kotlin", + "ResourceAssignmentProcessor_cba\$ScriptResourceAssignmentProcessor", instanceDependencies) + + assertNotNull(resourceAssignmentProcessor, "couldn't get kotlin script resource assignment processor") + + val resourceAssignment = ResourceAssignment().apply { + name = "ra-name" + dictionaryName = "ra-dict-name" + dictionarySource = "capability" + property = PropertyDefinition().apply { + type = "string" + } + } + + val processorName = resourceAssignmentProcessor.apply(resourceAssignment) + assertNotNull(processorName, "couldn't get kotlin script resource assignment processor name") + println(processorName) + } + + @Test + fun `test jython capability`() { + + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( + "./../../../../components/model-catalog/blueprint-model/test-blueprint/capability_python") + + val resourceAssignmentRuntimeService = ResourceAssignmentRuntimeService("1234", bluePrintContext) + + capabilityResourceResolutionProcessor.raRuntimeService = resourceAssignmentRuntimeService + + val resourceDefinition = JacksonUtils + .readValueFromClassPathFile("mapping/capability/jython-resource-definitions.json", + ResourceDefinition::class.java)!! + val resourceDefinitions: MutableMap = mutableMapOf() + resourceDefinitions[resourceDefinition.name] = resourceDefinition + capabilityResourceResolutionProcessor.resourceDictionaries = resourceDefinitions + + val resourceAssignment = ResourceAssignment().apply { + name = "service-instance-id" + dictionaryName = "service-instance-id" + dictionarySource = "capability" + property = PropertyDefinition().apply { + type = "string" + } + } + + val processorName = capabilityResourceResolutionProcessor.apply(resourceAssignment) + assertNotNull(processorName, "couldn't get Jython script resource assignment processor name") + + } + +} + +open class MockCapabilityService { + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/logback-test.xml index a816a06c5..0c8d93bf0 100644 --- a/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/functions/resource-resolution/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/functions/restconf-executor/pom.xml b/ms/blueprintsprocessor/functions/restconf-executor/pom.xml index 1ee23d3d0..ef2f8bbb6 100644 --- a/ms/blueprintsprocessor/functions/restconf-executor/pom.xml +++ b/ms/blueprintsprocessor/functions/restconf-executor/pom.xml @@ -17,18 +17,18 @@ functions - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor 0.4.2-SNAPSHOT 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions restconf-executor Blueprints Processor Function - Restconf Executor Blueprints Processor Function - Restconf Executor - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions resource-resolution diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt deleted file mode 100644 index 7166ec279..000000000 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.restconf.executor - -import com.fasterxml.jackson.databind.node.ArrayNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.apps.blueprintsprocessor.rest.RestLibConstants -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.ComponentFunctionScriptingService -import org.onap.ccsdk.apps.controllerblueprints.core.getAsString -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component - -@Component("component-restconf-executor") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -open class ComponentRestconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) : - AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(ComponentRestconfExecutor::class.java) - - lateinit var scriptComponent: RestconfComponentFunction - - companion object { - const val SCRIPT_TYPE = "script-type" - const val SCRIPT_CLASS_REFERENCE = "script-class-reference" - const val INSTANCE_DEPENDENCIES = "instance-dependencies" - } - - override fun process(executionRequest: ExecutionServiceInput) { - - val scriptType = operationInputs.getAsString(SCRIPT_TYPE) - val scriptClassReference = operationInputs.getAsString(SCRIPT_CLASS_REFERENCE) - val instanceDependenciesNode = operationInputs.get(INSTANCE_DEPENDENCIES) as? ArrayNode - - val scriptDependencies: MutableList = arrayListOf() - scriptDependencies.add(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) - scriptDependencies.add(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) - - instanceDependenciesNode?.forEach { instanceName -> - scriptDependencies.add(instanceName.textValue()) - } - /** - * Populate the Script Instance based on the Type - */ - scriptComponent = componentFunctionScriptingService.scriptInstance(this, scriptType, - scriptClassReference, scriptDependencies) - - checkNotNull(scriptComponent) { "failed to get restconf script component" } - - scriptComponent.process(executionServiceInput) - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - scriptComponent.recover(runtimeException, executionRequest) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt deleted file mode 100644 index 1914616e8..000000000 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -@file:Suppress("unused") - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.restconf.executor - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService -import org.onap.ccsdk.apps.blueprintsprocessor.rest.RestLibConstants -import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService -import org.onap.ccsdk.apps.blueprintsprocessor.rest.service.BlueprintWebClientService -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractScriptComponentFunction - - -abstract class RestconfComponentFunction : AbstractScriptComponentFunction() { - - open fun bluePrintRestLibPropertyService(): BluePrintRestLibPropertyService = - functionDependencyInstanceAsType(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) - - open fun resourceResolutionService(): ResourceResolutionService = - functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) - - - fun restClientService(selector: String): BlueprintWebClientService { - return bluePrintRestLibPropertyService().blueprintWebClientService(selector) - } - - fun resolveFromDatabase(resolutionKey: String, artifactName: String): String { - return resourceResolutionService().resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey) - } - - fun generateMessage(artifactName: String): String { - return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) - } - - fun resolveAndGenerateMessage(artifactMapping: String, artifactTemplate: String): String { - return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, - artifactMapping, artifactTemplate) - } - - fun resolveAndGenerateMessage(artifactPrefix: String): String { - return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, - artifactPrefix, mapOf()) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt deleted file mode 100644 index 300f5be13..000000000 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.restconf.executor - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - - -@Configuration -@ComponentScan -@EnableConfigurationProperties -@ConditionalOnProperty(name = ["blueprintsprocessor.restconfEnabled"], havingValue = "true") -open class RestconfExecutorConfiguration \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt new file mode 100644 index 000000000..0ce0edca5 --- /dev/null +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutor.kt @@ -0,0 +1,73 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.restconf.executor + +import com.fasterxml.jackson.databind.node.ArrayNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.ComponentFunctionScriptingService +import org.onap.ccsdk.cds.controllerblueprints.core.getAsString +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component + +@Component("component-restconf-executor") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +open class ComponentRestconfExecutor(private var componentFunctionScriptingService: ComponentFunctionScriptingService) : + AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(ComponentRestconfExecutor::class.java) + + lateinit var scriptComponent: RestconfComponentFunction + + companion object { + const val SCRIPT_TYPE = "script-type" + const val SCRIPT_CLASS_REFERENCE = "script-class-reference" + const val INSTANCE_DEPENDENCIES = "instance-dependencies" + } + + override fun process(executionRequest: ExecutionServiceInput) { + + val scriptType = operationInputs.getAsString(SCRIPT_TYPE) + val scriptClassReference = operationInputs.getAsString(SCRIPT_CLASS_REFERENCE) + val instanceDependenciesNode = operationInputs.get(INSTANCE_DEPENDENCIES) as? ArrayNode + + val scriptDependencies: MutableList = arrayListOf() + scriptDependencies.add(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) + scriptDependencies.add(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) + + instanceDependenciesNode?.forEach { instanceName -> + scriptDependencies.add(instanceName.textValue()) + } + /** + * Populate the Script Instance based on the Type + */ + scriptComponent = componentFunctionScriptingService.scriptInstance(this, scriptType, + scriptClassReference, scriptDependencies) + + checkNotNull(scriptComponent) { "failed to get restconf script component" } + + scriptComponent.process(executionServiceInput) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + scriptComponent.recover(runtimeException, executionRequest) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.kt new file mode 100644 index 000000000..b95879274 --- /dev/null +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfComponentFunction.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. + */ +@file:Suppress("unused") + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.restconf.executor + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService +import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractScriptComponentFunction + + +abstract class RestconfComponentFunction : AbstractScriptComponentFunction() { + + open fun bluePrintRestLibPropertyService(): BluePrintRestLibPropertyService = + functionDependencyInstanceAsType(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) + + open fun resourceResolutionService(): ResourceResolutionService = + functionDependencyInstanceAsType(ResourceResolutionConstants.SERVICE_RESOURCE_RESOLUTION) + + + fun restClientService(selector: String): BlueprintWebClientService { + return bluePrintRestLibPropertyService().blueprintWebClientService(selector) + } + + fun resolveFromDatabase(resolutionKey: String, artifactName: String): String { + return resourceResolutionService().resolveFromDatabase(bluePrintRuntimeService, artifactName, resolutionKey) + } + + fun generateMessage(artifactName: String): String { + return bluePrintRuntimeService.resolveNodeTemplateArtifact(nodeTemplateName, artifactName) + } + + fun resolveAndGenerateMessage(artifactMapping: String, artifactTemplate: String): String { + return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, + artifactMapping, artifactTemplate) + } + + fun resolveAndGenerateMessage(artifactPrefix: String): String { + return resourceResolutionService().resolveResources(bluePrintRuntimeService, nodeTemplateName, + artifactPrefix, mapOf()) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt new file mode 100644 index 000000000..11e774315 --- /dev/null +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/RestconfExecutorConfiguration.kt @@ -0,0 +1,29 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.restconf.executor + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + + +@Configuration +@ComponentScan +@EnableConfigurationProperties +@ConditionalOnProperty(name = ["blueprintsprocessor.restconfEnabled"], havingValue = "true") +open class RestconfExecutorConfiguration \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/scripts/InternalSimpleRestconf.cba.kts b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/scripts/InternalSimpleRestconf.cba.kts index 588f7f108..88feddf49 100644 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/scripts/InternalSimpleRestconf.cba.kts +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/main/kotlin/scripts/InternalSimpleRestconf.cba.kts @@ -17,11 +17,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.functions.restconf.executor.RestconfComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils +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.functions.restconf.executor.RestconfComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils import org.slf4j.LoggerFactory open class EditConfigure : RestconfComponentFunction() { diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt deleted file mode 100644 index 5d903bc72..000000000 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.functions.restconf.executor - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ArrayNode -import com.fasterxml.jackson.databind.node.ObjectNode -import io.mockk.every -import io.mockk.mockk -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext -import org.onap.ccsdk.apps.controllerblueprints.core.service.DefaultBluePrintRuntimeService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -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.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@EnableAutoConfiguration -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@DirtiesContext -@TestPropertySource(properties = -["server.port=9111", - "blueprintsprocessor.restconfEnabled=true", - "blueprintsprocessor.restclient.odlPrimary.type=basic-auth", - "blueprintsprocessor.restclient.odlPrimary.url=http://127.0.0.1:9111", - "blueprintsprocessor.restclient.odlPrimary.userId=sampleuser", - "blueprintsprocessor.restclient.odlPrimary.token=sampletoken"], - locations = ["classpath:application-test.properties"]) -class ComponentRestconfExecutorTest { - - @Autowired - lateinit var componentRestconfExecutor: ComponentRestconfExecutor - - @Test - fun `test Restconf Component Instance`() { - assertNotNull(componentRestconfExecutor, "failed to get ComponentRestconfExecutor instance") - val executionServiceInput = ExecutionServiceInput().apply { - commonHeader = CommonHeader().apply { - requestId = "1234" - } - actionIdentifiers = ActionIdentifiers().apply { - actionName = "activate" - } - payload = JacksonUtils.jsonNode("{}") as ObjectNode - } - val bluePrintRuntime = mockk("1234") - componentRestconfExecutor.bluePrintRuntimeService = bluePrintRuntime - componentRestconfExecutor.stepName = "sample-step" - - val operationInputs = hashMapOf() - operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-restconf".asJsonPrimitive() - operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() - operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() - operationInputs[ComponentRestconfExecutor.SCRIPT_TYPE] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive() - operationInputs[ComponentRestconfExecutor.SCRIPT_CLASS_REFERENCE] = - "InternalSimpleRestconf_cba\$TestRestconfConfigure".asJsonPrimitive() - operationInputs[ComponentRestconfExecutor.INSTANCE_DEPENDENCIES] = JacksonUtils.jsonNode("[]") as ArrayNode - - val blueprintContext = mockk() - every { bluePrintRuntime.bluePrintContext() } returns blueprintContext - every { bluePrintRuntime.get("sample-step-step-inputs") } returns operationInputs.asJsonNode() - every { - bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs("activate-restconf", - "interfaceName", "operationName") - } returns operationInputs - - val operationOutputs = hashMapOf() - every { - bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs("activate-restconf", - "interfaceName", "operationName") - } returns operationOutputs - every { bluePrintRuntime.put("sample-step-step-outputs", any()) } returns Unit - - componentRestconfExecutor.apply(executionServiceInput) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt b/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt new file mode 100644 index 000000000..24eb453c9 --- /dev/null +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/restconf/executor/ComponentRestconfExecutorTest.kt @@ -0,0 +1,102 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.functions.restconf.executor + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import com.fasterxml.jackson.databind.node.ObjectNode +import io.mockk.every +import io.mockk.mockk +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.service.DefaultBluePrintRuntimeService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +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.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@DirtiesContext +@TestPropertySource(properties = +["server.port=9111", + "blueprintsprocessor.restconfEnabled=true", + "blueprintsprocessor.restclient.odlPrimary.type=basic-auth", + "blueprintsprocessor.restclient.odlPrimary.url=http://127.0.0.1:9111", + "blueprintsprocessor.restclient.odlPrimary.userId=sampleuser", + "blueprintsprocessor.restclient.odlPrimary.token=sampletoken"], + locations = ["classpath:application-test.properties"]) +class ComponentRestconfExecutorTest { + + @Autowired + lateinit var componentRestconfExecutor: ComponentRestconfExecutor + + @Test + fun `test Restconf Component Instance`() { + assertNotNull(componentRestconfExecutor, "failed to get ComponentRestconfExecutor instance") + val executionServiceInput = ExecutionServiceInput().apply { + commonHeader = CommonHeader().apply { + requestId = "1234" + } + actionIdentifiers = ActionIdentifiers().apply { + actionName = "activate" + } + payload = JacksonUtils.jsonNode("{}") as ObjectNode + } + val bluePrintRuntime = mockk("1234") + componentRestconfExecutor.bluePrintRuntimeService = bluePrintRuntime + componentRestconfExecutor.stepName = "sample-step" + + val operationInputs = hashMapOf() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE] = "activate-restconf".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_INTERFACE] = "interfaceName".asJsonPrimitive() + operationInputs[BluePrintConstants.PROPERTY_CURRENT_OPERATION] = "operationName".asJsonPrimitive() + operationInputs[ComponentRestconfExecutor.SCRIPT_TYPE] = BluePrintConstants.SCRIPT_INTERNAL.asJsonPrimitive() + operationInputs[ComponentRestconfExecutor.SCRIPT_CLASS_REFERENCE] = + "InternalSimpleRestconf_cba\$TestRestconfConfigure".asJsonPrimitive() + operationInputs[ComponentRestconfExecutor.INSTANCE_DEPENDENCIES] = JacksonUtils.jsonNode("[]") as ArrayNode + + val blueprintContext = mockk() + every { bluePrintRuntime.bluePrintContext() } returns blueprintContext + every { bluePrintRuntime.get("sample-step-step-inputs") } returns operationInputs.asJsonNode() + every { + bluePrintRuntime.resolveNodeTemplateInterfaceOperationInputs("activate-restconf", + "interfaceName", "operationName") + } returns operationInputs + + val operationOutputs = hashMapOf() + every { + bluePrintRuntime.resolveNodeTemplateInterfaceOperationOutputs("activate-restconf", + "interfaceName", "operationName") + } returns operationOutputs + every { bluePrintRuntime.put("sample-step-step-outputs", any()) } returns Unit + + componentRestconfExecutor.apply(executionServiceInput) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/functions/restconf-executor/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/functions/restconf-executor/src/test/resources/logback-test.xml index 56ea7bb50..daab7eaf8 100644 --- a/ms/blueprintsprocessor/functions/restconf-executor/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/functions/restconf-executor/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml index 045c871ff..faf5578c9 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/db-lib/pom.xml @@ -18,7 +18,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor commons 0.4.2-SNAPSHOT @@ -30,19 +30,19 @@ - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints db-resources - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-validation - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor processor-core diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt deleted file mode 100644 index 3e9ec0cef..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db - -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BluePrintDBLibConfiguration(private var bluePrintProperties: BluePrintProperties) { - - @Bean("primary-database-properties") - open fun getPrimaryProperties(): PrimaryDataSourceProperties { - return bluePrintProperties.propertyBeanType(DBLibConstants.PREFIX_DB_PRIMARY, - PrimaryDataSourceProperties::class.java) - } -} - -class DBLibConstants { - companion object { - const val PREFIX_DB_PRIMARY: String = "blueprintsprocessor.db.primary" - - //list of database - const val MARIA_DB: String = "maria-db" - const val PRIMARY_DB: String = "primary-db" - const val MYSQL_DB: String = "mysql-db" - const val ORACLE_DB: String = "oracle-db" - const val POSTGRES_DB: String = "postgres-db" - - //List of database drivers - const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver" - const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver" - const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver" - const val DRIVER_POSTGRES_DB = "org.postgresql.Driver" - - - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibData.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibData.kt deleted file mode 100644 index ab2c19a40..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibData.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db - - -open class DBDataSourceProperties { - lateinit var url: String - lateinit var username: String - lateinit var password: String - open lateinit var driverClassName: String - -} - -open class PrimaryDataSourceProperties: DBDataSourceProperties() { - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var hibernateDialect: String -} - -open class MariaDataSourceProperties: DBDataSourceProperties() { - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var type: String - lateinit var hibernateDialect: String - override var driverClassName = DBLibConstants.DRIVER_MARIA_DB -} - -open class MySqlDataSourceProperties: DBDataSourceProperties() { - lateinit var hibernateHbm2ddlAuto: String - lateinit var hibernateDDLAuto: String - lateinit var hibernateNamingStrategy: String - lateinit var type: String - lateinit var hibernateDialect: String - override var driverClassName = DBLibConstants.DRIVER_MYSQL_DB -} - diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt deleted file mode 100644 index aee74d3f4..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BluePrintDBLibGenericService.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db - -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate - -interface BluePrintDBLibGenericService { - - fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate - - fun query(sql: String, params: Map): List> - - fun update(sql: String, params: Map): Int -} - -abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) - : BluePrintDBLibGenericService { - - override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { - return namedParameterJdbcTemplate - } - - override fun query(sql: String, params: Map): List> { - return namedParameterJdbcTemplate.queryForList(sql, params) - } - - override fun update(sql: String, params: Map): Int { - return namedParameterJdbcTemplate.update(sql, params) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt deleted file mode 100755 index e94bcff52..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 Bell Canada. - * 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.apps.blueprintsprocessor.db - -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModelContent -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.repository.BlueprintProcessorModelRepository -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException -import org.onap.ccsdk.apps.controllerblueprints.core.common.ApplicationConstants -import org.onap.ccsdk.apps.controllerblueprints.core.data.ErrorCode -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintValidatorService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils -import org.onap.ccsdk.apps.controllerblueprints.db.resources.BlueprintCatalogServiceImpl -import org.slf4j.LoggerFactory -import org.springframework.dao.DataIntegrityViolationException -import org.springframework.stereotype.Service -import java.io.File -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Similar/Duplicate implementation in [org.onap.ccsdk.apps.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl] - */ -@Service -class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: BluePrintValidatorService, - private val blueprintConfig: BluePrintCoreConfiguration, - private val blueprintModelRepository: BlueprintProcessorModelRepository) - : BlueprintCatalogServiceImpl(bluePrintRuntimeValidatorService) { - - private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString()) - - init { - - log.info("BlueprintProcessorCatalogServiceImpl initialized") - } - - override fun delete(name: String, version: String) = blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(name, version) - - - override fun get(name: String, version: String, extract: Boolean): Path? { - var path = "${blueprintConfig.archivePath}/$name/$version.zip" - - blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also { - it.blueprintModelContent.run { - val file = File(path) - file.parentFile.mkdirs() - file.createNewFile() - file.writeBytes(this!!.content!!).let { - if (extract) { - path = "${blueprintConfig.archivePath}/$name/$version" - BluePrintArchiveUtils.deCompress(file, path) - } - return Paths.get(path) - } - } - } - return null - } - - override fun save(metadata: MutableMap, archiveFile: File) { - val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] - val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] - - blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let { - log.info("Overwriting blueprint model :$artifactName::$artifactVersion") - blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion) - } - - val blueprintModel = BlueprintProcessorModel() - blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] - blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL - blueprintModel.artifactName = artifactName - blueprintModel.artifactVersion = artifactVersion - blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] - blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] - blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion" - - val blueprintModelContent = BlueprintProcessorModelContent() - blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] - blueprintModelContent.contentType = "CBA_ZIP" - blueprintModelContent.name = "$artifactName:$artifactVersion" - blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" - blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) - blueprintModelContent.blueprintModel = blueprintModel - - blueprintModel.blueprintModelContent = blueprintModelContent - - 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) - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt deleted file mode 100644 index f93c241d4..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright © 2019 Bell Canada Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.db.* -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service -class BluePrintDBLibPropertySevice(private var bluePrintProperties: BluePrintProperties) { - - fun JdbcTemplate(jsonNode: JsonNode): BluePrintDBLibGenericService { - val dBConnetionProperties = dBDataSourceProperties(jsonNode) - return blueprintDBDataSourceService(dBConnetionProperties) - } - - fun JdbcTemplate(selector: String): BluePrintDBLibGenericService { - val prefix = "blueprintsprocessor.database.$selector" - val dBConnetionProperties = dBDataSourceProperties(prefix) - return blueprintDBDataSourceService(dBConnetionProperties) - } - - private fun dBDataSourceProperties(jsonNode: JsonNode): DBDataSourceProperties { - val type = jsonNode.get("type").textValue() - return when (type) { - DBLibConstants.MYSQL_DB -> { - JacksonUtils.readValue(jsonNode, MySqlDataSourceProperties::class.java)!! - } - DBLibConstants.MARIA_DB -> { - JacksonUtils.readValue(jsonNode, MariaDataSourceProperties::class.java)!! - } - else -> { - throw BluePrintProcessorException("Rest adaptor($type) is not supported") - } - } - } - - private fun dBDataSourceProperties(prefix: String): DBDataSourceProperties { - val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - DBLibConstants.MARIA_DB -> { - mariaDBConnectionProperties(prefix) - } - DBLibConstants.MYSQL_DB -> { - mySqlDBConnectionProperties(prefix) - } - DBLibConstants.ORACLE_DB -> { - TODO("not implemented") - } - DBLibConstants.POSTGRES_DB -> { - TODO("not implemented") - } - DBLibConstants.PRIMARY_DB -> { - primaryDBConnectionProperties(prefix) - } - else -> { - throw BluePrintProcessorException("Rest adaptor($type) is not supported") - } - } - } - - private fun blueprintDBDataSourceService(dBConnetionProperties: DBDataSourceProperties): BluePrintDBLibGenericService { - when (dBConnetionProperties) { - is MariaDataSourceProperties -> { - return MariaDatabaseConfiguration(dBConnetionProperties) - } - is MySqlDataSourceProperties -> { - return MySqlDatabaseConfiguration(dBConnetionProperties) - } - else -> { - throw BluePrintProcessorException("couldn't get rest service for") - } - } - } - - private fun mySqlDBConnectionProperties(prefix: String): MySqlDataSourceProperties { - return bluePrintProperties.propertyBeanType(prefix, MySqlDataSourceProperties::class.java) - } - - private fun mariaDBConnectionProperties(prefix: String): MariaDataSourceProperties { - return bluePrintProperties.propertyBeanType(prefix, MariaDataSourceProperties::class.java) - } - - private fun primaryDBConnectionProperties(prefix: String): PrimaryDataSourceProperties { - return bluePrintProperties.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/apps/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt deleted file mode 100644 index c67fb3397..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright © 2019 Bell Canada Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibGenericService -import org.onap.ccsdk.apps.blueprintsprocessor.db.MariaDataSourceProperties -import org.slf4j.LoggerFactory -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 javax.sql.DataSource - -class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDataSourceProperties) : BluePrintDBLibGenericService { - - override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { - return mariaNamedParameterJdbcTemplate(mariaDataSource()) - } - - override fun query(sql: String, params: Map): List> { - return mariaNamedParameterJdbcTemplate(mariaDataSource()).queryForList(sql, params) - } - - override fun update(sql: String, params: Map): Int { - return mariaNamedParameterJdbcTemplate(mariaDataSource()).update(sql, params) - } - - val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! - - fun mariaDataSource(): DataSource { - val dataSource = DriverManagerDataSource() - dataSource.setDriverClassName(mariaDataSourceProperties.driverClassName) - dataSource.url = mariaDataSourceProperties.url - dataSource.username = mariaDataSourceProperties.username - dataSource.password = mariaDataSourceProperties.password - return dataSource - } - - 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/apps/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt deleted file mode 100644 index 2a0dec73e..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2019 Bell Canada Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibGenericService -import org.onap.ccsdk.apps.blueprintsprocessor.db.MySqlDataSourceProperties -import org.slf4j.LoggerFactory -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate -import org.springframework.jdbc.datasource.DriverManagerDataSource -import javax.sql.DataSource - -class MySqlDatabaseConfiguration(private val mySqlDataSourceProperties: MySqlDataSourceProperties) : BluePrintDBLibGenericService { - override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { - return mySqlNamedParameterJdbcTemplate(mySqlDataSource()) - } - - override fun query(sql: String, params: Map): List> { - return mySqlNamedParameterJdbcTemplate(mySqlDataSource()).queryForList(sql, params) - } - - override fun update(sql: String, params: Map): Int { - return mySqlNamedParameterJdbcTemplate(mySqlDataSource()).update(sql, params) - } - - val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! - - fun mySqlDataSource(): DataSource { - val dataSource = DriverManagerDataSource() - dataSource.setDriverClassName(mySqlDataSourceProperties.driverClassName) - dataSource.url = mySqlDataSourceProperties.url - dataSource.username = mySqlDataSourceProperties.username - dataSource.password = mySqlDataSourceProperties.password - return dataSource - } - - fun mySqlNamedParameterJdbcTemplate(mySqlDataSource: DataSource): NamedParameterJdbcTemplate { - return NamedParameterJdbcTemplate(mySqlDataSource) - } - - -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt deleted file mode 100644 index 5a9265348..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import org.onap.ccsdk.apps.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 diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt deleted file mode 100644 index 4039b053b..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import org.onap.ccsdk.apps.blueprintsprocessor.db.PrimaryDataSourceProperties -import org.slf4j.LoggerFactory -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.Primary -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 javax.sql.DataSource - -@Configuration -@EnableJpaRepositories( - basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor.*"], - entityManagerFactoryRef = "primaryEntityManager", - transactionManagerRef = "primaryTransactionManager" -) -open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties: PrimaryDataSourceProperties) { - val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! - - @Primary - @Bean("primaryEntityManager") - open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean { - val em = LocalContainerEntityManagerFactoryBean() - em.dataSource = primaryDataSource() - em.setPackagesToScan("org.onap.ccsdk.apps.blueprintsprocessor.*") - em.jpaVendorAdapter = HibernateJpaVendorAdapter() - val properties = HashMap() - properties["hibernate.hbm2ddl.auto"] = primaryDataSourceProperties.hibernateHbm2ddlAuto - properties["hibernate.dialect"] = primaryDataSourceProperties.hibernateDialect - em.jpaPropertyMap = properties - return em - } - - @Primary - @Bean("primaryDataSource") - open fun primaryDataSource(): DataSource { - val dataSource = DriverManagerDataSource() - dataSource.setDriverClassName(primaryDataSourceProperties.driverClassName) - dataSource.url = primaryDataSourceProperties.url - dataSource.username = primaryDataSourceProperties.username - dataSource.password = primaryDataSourceProperties.password - return dataSource - } - - @Primary - @Bean("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/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt deleted file mode 100755 index 0935d038c..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain - -import com.fasterxml.jackson.annotation.JsonFormat -import io.swagger.annotations.ApiModelProperty -import javax.persistence.Entity -import javax.persistence.EntityListeners -import javax.persistence.Table -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.CascadeType -import javax.persistence.Column -import javax.persistence.FetchType -import javax.persistence.Id -import javax.persistence.Lob -import javax.persistence.OneToOne -import javax.persistence.Temporal -import javax.persistence.TemporalType - -@EntityListeners(AuditingEntityListener::class) -@Entity -@Table(name = "BLUEPRINT_RUNTIME") -@Proxy(lazy = false) -class BlueprintProcessorModel : Serializable { - - @Id - @Column(name = "blueprint_runtime_id") - var id: String? = null - - @Column(name = "artifact_type") - var artifactType: String? = null - - @Column(name = "artifact_version", nullable = false) - @ApiModelProperty(required = true) - var artifactVersion: String? = null - - @Lob - @Column(name = "artifact_description") - var artifactDescription: String? = null - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @LastModifiedDate - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "creation_date") - var createdDate = Date() - - @Column(name = "artifact_name", nullable = false) - @ApiModelProperty(required = true) - var artifactName: String? = null - - @Column(name = "updated_by", nullable = false) - @ApiModelProperty(required = true) - var updatedBy: String? = null - - @Lob - @Column(name = "tags", nullable = false) - @ApiModelProperty(required = true) - var tags: String? = null - - @OneToOne(mappedBy = "blueprintModel", fetch = FetchType.EAGER, orphanRemoval = true, cascade = [CascadeType.ALL]) - var blueprintModelContent: BlueprintProcessorModelContent? = null - - companion object { - private const val serialVersionUID = 1L - } -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt deleted file mode 100644 index 58bf8a338..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain - -import com.fasterxml.jackson.annotation.JsonFormat -import io.swagger.annotations.ApiModelProperty -import java.io.Serializable -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 -import org.springframework.data.annotation.LastModifiedDate -import org.springframework.data.jpa.domain.support.AuditingEntityListener - -@EntityListeners(AuditingEntityListener::class) -@Entity -@Table(name = "BLUEPRINT_CONTENT_RUNTIME") -class BlueprintProcessorModelContent : Serializable { - - @Id - @Column(name = "blueprint_content_runtime_id") - var id: String? = null - - @Column(name = "name", nullable = false) - @ApiModelProperty(required = true) - var name: String? = null - - @Column(name = "content_type", nullable = false) - @ApiModelProperty(required = true) - var contentType: String? = null - - @OneToOne - @JoinColumn(name = "blueprint_runtime_id") - var blueprintModel: BlueprintProcessorModel? = null - - @Lob - @Column(name = "description") - var description: String? = null - - @Lob - @Column(name = "content", nullable = false) - @ApiModelProperty(required = true) - var content: ByteArray? = null - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - @LastModifiedDate - @Temporal(TemporalType.TIMESTAMP) - @Column(name = "updated_date") - var creationDate = Date() - - override fun toString(): String { - return "[" + "id = " + id + - ", name = " + name + - ", contentType = " + contentType + - "]" - } - - override fun equals(o: Any?): Boolean { - - if (o === this) { - return true - } - if (o !is BlueprintProcessorModelContent) { - return false - } - val blueprintModelContent = o as BlueprintProcessorModelContent? - return (id == blueprintModelContent!!.id && name == blueprintModelContent.name - && contentType == blueprintModelContent.contentType) - } - - override fun hashCode(): Int { - return Objects.hash(id, name, contentType) - } - - companion object { - private const val serialVersionUID = 1L - } - -} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt deleted file mode 100644 index e614544e9..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.db.primary.repository - -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModelContent -import org.onap.ccsdk.apps.controllerblueprints.db.resources.repository.ModelContentRepository - -interface BlueprintProcessorModelContentRepository : ModelContentRepository \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt deleted file mode 100644 index 25f3dac9a..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.db.primary.repository - -import org.onap.ccsdk.apps.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel -import org.onap.ccsdk.apps.controllerblueprints.db.resources.repository.ModelRepository - -interface BlueprintProcessorModelRepository : ModelRepository diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt new file mode 100644 index 000000000..19e482aab --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibConfiguration.kt @@ -0,0 +1,56 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintDBLibConfiguration(private var bluePrintProperties: BluePrintProperties) { + + @Bean("primary-database-properties") + open fun getPrimaryProperties(): PrimaryDataSourceProperties { + return bluePrintProperties.propertyBeanType(DBLibConstants.PREFIX_DB_PRIMARY, + PrimaryDataSourceProperties::class.java) + } +} + +class DBLibConstants { + companion object { + const val PREFIX_DB_PRIMARY: String = "blueprintsprocessor.db.primary" + + //list of database + const val MARIA_DB: String = "maria-db" + const val PRIMARY_DB: String = "primary-db" + const val MYSQL_DB: String = "mysql-db" + const val ORACLE_DB: String = "oracle-db" + const val POSTGRES_DB: String = "postgres-db" + + //List of database drivers + const val DRIVER_MARIA_DB = "org.mariadb.jdbc.Driver" + const val DRIVER_MYSQL_DB = "com.mysql.jdbc.Driver" + const val DRIVER_ORACLE_DB = "oracle.jdbc.driver.OracleDriver" + const val DRIVER_POSTGRES_DB = "org.postgresql.Driver" + + + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt new file mode 100644 index 000000000..b71287d6e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibData.kt @@ -0,0 +1,52 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + + +open class DBDataSourceProperties { + lateinit var url: String + lateinit var username: String + lateinit var password: String + open lateinit var driverClassName: String + +} + +open class PrimaryDataSourceProperties: DBDataSourceProperties() { + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var hibernateDialect: String +} + +open class MariaDataSourceProperties: DBDataSourceProperties() { + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var type: String + lateinit var hibernateDialect: String + override var driverClassName = DBLibConstants.DRIVER_MARIA_DB +} + +open class MySqlDataSourceProperties: DBDataSourceProperties() { + lateinit var hibernateHbm2ddlAuto: String + lateinit var hibernateDDLAuto: String + lateinit var hibernateNamingStrategy: String + lateinit var type: String + lateinit var hibernateDialect: String + override var driverClassName = DBLibConstants.DRIVER_MYSQL_DB +} + diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt new file mode 100644 index 000000000..0f6314685 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BluePrintDBLibGenericService.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate + +interface BluePrintDBLibGenericService { + + fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate + + fun query(sql: String, params: Map): List> + + fun update(sql: String, params: Map): Int +} + +abstract class AbstractDBLibGenericService(private val namedParameterJdbcTemplate: NamedParameterJdbcTemplate) + : BluePrintDBLibGenericService { + + override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { + return namedParameterJdbcTemplate + } + + override fun query(sql: String, params: Map): List> { + return namedParameterJdbcTemplate.queryForList(sql, params) + } + + override fun update(sql: String, params: Map): Int { + return namedParameterJdbcTemplate.update(sql, params) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt new file mode 100755 index 000000000..0a625007f --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImpl.kt @@ -0,0 +1,114 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintProcessorModelContent +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository.BlueprintProcessorModelRepository +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.common.ApplicationConstants +import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintValidatorService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils +import org.onap.ccsdk.cds.controllerblueprints.db.resources.BlueprintCatalogServiceImpl +import org.slf4j.LoggerFactory +import org.springframework.dao.DataIntegrityViolationException +import org.springframework.stereotype.Service +import java.io.File +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths + +/** + * Similar/Duplicate implementation in [org.onap.ccsdk.cds.controllerblueprints.service.load.ControllerBlueprintCatalogServiceImpl] + */ +@Service +class BlueprintProcessorCatalogServiceImpl(bluePrintRuntimeValidatorService: BluePrintValidatorService, + private val blueprintConfig: BluePrintCoreConfiguration, + private val blueprintModelRepository: BlueprintProcessorModelRepository) + : BlueprintCatalogServiceImpl(bluePrintRuntimeValidatorService) { + + private val log = LoggerFactory.getLogger(BlueprintProcessorCatalogServiceImpl::class.toString()) + + init { + + log.info("BlueprintProcessorCatalogServiceImpl initialized") + } + + override fun delete(name: String, version: String) = blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(name, version) + + + override fun get(name: String, version: String, extract: Boolean): Path? { + var path = "${blueprintConfig.archivePath}/$name/$version.zip" + + blueprintModelRepository.findByArtifactNameAndArtifactVersion(name, version)?.also { + it.blueprintModelContent.run { + val file = File(path) + file.parentFile.mkdirs() + file.createNewFile() + file.writeBytes(this!!.content!!).let { + if (extract) { + path = "${blueprintConfig.archivePath}/$name/$version" + BluePrintArchiveUtils.deCompress(file, path) + } + return Paths.get(path) + } + } + } + return null + } + + override fun save(metadata: MutableMap, archiveFile: File) { + val artifactName = metadata[BluePrintConstants.METADATA_TEMPLATE_NAME] + val artifactVersion = metadata[BluePrintConstants.METADATA_TEMPLATE_VERSION] + + blueprintModelRepository.findByArtifactNameAndArtifactVersion(artifactName!!, artifactVersion!!)?.let { + log.info("Overwriting blueprint model :$artifactName::$artifactVersion") + blueprintModelRepository.deleteByArtifactNameAndArtifactVersion(artifactName, artifactVersion) + } + + val blueprintModel = BlueprintProcessorModel() + blueprintModel.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModel.artifactType = ApplicationConstants.ASDC_ARTIFACT_TYPE_SDNC_MODEL + blueprintModel.artifactName = artifactName + blueprintModel.artifactVersion = artifactVersion + blueprintModel.updatedBy = metadata[BluePrintConstants.METADATA_TEMPLATE_AUTHOR] + blueprintModel.tags = metadata[BluePrintConstants.METADATA_TEMPLATE_TAGS] + blueprintModel.artifactDescription = "Controller Blueprint for $artifactName:$artifactVersion" + + val blueprintModelContent = BlueprintProcessorModelContent() + blueprintModelContent.id = metadata[BluePrintConstants.PROPERTY_BLUEPRINT_PROCESS_ID] + blueprintModelContent.contentType = "CBA_ZIP" + blueprintModelContent.name = "$artifactName:$artifactVersion" + blueprintModelContent.description = "$artifactName:$artifactVersion CBA Zip Content" + blueprintModelContent.content = Files.readAllBytes(archiveFile.toPath()) + blueprintModelContent.blueprintModel = blueprintModel + + blueprintModel.blueprintModelContent = blueprintModelContent + + 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) + } + } +} \ 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/BluePrintDBLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt new file mode 100644 index 000000000..cf2ca550e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/BluePrintDBLibPropertyService.kt @@ -0,0 +1,105 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.db.* +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 bluePrintProperties: BluePrintProperties) { + + fun JdbcTemplate(jsonNode: JsonNode): BluePrintDBLibGenericService { + val dBConnetionProperties = dBDataSourceProperties(jsonNode) + return blueprintDBDataSourceService(dBConnetionProperties) + } + + fun JdbcTemplate(selector: String): BluePrintDBLibGenericService { + val prefix = "blueprintsprocessor.database.$selector" + val dBConnetionProperties = dBDataSourceProperties(prefix) + return blueprintDBDataSourceService(dBConnetionProperties) + } + + private fun dBDataSourceProperties(jsonNode: JsonNode): DBDataSourceProperties { + val type = jsonNode.get("type").textValue() + return when (type) { + DBLibConstants.MYSQL_DB -> { + JacksonUtils.readValue(jsonNode, MySqlDataSourceProperties::class.java)!! + } + DBLibConstants.MARIA_DB -> { + JacksonUtils.readValue(jsonNode, MariaDataSourceProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Rest adaptor($type) is not supported") + } + } + } + + private fun dBDataSourceProperties(prefix: String): DBDataSourceProperties { + val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) + return when (type) { + DBLibConstants.MARIA_DB -> { + mariaDBConnectionProperties(prefix) + } + DBLibConstants.MYSQL_DB -> { + mySqlDBConnectionProperties(prefix) + } + DBLibConstants.ORACLE_DB -> { + TODO("not implemented") + } + DBLibConstants.POSTGRES_DB -> { + TODO("not implemented") + } + DBLibConstants.PRIMARY_DB -> { + primaryDBConnectionProperties(prefix) + } + else -> { + throw BluePrintProcessorException("Rest adaptor($type) is not supported") + } + } + } + + private fun blueprintDBDataSourceService(dBConnetionProperties: DBDataSourceProperties): BluePrintDBLibGenericService { + when (dBConnetionProperties) { + is MariaDataSourceProperties -> { + return MariaDatabaseConfiguration(dBConnetionProperties) + } + is MySqlDataSourceProperties -> { + return MySqlDatabaseConfiguration(dBConnetionProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get rest service for") + } + } + } + + private fun mySqlDBConnectionProperties(prefix: String): MySqlDataSourceProperties { + return bluePrintProperties.propertyBeanType(prefix, MySqlDataSourceProperties::class.java) + } + + private fun mariaDBConnectionProperties(prefix: String): MariaDataSourceProperties { + return bluePrintProperties.propertyBeanType(prefix, MariaDataSourceProperties::class.java) + } + + private fun primaryDBConnectionProperties(prefix: String): PrimaryDataSourceProperties { + return bluePrintProperties.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 new file mode 100644 index 000000000..5015388b9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MariaDatabaseConfiguration.kt @@ -0,0 +1,59 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.MariaDataSourceProperties +import org.slf4j.LoggerFactory +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate +import org.springframework.jdbc.datasource.DriverManagerDataSource +import 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 javax.sql.DataSource + +class MariaDatabaseConfiguration(private val mariaDataSourceProperties: MariaDataSourceProperties) : BluePrintDBLibGenericService { + + override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { + return mariaNamedParameterJdbcTemplate(mariaDataSource()) + } + + override fun query(sql: String, params: Map): List> { + return mariaNamedParameterJdbcTemplate(mariaDataSource()).queryForList(sql, params) + } + + override fun update(sql: String, params: Map): Int { + return mariaNamedParameterJdbcTemplate(mariaDataSource()).update(sql, params) + } + + val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! + + fun mariaDataSource(): DataSource { + val dataSource = DriverManagerDataSource() + dataSource.setDriverClassName(mariaDataSourceProperties.driverClassName) + dataSource.url = mariaDataSourceProperties.url + dataSource.username = mariaDataSourceProperties.username + dataSource.password = mariaDataSourceProperties.password + return dataSource + } + + 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 new file mode 100644 index 000000000..3091674f0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/MySqlDatabaseConfiguration.kt @@ -0,0 +1,55 @@ +/* + * Copyright © 2019 Bell Canada Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +import org.onap.ccsdk.cds.blueprintsprocessor.db.BluePrintDBLibGenericService +import org.onap.ccsdk.cds.blueprintsprocessor.db.MySqlDataSourceProperties +import org.slf4j.LoggerFactory +import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate +import org.springframework.jdbc.datasource.DriverManagerDataSource +import javax.sql.DataSource + +class MySqlDatabaseConfiguration(private val mySqlDataSourceProperties: MySqlDataSourceProperties) : BluePrintDBLibGenericService { + override fun namedParameterJdbcTemplate(): NamedParameterJdbcTemplate { + return mySqlNamedParameterJdbcTemplate(mySqlDataSource()) + } + + override fun query(sql: String, params: Map): List> { + return mySqlNamedParameterJdbcTemplate(mySqlDataSource()).queryForList(sql, params) + } + + override fun update(sql: String, params: Map): Int { + return mySqlNamedParameterJdbcTemplate(mySqlDataSource()).update(sql, params) + } + + val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! + + fun mySqlDataSource(): DataSource { + val dataSource = DriverManagerDataSource() + dataSource.setDriverClassName(mySqlDataSourceProperties.driverClassName) + dataSource.url = mySqlDataSourceProperties.url + dataSource.username = mySqlDataSourceProperties.username + dataSource.password = mySqlDataSourceProperties.password + return dataSource + } + + 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/PrimaryDBLibGenericService.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt new file mode 100644 index 000000000..896929fbb --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDBLibGenericService.kt @@ -0,0 +1,27 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +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 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 new file mode 100644 index 000000000..4ea407ada --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfiguration.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary + +import org.onap.ccsdk.cds.blueprintsprocessor.db.PrimaryDataSourceProperties +import org.slf4j.LoggerFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Primary +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 javax.sql.DataSource + +@Configuration +@EnableJpaRepositories( + basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor.*"], + entityManagerFactoryRef = "primaryEntityManager", + transactionManagerRef = "primaryTransactionManager" +) +open class PrimaryDatabaseConfiguration(private val primaryDataSourceProperties: PrimaryDataSourceProperties) { + val log = LoggerFactory.getLogger(PrimaryDatabaseConfiguration::class.java)!! + + @Primary + @Bean("primaryEntityManager") + open fun primaryEntityManager(): LocalContainerEntityManagerFactoryBean { + val em = LocalContainerEntityManagerFactoryBean() + em.dataSource = primaryDataSource() + em.setPackagesToScan("org.onap.ccsdk.cds.blueprintsprocessor.*") + em.jpaVendorAdapter = HibernateJpaVendorAdapter() + val properties = HashMap() + properties["hibernate.hbm2ddl.auto"] = primaryDataSourceProperties.hibernateHbm2ddlAuto + properties["hibernate.dialect"] = primaryDataSourceProperties.hibernateDialect + em.jpaPropertyMap = properties + return em + } + + @Primary + @Bean("primaryDataSource") + open fun primaryDataSource(): DataSource { + val dataSource = DriverManagerDataSource() + dataSource.setDriverClassName(primaryDataSourceProperties.driverClassName) + dataSource.url = primaryDataSourceProperties.url + dataSource.username = primaryDataSourceProperties.username + dataSource.password = primaryDataSourceProperties.password + return dataSource + } + + @Primary + @Bean("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/BlueprintProcessorModel.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt new file mode 100755 index 000000000..c565262db --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModel.kt @@ -0,0 +1,84 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain + +import com.fasterxml.jackson.annotation.JsonFormat +import io.swagger.annotations.ApiModelProperty +import javax.persistence.Entity +import javax.persistence.EntityListeners +import javax.persistence.Table +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.CascadeType +import javax.persistence.Column +import javax.persistence.FetchType +import javax.persistence.Id +import javax.persistence.Lob +import javax.persistence.OneToOne +import javax.persistence.Temporal +import javax.persistence.TemporalType + +@EntityListeners(AuditingEntityListener::class) +@Entity +@Table(name = "BLUEPRINT_RUNTIME") +@Proxy(lazy = false) +class BlueprintProcessorModel : Serializable { + + @Id + @Column(name = "blueprint_runtime_id") + var id: String? = null + + @Column(name = "artifact_type") + var artifactType: String? = null + + @Column(name = "artifact_version", nullable = false) + @ApiModelProperty(required = true) + var artifactVersion: String? = null + + @Lob + @Column(name = "artifact_description") + var artifactDescription: String? = null + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + @LastModifiedDate + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "creation_date") + var createdDate = Date() + + @Column(name = "artifact_name", nullable = false) + @ApiModelProperty(required = true) + var artifactName: String? = null + + @Column(name = "updated_by", nullable = false) + @ApiModelProperty(required = true) + var updatedBy: String? = null + + @Lob + @Column(name = "tags", nullable = false) + @ApiModelProperty(required = true) + var tags: String? = null + + @OneToOne(mappedBy = "blueprintModel", fetch = FetchType.EAGER, orphanRemoval = true, cascade = [CascadeType.ALL]) + var blueprintModelContent: BlueprintProcessorModelContent? = null + + companion object { + 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/BlueprintProcessorModelContent.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt new file mode 100644 index 000000000..dc02d2fd0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/domain/BlueprintProcessorModelContent.kt @@ -0,0 +1,101 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain + +import com.fasterxml.jackson.annotation.JsonFormat +import io.swagger.annotations.ApiModelProperty +import java.io.Serializable +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 +import org.springframework.data.annotation.LastModifiedDate +import org.springframework.data.jpa.domain.support.AuditingEntityListener + +@EntityListeners(AuditingEntityListener::class) +@Entity +@Table(name = "BLUEPRINT_CONTENT_RUNTIME") +class BlueprintProcessorModelContent : Serializable { + + @Id + @Column(name = "blueprint_content_runtime_id") + var id: String? = null + + @Column(name = "name", nullable = false) + @ApiModelProperty(required = true) + var name: String? = null + + @Column(name = "content_type", nullable = false) + @ApiModelProperty(required = true) + var contentType: String? = null + + @OneToOne + @JoinColumn(name = "blueprint_runtime_id") + var blueprintModel: BlueprintProcessorModel? = null + + @Lob + @Column(name = "description") + var description: String? = null + + @Lob + @Column(name = "content", nullable = false) + @ApiModelProperty(required = true) + var content: ByteArray? = null + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + @LastModifiedDate + @Temporal(TemporalType.TIMESTAMP) + @Column(name = "updated_date") + var creationDate = Date() + + override fun toString(): String { + return "[" + "id = " + id + + ", name = " + name + + ", contentType = " + contentType + + "]" + } + + override fun equals(o: Any?): Boolean { + + if (o === this) { + return true + } + if (o !is BlueprintProcessorModelContent) { + return false + } + val blueprintModelContent = o as BlueprintProcessorModelContent? + return (id == blueprintModelContent!!.id && name == blueprintModelContent.name + && contentType == blueprintModelContent.contentType) + } + + override fun hashCode(): Int { + return Objects.hash(id, name, contentType) + } + + companion object { + private const val serialVersionUID = 1L + } + +} diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt new file mode 100644 index 000000000..c914af8f3 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelContentRepository.kt @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository + +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintProcessorModelContent +import org.onap.ccsdk.cds.controllerblueprints.db.resources.repository.ModelContentRepository + +interface BlueprintProcessorModelContentRepository : ModelContentRepository \ 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/BlueprintProcessorModelRepository.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt new file mode 100644 index 000000000..4f22bf07d --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/repository/BlueprintProcessorModelRepository.kt @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.db.primary.repository + +import org.onap.ccsdk.cds.blueprintsprocessor.db.primary.domain.BlueprintProcessorModel +import org.onap.ccsdk.cds.controllerblueprints.db.resources.repository.ModelRepository + +interface BlueprintProcessorModelRepository : ModelRepository diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt deleted file mode 100644 index 4c953163a..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.db - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.context.annotation.ComponentScan -import org.springframework.test.context.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import java.io.File -import java.nio.file.Paths -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@EnableAutoConfiguration -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BlueprintProcessorCatalogServiceImplTest { - - @Autowired - lateinit var blueprintCatalog: BluePrintCatalogService - - @Test - fun `test catalog service`() { - val file = Paths.get("./src/test/resources/test-cba.zip").toFile() - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - - blueprintCatalog.saveToDatabase(file) - - blueprintCatalog.getFromDatabase("baseconfiguration", "1.0.0") - - blueprintCatalog.deleteFromDatabase("baseconfiguration", "1.0.0") - - File("./src/test/resources/baseconfiguration").deleteRecursively() - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt deleted file mode 100644 index 3f737e314..000000000 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.db.primary - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.db.BluePrintDBLibConfiguration -import org.onap.ccsdk.apps.controllerblueprints.core.config.BluePrintLoadConfiguration -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 -import javax.sql.DataSource -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BlueprintPropertyConfiguration::class, BluePrintProperties::class, - BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@EnableAutoConfiguration -class PrimaryDatabaseConfigurationTest { - - @Autowired - lateinit var primaryDataSource: DataSource - - @Test - 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/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 new file mode 100644 index 000000000..a9a2ae73e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/BlueprintProcessorCatalogServiceImplTest.kt @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.db + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import java.io.File +import java.nio.file.Paths +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BlueprintProcessorCatalogServiceImplTest { + + @Autowired + lateinit var blueprintCatalog: BluePrintCatalogService + + @Test + fun `test catalog service`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + blueprintCatalog.saveToDatabase(file) + + blueprintCatalog.getFromDatabase("baseconfiguration", "1.0.0") + + blueprintCatalog.deleteFromDatabase("baseconfiguration", "1.0.0") + + File("./src/test/resources/baseconfiguration").deleteRecursively() + } +} \ 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 new file mode 100644 index 000000000..b4a21780b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/db/primary/PrimaryDatabaseConfigurationTest.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.blueprintsprocessor.db.primary + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +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.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 +import javax.sql.DataSource +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [BlueprintPropertyConfiguration::class, BluePrintProperties::class, + BluePrintDBLibConfiguration::class, BluePrintLoadConfiguration::class]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@EnableAutoConfiguration +class PrimaryDatabaseConfigurationTest { + + @Autowired + lateinit var primaryDataSource: DataSource + + @Test + 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/logback-test.xml b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/logback-test.xml index f9ec9fe57..355cd3ace 100644 --- a/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/modules/commons/db-lib/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/pom.xml b/ms/blueprintsprocessor/modules/commons/dmaap-lib/pom.xml index 30f83d389..5f302993a 100644 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/pom.xml @@ -21,7 +21,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor commons 0.4.2-SNAPSHOT @@ -69,7 +69,7 @@ test - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor processor-core diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt deleted file mode 100644 index dd884092d..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -import com.att.nsa.mr.client.MRBatchingPublisher -import com.att.nsa.mr.client.MRClientFactory -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher - -/** - * Representation of DMAAP client service for AAF auth type. - */ -class AafAuthDmaapClientService(private val clientProps: - AafAuthDmaapClientProperties) - : BluePrintDmaapClientService { - - /** - * The constructed DMAAP client. - */ - var clients: MutableList = mutableListOf() - - - /** - * Returns the DMAAP client after constructing it properly with the data - * that is required for AAF auth connection. - */ - override fun getDmaapClient(): MutableList { - if (!clients.isEmpty()) { - return clients - } - val topics = mutableListOf() - topics.addAll(clientProps.topic.split(",")) - - for (t in topics) { - val client = MRClientFactory.createBatchingPublisher( - clientProps.host, t, clientProps.username, - clientProps.password, 1, 1, false, - 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/apps/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt deleted file mode 100644 index 21d7128e4..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -import com.att.nsa.mr.client.MRBatchingPublisher -import com.att.nsa.mr.client.MRPublisher -import org.slf4j.LoggerFactory -import java.io.IOException -import java.util.concurrent.TimeUnit - - -/** - * Abstraction of DMAAP client services that could form DMAAP client from the - * properties provided. This abstraction also provides a mechanism to send - * messages with the given partition in a session and closing the same. - */ -interface BluePrintDmaapClientService { - - /** - * Static variable for logging. - */ - companion object { - var log = LoggerFactory.getLogger( - BluePrintDmaapClientService::class.java)!! - } - - /** - * Returns the properly constructed DMAAP client with the type. - */ - fun getDmaapClient(): MutableList - - /** - * Sends messages to the sessions created by the information provided from - * application.properties and event.properties file - */ - fun sendMessage(msgs: Collection): Boolean { - var success = true - val clients = getDmaapClient() - val dmaapMsgs = mutableListOf() - for (m in msgs) { - dmaapMsgs.add(MRPublisher.message("1", m)) - } - log.info("Sending messages to the DMAAP Server") - for (client in clients) { - try { - client.send(dmaapMsgs) - } catch (e: IOException) { - success = false - log.error(e.message, e) - } - } - return success - } - - /** - * Sends message to the sessions created by the information provided from - * application.properties and event.properties file - */ - fun sendMessage(msg: String): Boolean { - val msgs = mutableListOf() - msgs.add(msg) - return sendMessage(msgs) - } - - /** - * Closes the opened session that was used for sending messages. - */ - fun close(timeout: Long): MutableList>? { - log.debug("Closing the DMAAP producer clients") - var msgs: MutableList> = - mutableListOf() - val clients = getDmaapClient() - for (client in clients) { - try { - var ms = client.close(timeout, TimeUnit.SECONDS) - msgs.add(ms) - } catch (e: IOException) { - log.warn("Unable to cleanly close the connection from the " + - "client $client", e) - } - } - return msgs - } -} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt deleted file mode 100644 index ca1a07ba3..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -/** - * Representation of DMAAP lib configuration to load the required property - * files into the application context. - */ -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BluePrintDmaapLibConfiguration - -/** - * Util constants required for DMAAP library to use. - */ -class DmaapLibConstants { - companion object { - const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" + - "-dmaap-lib-property-service" - const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH" - const val TYPE_HTTP_AAF_AUTH = "HTTPAAF" - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt deleted file mode 100644 index 7abbefbca..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY -import org.onap.ccsdk.apps.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_AAF_AUTH -import org.onap.ccsdk.apps.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_NO_AUTH -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.PropertySource -import org.springframework.context.annotation.PropertySources -import org.springframework.core.env.ConfigurableEnvironment -import org.springframework.core.env.Environment -import org.springframework.core.io.support.ResourcePropertySource -import org.springframework.stereotype.Service -import java.util.Properties - -/** - * Representation of DMAAP lib property service to load the properties - * according to the connection type to the DMAAP server and returning back - * the appropriate DMAAP client to send messages DMAAP client. - */ -@Service(SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY) -@Configuration -@PropertySources(PropertySource("classpath:event.properties")) -open class BluePrintDmaapLibPropertyService(private var bluePrintProperties: - BluePrintProperties) { - - /** - * Static variable for logging. - */ - companion object { - var log = LoggerFactory.getLogger( - BluePrintDmaapLibPropertyService::class.java)!! - } - - /** - * Environment entity to derive it from the system to load a specific - * property file. - */ - @Autowired - lateinit var env: Environment - - /** - * Returns the DMAAP client by providing the input properties as a JSON - * node. - */ - fun blueprintDmaapClientService(jsonNode: JsonNode): - BluePrintDmaapClientService { - val dmaapProps = dmaapClientProperties(jsonNode) - return blueprintDmaapClientService(dmaapProps) - } - - /** - * Returns the DMAAP client by providing the input properties as a - * selector string. - */ - fun blueprintDmaapClientService(selector: String): - BluePrintDmaapClientService { - val prefix = "blueprintsprocessor.dmaapclient.$selector" - val dmaapProps = dmaapClientProperties(prefix) - return blueprintDmaapClientService(dmaapProps) - } - - /** - * Returns the DMAAP client properties from the type of connection it - * requires. - */ - fun dmaapClientProperties(prefix: String): DmaapClientProperties { - val type = bluePrintProperties.propertyBeanType( - "$prefix.type", String::class.java) - val clientProps : DmaapClientProperties - - when (type) { - TYPE_HTTP_NO_AUTH -> { - clientProps = bluePrintProperties.propertyBeanType( - prefix, HttpNoAuthDmaapClientProperties::class.java) - clientProps.props = parseEventProps() - } - - TYPE_HTTP_AAF_AUTH -> { - clientProps = bluePrintProperties.propertyBeanType( - prefix, AafAuthDmaapClientProperties::class.java) - clientProps.props = parseEventProps() - } - - else -> { - throw BluePrintProcessorException("DMAAP adaptor($type) is " + - "not supported") - } - } - return clientProps - } - - /** - * Returns the DMAAP client properties from the type of connection it - * requires. - */ - fun dmaapClientProperties(jsonNode: JsonNode): DmaapClientProperties { - val type = jsonNode.get("type").textValue() - val clientProps : DmaapClientProperties - - when (type) { - TYPE_HTTP_NO_AUTH -> { - clientProps = JacksonUtils.readValue(jsonNode, - HttpNoAuthDmaapClientProperties::class.java)!! - clientProps.props = parseEventProps() - } - - TYPE_HTTP_AAF_AUTH -> { - clientProps = JacksonUtils.readValue(jsonNode, - AafAuthDmaapClientProperties::class.java)!! - clientProps.props = parseEventProps() - } - - else -> { - throw BluePrintProcessorException("DMAAP adaptor($type) is " + - "not supported") - } - } - return clientProps - } - - /** - * Returns DMAAP client service according to the type of client properties. - */ - private fun blueprintDmaapClientService(clientProps: DmaapClientProperties): - BluePrintDmaapClientService { - when (clientProps) { - is HttpNoAuthDmaapClientProperties -> { - return HttpNoAuthDmaapClientService(clientProps) - } - - is AafAuthDmaapClientProperties -> { - return AafAuthDmaapClientService(clientProps) - } - - else -> { - throw BluePrintProcessorException("Unable to get the DMAAP " + - "client") - } - } - } - - /** - * Parses the event.properties file which contains the default values for - * the connection required. - */ - private fun parseEventProps(): Properties { - val prodProps = Properties() - val proProps = (env as ConfigurableEnvironment).propertySources.get( - "class path resource [event.properties]") - - if (proProps != null) { - val entries = (proProps as ResourcePropertySource).source.entries - for (e in entries) { - prodProps.put(e.key, e.value) - } - } else { - log.error("Unable to load the event.properties file") - } - return prodProps - } -} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/DmaapClientProperties.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/DmaapClientProperties.kt deleted file mode 100644 index 97df2723b..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/DmaapClientProperties.kt +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -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 - lateinit var topic: String -} - -/** - * Representation of data required for HTTP no auth DMAAP client. - */ -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/apps/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt deleted file mode 100644 index ad023b962..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.dmaap - -import com.att.nsa.mr.client.MRBatchingPublisher -import com.att.nsa.mr.client.MRClientFactory.createSimplePublisher -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 { - - /** - * The constructed DMAAP client. - */ - var clients: MutableList = mutableListOf() - - - /** - * Returns the DMAAP client after constructing it properly with the data - * that is required for HTTP no auth connection. - */ - override fun getDmaapClient(): MutableList { - if (!clients.isEmpty()) { - return clients - } - val topics = mutableListOf() - topics.addAll(clientProps.topic.split(",")) - - for (t in topics) { - val client = createSimplePublisher(clientProps.host, t) - val batchPublisher = client as MRSimplerBatchPublisher - batchPublisher.setProtocolFlag(clientProps.type) - 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/AafAuthDmaapClientService.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt new file mode 100644 index 000000000..2dbea8fc9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/AafAuthDmaapClientService.kt @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.att.nsa.mr.client.MRBatchingPublisher +import com.att.nsa.mr.client.MRClientFactory +import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher + +/** + * Representation of DMAAP client service for AAF auth type. + */ +class AafAuthDmaapClientService(private val clientProps: + AafAuthDmaapClientProperties) + : BluePrintDmaapClientService { + + /** + * The constructed DMAAP client. + */ + var clients: MutableList = mutableListOf() + + + /** + * Returns the DMAAP client after constructing it properly with the data + * that is required for AAF auth connection. + */ + override fun getDmaapClient(): MutableList { + if (!clients.isEmpty()) { + return clients + } + val topics = mutableListOf() + topics.addAll(clientProps.topic.split(",")) + + for (t in topics) { + val client = MRClientFactory.createBatchingPublisher( + clientProps.host, t, clientProps.username, + clientProps.password, 1, 1, false, + 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 new file mode 100644 index 000000000..a4cb5a3e6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapClientService.kt @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.att.nsa.mr.client.MRBatchingPublisher +import com.att.nsa.mr.client.MRPublisher +import org.slf4j.LoggerFactory +import java.io.IOException +import java.util.concurrent.TimeUnit + + +/** + * Abstraction of DMAAP client services that could form DMAAP client from the + * properties provided. This abstraction also provides a mechanism to send + * messages with the given partition in a session and closing the same. + */ +interface BluePrintDmaapClientService { + + /** + * Static variable for logging. + */ + companion object { + var log = LoggerFactory.getLogger( + BluePrintDmaapClientService::class.java)!! + } + + /** + * Returns the properly constructed DMAAP client with the type. + */ + fun getDmaapClient(): MutableList + + /** + * Sends messages to the sessions created by the information provided from + * application.properties and event.properties file + */ + fun sendMessage(msgs: Collection): Boolean { + var success = true + val clients = getDmaapClient() + val dmaapMsgs = mutableListOf() + for (m in msgs) { + dmaapMsgs.add(MRPublisher.message("1", m)) + } + log.info("Sending messages to the DMAAP Server") + for (client in clients) { + try { + client.send(dmaapMsgs) + } catch (e: IOException) { + success = false + log.error(e.message, e) + } + } + return success + } + + /** + * Sends message to the sessions created by the information provided from + * application.properties and event.properties file + */ + fun sendMessage(msg: String): Boolean { + val msgs = mutableListOf() + msgs.add(msg) + return sendMessage(msgs) + } + + /** + * Closes the opened session that was used for sending messages. + */ + fun close(timeout: Long): MutableList>? { + log.debug("Closing the DMAAP producer clients") + var msgs: MutableList> = + mutableListOf() + val clients = getDmaapClient() + for (client in clients) { + try { + var ms = client.close(timeout, TimeUnit.SECONDS) + msgs.add(ms) + } catch (e: IOException) { + log.warn("Unable to cleanly close the connection from the " + + "client $client", e) + } + } + return msgs + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt new file mode 100644 index 000000000..51cd3bf0a --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibConfiguration.kt @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +/** + * Representation of DMAAP lib configuration to load the required property + * files into the application context. + */ +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintDmaapLibConfiguration + +/** + * Util constants required for DMAAP library to use. + */ +class DmaapLibConstants { + companion object { + const val SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY = "blueprint" + + "-dmaap-lib-property-service" + const val TYPE_HTTP_NO_AUTH = "HTTPNOAUTH" + const val TYPE_HTTP_AAF_AUTH = "HTTPAAF" + } +} \ 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 new file mode 100644 index 000000000..8604d8880 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/BluePrintDmaapLibPropertyService.kt @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_AAF_AUTH +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.DmaapLibConstants.Companion.TYPE_HTTP_NO_AUTH +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.PropertySource +import org.springframework.context.annotation.PropertySources +import org.springframework.core.env.ConfigurableEnvironment +import org.springframework.core.env.Environment +import org.springframework.core.io.support.ResourcePropertySource +import org.springframework.stereotype.Service +import java.util.Properties + +/** + * Representation of DMAAP lib property service to load the properties + * according to the connection type to the DMAAP server and returning back + * the appropriate DMAAP client to send messages DMAAP client. + */ +@Service(SERVICE_BLUEPRINT_DMAAP_LIB_PROPERTY) +@Configuration +@PropertySources(PropertySource("classpath:event.properties")) +open class BluePrintDmaapLibPropertyService(private var bluePrintProperties: + BluePrintProperties) { + + /** + * Static variable for logging. + */ + companion object { + var log = LoggerFactory.getLogger( + BluePrintDmaapLibPropertyService::class.java)!! + } + + /** + * Environment entity to derive it from the system to load a specific + * property file. + */ + @Autowired + lateinit var env: Environment + + /** + * Returns the DMAAP client by providing the input properties as a JSON + * node. + */ + fun blueprintDmaapClientService(jsonNode: JsonNode): + BluePrintDmaapClientService { + val dmaapProps = dmaapClientProperties(jsonNode) + return blueprintDmaapClientService(dmaapProps) + } + + /** + * Returns the DMAAP client by providing the input properties as a + * selector string. + */ + fun blueprintDmaapClientService(selector: String): + BluePrintDmaapClientService { + val prefix = "blueprintsprocessor.dmaapclient.$selector" + val dmaapProps = dmaapClientProperties(prefix) + return blueprintDmaapClientService(dmaapProps) + } + + /** + * Returns the DMAAP client properties from the type of connection it + * requires. + */ + fun dmaapClientProperties(prefix: String): DmaapClientProperties { + val type = bluePrintProperties.propertyBeanType( + "$prefix.type", String::class.java) + val clientProps : DmaapClientProperties + + when (type) { + TYPE_HTTP_NO_AUTH -> { + clientProps = bluePrintProperties.propertyBeanType( + prefix, HttpNoAuthDmaapClientProperties::class.java) + clientProps.props = parseEventProps() + } + + TYPE_HTTP_AAF_AUTH -> { + clientProps = bluePrintProperties.propertyBeanType( + prefix, AafAuthDmaapClientProperties::class.java) + clientProps.props = parseEventProps() + } + + else -> { + throw BluePrintProcessorException("DMAAP adaptor($type) is " + + "not supported") + } + } + return clientProps + } + + /** + * Returns the DMAAP client properties from the type of connection it + * requires. + */ + fun dmaapClientProperties(jsonNode: JsonNode): DmaapClientProperties { + val type = jsonNode.get("type").textValue() + val clientProps : DmaapClientProperties + + when (type) { + TYPE_HTTP_NO_AUTH -> { + clientProps = JacksonUtils.readValue(jsonNode, + HttpNoAuthDmaapClientProperties::class.java)!! + clientProps.props = parseEventProps() + } + + TYPE_HTTP_AAF_AUTH -> { + clientProps = JacksonUtils.readValue(jsonNode, + AafAuthDmaapClientProperties::class.java)!! + clientProps.props = parseEventProps() + } + + else -> { + throw BluePrintProcessorException("DMAAP adaptor($type) is " + + "not supported") + } + } + return clientProps + } + + /** + * Returns DMAAP client service according to the type of client properties. + */ + private fun blueprintDmaapClientService(clientProps: DmaapClientProperties): + BluePrintDmaapClientService { + when (clientProps) { + is HttpNoAuthDmaapClientProperties -> { + return HttpNoAuthDmaapClientService(clientProps) + } + + is AafAuthDmaapClientProperties -> { + return AafAuthDmaapClientService(clientProps) + } + + else -> { + throw BluePrintProcessorException("Unable to get the DMAAP " + + "client") + } + } + } + + /** + * Parses the event.properties file which contains the default values for + * the connection required. + */ + private fun parseEventProps(): Properties { + val prodProps = Properties() + val proProps = (env as ConfigurableEnvironment).propertySources.get( + "class path resource [event.properties]") + + if (proProps != null) { + val entries = (proProps as ResourcePropertySource).source.entries + for (e in entries) { + prodProps.put(e.key, e.value) + } + } else { + log.error("Unable to load the event.properties file") + } + return prodProps + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt new file mode 100644 index 000000000..9d942943e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/DmaapClientProperties.kt @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import 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 + lateinit var topic: String +} + +/** + * Representation of data required for HTTP no auth DMAAP client. + */ +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 new file mode 100644 index 000000000..8bf50a944 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/dmaap/HttpNoAuthDmaapClientService.kt @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.dmaap + +import com.att.nsa.mr.client.MRBatchingPublisher +import com.att.nsa.mr.client.MRClientFactory.createSimplePublisher +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 { + + /** + * The constructed DMAAP client. + */ + var clients: MutableList = mutableListOf() + + + /** + * Returns the DMAAP client after constructing it properly with the data + * that is required for HTTP no auth connection. + */ + override fun getDmaapClient(): MutableList { + if (!clients.isEmpty()) { + return clients + } + val topics = mutableListOf() + topics.addAll(clientProps.topic.split(",")) + + for (t in topics) { + val client = createSimplePublisher(clientProps.host, t) + val batchPublisher = client as MRSimplerBatchPublisher + batchPublisher.setProtocolFlag(clientProps.type) + 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/test/kotlin/org/ccsdk/apps/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/apps/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt deleted file mode 100644 index 9b3aae5e6..000000000 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/apps/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt +++ /dev/null @@ -1,215 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - CDS - * ================================================================================ - * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.ccsdk.apps.blueprintprocessor.dmaap - -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.dmaap.BluePrintDmaapLibConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.dmaap.BluePrintDmaapLibPropertyService -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.test.context.SpringBootTest -import org.springframework.http.HttpStatus -import org.springframework.http.ResponseEntity -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.PathVariable -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController -import kotlin.test.assertEquals -import kotlin.test.assertNotNull - -/** - * Unit test cases for DMaap publisher code. - */ -@RunWith(SpringRunner::class) -@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class]) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@ContextConfiguration(classes = [BluePrintDmaapLibConfiguration::class, TestController::class, - BlueprintPropertyConfiguration::class, BluePrintProperties::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 - - /** - * Tests the event properties being set properly and sent as request. - */ - @Test - fun testEventProperties() { - val strList = mutableListOf() - val dmaapClient = dmaapService.blueprintDmaapClientService("aai") - - strList.add("{\n" + - " \"a\" : \"hello\"\n" + - "}") - dmaapClient.sendMessage(strList) - val msgs = dmaapClient.close(2) - assertEquals(msgs!!.size, 1) - val topic1 = msgs.get(0) - assertEquals(topic1!!.size, 0) - } - - /** - * Tests the event properties being set properly and sent as request with - * single message. - */ - @Test - fun testEventPropertiesWithSingleMsg() { - val dmaapClient = dmaapService.blueprintDmaapClientService("aai") - val str : String = "{\n" + - " \"a\" : \"hello\"\n" + - "}" - dmaapClient.sendMessage(str) - val msgs = dmaapClient.close(2) - assertEquals(msgs!!.size, 1) - val topic1 = msgs.get(0) - assertEquals(topic1!!.size, 0) - } - - /** - * Tests the event properties with multiple topics. - */ - @Test - fun testMultiTopicProperties() { - val strList = mutableListOf() - val dmaapClient = dmaapService.blueprintDmaapClientService("multi") - - strList.add("{\n" + - " \"a\" : \"hello\"\n" + - "}") - dmaapClient.sendMessage(strList) - val msgs = dmaapClient.close(2) - assertEquals(msgs!!.size, 2) - val topic1 = msgs.get(0) - assertEquals(topic1!!.size, 0) - val topic2 = msgs.get(1) - assertEquals(topic2!!.size, 0) - } - - - /** - * Tests the event properties with multiple topics with JSON node as input. - */ - @Test - fun testMultiTopicPropertiesWithJsonInput() { - val jsonString = "{\n" + - " \"topic\" : \"cds_json1,cds_json2\",\n" + - " \"type\" : \"HTTPNOAUTH\",\n" + - " \"host\" : \"127.0.0.1:9111\"\n" + - "}" - val mapper = ObjectMapper() - val node = mapper.readTree(jsonString) - val strList = mutableListOf() - val dmaapClient = dmaapService.blueprintDmaapClientService(node) - - strList.add("{\n" + - " \"a\" : \"hello\"\n" + - "}") - dmaapClient.sendMessage(strList) - val msgs = dmaapClient.close(2) - assertEquals(msgs!!.size, 2) - val topic1 = msgs.get(0) - assertEquals(topic1!!.size, 0) - val topic2 = msgs.get(1) - assertEquals(topic2!!.size, 0) - } - - - /** - * Tests the event properties with multiple messages. - */ - @Test - fun testMultiMsgsProperties() { - val strList = mutableListOf() - val dmaapClient = dmaapService.blueprintDmaapClientService("aai") - - strList.add("{\n" + - " \"a\" : \"hello\"\n" + - "}") - strList.add("{\n" + - " \"a\" : \"second\"\n" + - "}") - dmaapClient.sendMessage(strList) - val msgs = dmaapClient.close(2) - assertEquals(msgs!!.size, 1) - val topic1 = msgs.get(0) - assertEquals(topic1!!.size, 0) - } - - /** - * Tests the DMAAP client properties generated with the complete prefix. - */ - @Test - fun testDmaapClientProperties() { - val properties = dmaapService.dmaapClientProperties( - "blueprintsprocessor.dmaapclient.aai") - assertNotNull(properties, "failed to create property bean") - assertNotNull(properties.host, "failed to get url property" + - " in property bean") - } - - /** - * Tests the blueprint DMAAP client service with only selector prefix. - */ - @Test - fun testBlueprintDmaapClientService() { - val blueprintDmaapClientService = - dmaapService.blueprintDmaapClientService("aai") - assertNotNull(blueprintDmaapClientService, - "failed to create blueprintDmaapClientService") - } - -} - -/** - * Rest controller for testing the client request that is sent. - */ -@RestController -@RequestMapping(path = ["/events"]) -open class TestController { - - /** - * Accepts request for a topic and sends a message as response. - */ - @PostMapping(path = ["/{topic}"]) - fun postTopic(@PathVariable(value = "topic") topic : String): - ResponseEntity { - var a = "{\n" + - " \"message\" : \"The message is published into $topic " + - "topic\"\n" + - "}" - return ResponseEntity(a, HttpStatus.OK) - } -} 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 new file mode 100644 index 000000000..65d877518 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/kotlin/org/ccsdk/cds/blueprintprocessor/dmaap/TestDmaapEventPublisher.kt @@ -0,0 +1,215 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - CDS + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.ccsdk.apps.blueprintprocessor.dmaap + +import com.fasterxml.jackson.databind.ObjectMapper +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BluePrintDmaapLibConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.dmaap.BluePrintDmaapLibPropertyService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpStatus +import org.springframework.http.ResponseEntity +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.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController +import kotlin.test.assertEquals +import kotlin.test.assertNotNull + +/** + * Unit test cases for DMaap publisher code. + */ +@RunWith(SpringRunner::class) +@EnableAutoConfiguration(exclude = [DataSourceAutoConfiguration::class]) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ContextConfiguration(classes = [BluePrintDmaapLibConfiguration::class, TestController::class, + BlueprintPropertyConfiguration::class, BluePrintProperties::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 + + /** + * Tests the event properties being set properly and sent as request. + */ + @Test + fun testEventProperties() { + val strList = mutableListOf() + val dmaapClient = dmaapService.blueprintDmaapClientService("aai") + + strList.add("{\n" + + " \"a\" : \"hello\"\n" + + "}") + dmaapClient.sendMessage(strList) + val msgs = dmaapClient.close(2) + assertEquals(msgs!!.size, 1) + val topic1 = msgs.get(0) + assertEquals(topic1!!.size, 0) + } + + /** + * Tests the event properties being set properly and sent as request with + * single message. + */ + @Test + fun testEventPropertiesWithSingleMsg() { + val dmaapClient = dmaapService.blueprintDmaapClientService("aai") + val str : String = "{\n" + + " \"a\" : \"hello\"\n" + + "}" + dmaapClient.sendMessage(str) + val msgs = dmaapClient.close(2) + assertEquals(msgs!!.size, 1) + val topic1 = msgs.get(0) + assertEquals(topic1!!.size, 0) + } + + /** + * Tests the event properties with multiple topics. + */ + @Test + fun testMultiTopicProperties() { + val strList = mutableListOf() + val dmaapClient = dmaapService.blueprintDmaapClientService("multi") + + strList.add("{\n" + + " \"a\" : \"hello\"\n" + + "}") + dmaapClient.sendMessage(strList) + val msgs = dmaapClient.close(2) + assertEquals(msgs!!.size, 2) + val topic1 = msgs.get(0) + assertEquals(topic1!!.size, 0) + val topic2 = msgs.get(1) + assertEquals(topic2!!.size, 0) + } + + + /** + * Tests the event properties with multiple topics with JSON node as input. + */ + @Test + fun testMultiTopicPropertiesWithJsonInput() { + val jsonString = "{\n" + + " \"topic\" : \"cds_json1,cds_json2\",\n" + + " \"type\" : \"HTTPNOAUTH\",\n" + + " \"host\" : \"127.0.0.1:9111\"\n" + + "}" + val mapper = ObjectMapper() + val node = mapper.readTree(jsonString) + val strList = mutableListOf() + val dmaapClient = dmaapService.blueprintDmaapClientService(node) + + strList.add("{\n" + + " \"a\" : \"hello\"\n" + + "}") + dmaapClient.sendMessage(strList) + val msgs = dmaapClient.close(2) + assertEquals(msgs!!.size, 2) + val topic1 = msgs.get(0) + assertEquals(topic1!!.size, 0) + val topic2 = msgs.get(1) + assertEquals(topic2!!.size, 0) + } + + + /** + * Tests the event properties with multiple messages. + */ + @Test + fun testMultiMsgsProperties() { + val strList = mutableListOf() + val dmaapClient = dmaapService.blueprintDmaapClientService("aai") + + strList.add("{\n" + + " \"a\" : \"hello\"\n" + + "}") + strList.add("{\n" + + " \"a\" : \"second\"\n" + + "}") + dmaapClient.sendMessage(strList) + val msgs = dmaapClient.close(2) + assertEquals(msgs!!.size, 1) + val topic1 = msgs.get(0) + assertEquals(topic1!!.size, 0) + } + + /** + * Tests the DMAAP client properties generated with the complete prefix. + */ + @Test + fun testDmaapClientProperties() { + val properties = dmaapService.dmaapClientProperties( + "blueprintsprocessor.dmaapclient.aai") + assertNotNull(properties, "failed to create property bean") + assertNotNull(properties.host, "failed to get url property" + + " in property bean") + } + + /** + * Tests the blueprint DMAAP client service with only selector prefix. + */ + @Test + fun testBlueprintDmaapClientService() { + val blueprintDmaapClientService = + dmaapService.blueprintDmaapClientService("aai") + assertNotNull(blueprintDmaapClientService, + "failed to create blueprintDmaapClientService") + } + +} + +/** + * Rest controller for testing the client request that is sent. + */ +@RestController +@RequestMapping(path = ["/events"]) +open class TestController { + + /** + * Accepts request for a topic and sends a message as response. + */ + @PostMapping(path = ["/{topic}"]) + fun postTopic(@PathVariable(value = "topic") topic : String): + ResponseEntity { + var a = "{\n" + + " \"message\" : \"The message is published into $topic " + + "topic\"\n" + + "}" + return ResponseEntity(a, HttpStatus.OK) + } +} diff --git a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/resources/logback-test.xml index 0f76057ad..ebb41b854 100644 --- a/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/modules/commons/dmaap-lib/src/test/resources/logback-test.xml @@ -31,7 +31,7 @@ - + diff --git a/ms/blueprintsprocessor/modules/commons/pom.xml b/ms/blueprintsprocessor/modules/commons/pom.xml index 205fd94c5..ebd905248 100755 --- a/ms/blueprintsprocessor/modules/commons/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/pom.xml @@ -20,7 +20,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor modules 0.4.2-SNAPSHOT @@ -38,7 +38,7 @@ - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints resource-dict diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml b/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml index 32e4b3d4a..93a9b793a 100644 --- a/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/processor-core/pom.xml @@ -19,7 +19,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor commons 0.4.2-SNAPSHOT diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintCoreConfiguration.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintCoreConfiguration.kt deleted file mode 100644 index 07e494a1a..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintCoreConfiguration.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.beans.factory.annotation.Value -import org.springframework.boot.context.properties.bind.Binder -import org.springframework.boot.context.properties.source.ConfigurationPropertySources -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.core.env.Environment - - -@Configuration -open class BluePrintCoreConfiguration { - - @Value("\${blueprintsprocessor.blueprintDeployPath}") - lateinit var deployPath: String - - @Value("\${blueprintsprocessor.blueprintArchivePath}") - lateinit var archivePath: String - -} - -@Configuration -open class BlueprintPropertyConfiguration { - @Autowired - lateinit var environment: Environment - - @Bean - open fun bluePrintPropertyBinder(): Binder { - val configurationPropertySource = ConfigurationPropertySources.get(environment) - return Binder(configurationPropertySource) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintProperties.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintProperties.kt deleted file mode 100644 index 10b8ceb5e..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintProperties.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core - -import org.springframework.boot.context.properties.bind.Bindable -import org.springframework.boot.context.properties.bind.Binder -import org.springframework.stereotype.Service - -@Service -open class BluePrintProperties(var bluePrintPropertyBinder: Binder) { - - fun propertyBeanType(prefix: String, type: Class): T { - return bluePrintPropertyBinder.bind(prefix, Bindable.of(type)).get() - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt deleted file mode 100644 index 41bbd1dfd..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core.api.data - -import com.fasterxml.jackson.annotation.JsonFormat -import com.fasterxml.jackson.databind.node.ObjectNode -import io.swagger.annotations.ApiModelProperty -import java.util.* - -/** - * BlueprintProcessorData - * @author Brinda Santh - * DATE : 8/15/2018 - */ - -open class ExecutionServiceInput { - @get:ApiModelProperty(required = true) - lateinit var commonHeader: CommonHeader - @get:ApiModelProperty(required = true) - lateinit var actionIdentifiers: ActionIdentifiers - @get:ApiModelProperty(required = true) - lateinit var payload: ObjectNode -} - -open class ExecutionServiceOutput { - @get:ApiModelProperty(required = true) - lateinit var commonHeader: CommonHeader - @get:ApiModelProperty(required = true) - lateinit var actionIdentifiers: ActionIdentifiers - @get:ApiModelProperty(required = true) - var status: Status = Status() - @get:ApiModelProperty(required = true) - lateinit var payload: ObjectNode -} - -const val ACTION_MODE_ASYNC = "async" -const val ACTION_MODE_SYNC = "sync" - -open class ActionIdentifiers { - @get:ApiModelProperty(required = false) - lateinit var blueprintName: String - @get:ApiModelProperty(required = false) - lateinit var blueprintVersion: String - @get:ApiModelProperty(required = true) - lateinit var actionName: String - @get:ApiModelProperty(required = true, allowableValues = "sync, async") - lateinit var mode: String -} - -open class CommonHeader { - @get:ApiModelProperty(required = true, 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 = true) - lateinit var originatorId: String - @get:ApiModelProperty(required = true) - lateinit var requestId: String - @get:ApiModelProperty(required = true) - lateinit var subRequestId: String - @get:ApiModelProperty(required = false) - var flags: Flags? = null -} - -open class Flags { - var isForce: Boolean = false - @get:ApiModelProperty(value = "3600") - var ttl: Int = 3600 -} - -open class Status { - @get:ApiModelProperty(required = true) - var code: Int = 200 - @get:ApiModelProperty(required = true) - var eventType: String = "EVENT-ACTION-RESPONSE" - @get:ApiModelProperty(required = true, 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) - var errorMessage: String? = null - @get:ApiModelProperty(required = true) - var message: String = "success" -} - -open class BluePrintManagementInput { - @get:ApiModelProperty(required = true) - lateinit var commonHeader: CommonHeader - @get:ApiModelProperty(required = false) - lateinit var blueprintName: String - @get:ApiModelProperty(required = false) - lateinit var blueprintVersion: String - @get:ApiModelProperty(required = true) - lateinit var fileChunk: FileChunk -} - -open class FileChunk { - @get:ApiModelProperty(required = true) - lateinit var chunk: ByteArray -} - -open class BluePrintManagementOutput { - @get:ApiModelProperty(required = true) - lateinit var commonHeader: CommonHeader - @get:ApiModelProperty(required = true) - var status: Status = Status() -} - - - diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/factory/ComponentNodeFactory.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/factory/ComponentNodeFactory.kt deleted file mode 100644 index 9c6e50752..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/factory/ComponentNodeFactory.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core.factory - -import com.att.eelf.configuration.EELFManager -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.springframework.context.ApplicationContext -import org.springframework.context.ApplicationContextAware - -/** - * ComponentNode - * - * @author Brinda Santh - */ -interface ComponentNode { - - @Throws(BluePrintProcessorException::class) - fun validate(context: MutableMap, componentContext: MutableMap) - - @Throws(BluePrintProcessorException::class) - fun process(context: MutableMap, componentContext: MutableMap) - - @Throws(BluePrintProcessorException::class) - fun errorHandle(context: MutableMap, componentContext: MutableMap) - - @Throws(BluePrintProcessorException::class) - fun reTrigger(context: MutableMap, componentContext: MutableMap) -} - -/** - * ComponentNodeFactory - * - * @author Brinda Santh - */ -open class ComponentNodeFactory : ApplicationContextAware { - private val log = EELFManager.getInstance().getLogger(ComponentNodeFactory::class.java) - - var componentNodes: MutableMap = hashMapOf() - - fun getInstance(instanceName: String): ComponentNode? { - log.trace("looking for Component Nodes : {}", instanceName) - return componentNodes.get(instanceName) - } - - fun injectInstance(instanceName: String, componentNode: ComponentNode) { - this.componentNodes[instanceName] = componentNode - } - - override fun setApplicationContext(context: ApplicationContext) { - 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/apps/blueprintsprocessor/core/utils/PayloadUtils.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/utils/PayloadUtils.kt deleted file mode 100644 index 31dca33b8..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/utils/PayloadUtils.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core.utils - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService - - -class PayloadUtils { - - companion object { - - 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) - } - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.kt new file mode 100644 index 000000000..03b847e51 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintCoreConfiguration.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.blueprintsprocessor.core + +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.context.properties.bind.Binder +import org.springframework.boot.context.properties.source.ConfigurationPropertySources +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.core.env.Environment + + +@Configuration +open class BluePrintCoreConfiguration { + + @Value("\${blueprintsprocessor.blueprintDeployPath}") + lateinit var deployPath: String + + @Value("\${blueprintsprocessor.blueprintArchivePath}") + lateinit var archivePath: String + +} + +@Configuration +open class BlueprintPropertyConfiguration { + @Autowired + lateinit var environment: Environment + + @Bean + open fun bluePrintPropertyBinder(): Binder { + val configurationPropertySource = ConfigurationPropertySources.get(environment) + return Binder(configurationPropertySource) + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintProperties.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintProperties.kt new file mode 100644 index 000000000..e2a4808a6 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintProperties.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.blueprintsprocessor.core + +import org.springframework.boot.context.properties.bind.Bindable +import org.springframework.boot.context.properties.bind.Binder +import org.springframework.stereotype.Service + +@Service +open class BluePrintProperties(var bluePrintPropertyBinder: Binder) { + + fun propertyBeanType(prefix: String, type: Class): T { + return bluePrintPropertyBinder.bind(prefix, Bindable.of(type)).get() + } +} \ 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 new file mode 100644 index 000000000..a73c6a7d1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/api/data/BlueprintProcessorData.kt @@ -0,0 +1,123 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.api.data + +import com.fasterxml.jackson.annotation.JsonFormat +import com.fasterxml.jackson.databind.node.ObjectNode +import io.swagger.annotations.ApiModelProperty +import java.util.* + +/** + * BlueprintProcessorData + * @author Brinda Santh + * DATE : 8/15/2018 + */ + +open class ExecutionServiceInput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + lateinit var actionIdentifiers: ActionIdentifiers + @get:ApiModelProperty(required = true) + lateinit var payload: ObjectNode +} + +open class ExecutionServiceOutput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + lateinit var actionIdentifiers: ActionIdentifiers + @get:ApiModelProperty(required = true) + var status: Status = Status() + @get:ApiModelProperty(required = true) + lateinit var payload: ObjectNode +} + +const val ACTION_MODE_ASYNC = "async" +const val ACTION_MODE_SYNC = "sync" + +open class ActionIdentifiers { + @get:ApiModelProperty(required = false) + lateinit var blueprintName: String + @get:ApiModelProperty(required = false) + lateinit var blueprintVersion: String + @get:ApiModelProperty(required = true) + lateinit var actionName: String + @get:ApiModelProperty(required = true, allowableValues = "sync, async") + lateinit var mode: String +} + +open class CommonHeader { + @get:ApiModelProperty(required = true, 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 = true) + lateinit var originatorId: String + @get:ApiModelProperty(required = true) + lateinit var requestId: String + @get:ApiModelProperty(required = true) + lateinit var subRequestId: String + @get:ApiModelProperty(required = false) + var flags: Flags? = null +} + +open class Flags { + var isForce: Boolean = false + @get:ApiModelProperty(value = "3600") + var ttl: Int = 3600 +} + +open class Status { + @get:ApiModelProperty(required = true) + var code: Int = 200 + @get:ApiModelProperty(required = true) + var eventType: String = "EVENT-ACTION-RESPONSE" + @get:ApiModelProperty(required = true, 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) + var errorMessage: String? = null + @get:ApiModelProperty(required = true) + var message: String = "success" +} + +open class BluePrintManagementInput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = false) + lateinit var blueprintName: String + @get:ApiModelProperty(required = false) + lateinit var blueprintVersion: String + @get:ApiModelProperty(required = true) + lateinit var fileChunk: FileChunk +} + +open class FileChunk { + @get:ApiModelProperty(required = true) + lateinit var chunk: ByteArray +} + +open class BluePrintManagementOutput { + @get:ApiModelProperty(required = true) + lateinit var commonHeader: CommonHeader + @get:ApiModelProperty(required = true) + var status: Status = Status() +} + + + 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 new file mode 100644 index 000000000..a32d61e2f --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/factory/ComponentNodeFactory.kt @@ -0,0 +1,68 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.factory + +import com.att.eelf.configuration.EELFManager +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.springframework.context.ApplicationContext +import org.springframework.context.ApplicationContextAware + +/** + * ComponentNode + * + * @author Brinda Santh + */ +interface ComponentNode { + + @Throws(BluePrintProcessorException::class) + fun validate(context: MutableMap, componentContext: MutableMap) + + @Throws(BluePrintProcessorException::class) + fun process(context: MutableMap, componentContext: MutableMap) + + @Throws(BluePrintProcessorException::class) + fun errorHandle(context: MutableMap, componentContext: MutableMap) + + @Throws(BluePrintProcessorException::class) + fun reTrigger(context: MutableMap, componentContext: MutableMap) +} + +/** + * ComponentNodeFactory + * + * @author Brinda Santh + */ +open class ComponentNodeFactory : ApplicationContextAware { + private val log = EELFManager.getInstance().getLogger(ComponentNodeFactory::class.java) + + var componentNodes: MutableMap = hashMapOf() + + fun getInstance(instanceName: String): ComponentNode? { + log.trace("looking for Component Nodes : {}", instanceName) + return componentNodes.get(instanceName) + } + + fun injectInstance(instanceName: String, componentNode: ComponentNode) { + this.componentNodes[instanceName] = componentNode + } + + override fun setApplicationContext(context: ApplicationContext) { + 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/PayloadUtils.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt new file mode 100644 index 000000000..9eb95e679 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/utils/PayloadUtils.kt @@ -0,0 +1,47 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core.utils + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService + + +class PayloadUtils { + + companion object { + + 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) + } + } + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintPropertiesTest.kt b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintPropertiesTest.kt deleted file mode 100644 index 66de11fde..000000000 --- a/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/core/BluePrintPropertiesTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.core - -// TODO -open class BluePrintPropertiesTest \ 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 new file mode 100644 index 000000000..3dd629c13 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/processor-core/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/core/BluePrintPropertiesTest.kt @@ -0,0 +1,20 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.core + +// TODO +open class BluePrintPropertiesTest \ 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 1ed157dcc..054f2386e 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/pom.xml @@ -18,7 +18,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor commons 0.4.2-SNAPSHOT @@ -29,11 +29,11 @@ Blueprints Processor Rest Lib - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor processor-core diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt deleted file mode 100644 index 7af91c6fe..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest - -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@Configuration -@ComponentScan -@EnableConfigurationProperties -open class BluePrintRestLibConfiguration - - -class RestLibConstants { - companion object { - const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service" - const val TYPE_TOKEN_AUTH = "token-auth" - const val TYPE_BASIC_AUTH = "basic-auth" - const val TYPE_SSL_BASIC_AUTH = "ssl-basic-auth" - const val TYPE_DME2_PROXY = "dme2-proxy" - const val TYPE_POLICY_MANAGER = "policy-manager" - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibData.kt deleted file mode 100644 index dd4d9f7d7..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/BluePrintRestLibData.kt +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest - -open class RestClientProperties { - lateinit var type: String - lateinit var url: String -} - -open class BasicAuthRestClientProperties : RestClientProperties() { - lateinit var password: String - lateinit var username: String -} - -open class TokenAuthRestClientProperties : RestClientProperties() { - var token: String? = null -} - -open class SSLBasicAuthRestClientProperties : RestClientProperties() { - lateinit var keyStoreInstance: String // JKS, PKCS12 - lateinit var sslTrust: String - lateinit var sslTrustPassword: String - lateinit var sslKey: String - lateinit var sslKeyPassword: String -} - -open class DME2RestClientProperties : RestClientProperties() { - lateinit var service: String - lateinit var subContext: String - lateinit var version: String - lateinit var envContext: String - lateinit var routeOffer: String - var partner: String? = null - lateinit var appId: String -} - -open class PolicyManagerRestClientProperties : RestClientProperties() { - lateinit var env: String - lateinit var clientAuth: String - lateinit var authorisation: String -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt deleted file mode 100644 index 98a4fd58f..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, Bell Canada, 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.service - -import org.apache.http.message.BasicHeader -import org.onap.ccsdk.apps.blueprintsprocessor.rest.BasicAuthRestClientProperties -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import java.nio.charset.Charset -import java.util.* - -class BasicAuthRestClientService(private val restClientProperties: BasicAuthRestClientProperties) : - BlueprintWebClientService { - - override fun defaultHeaders(): Map { - 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") - } - - override fun host(uri: String): String { - return restClientProperties.url + uri - } - - override fun convertToBasicHeaders(headers: Map): Array { - val customHeaders: MutableMap = headers.toMutableMap() - if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { - val encodedCredentials = setBasicAuth(restClientProperties.username, restClientProperties.password) - customHeaders[HttpHeaders.AUTHORIZATION] = "Basic $encodedCredentials" - } - return super.convertToBasicHeaders(customHeaders) - } - - private fun setBasicAuth(username: String, password: String): String { - val credentialsString = "$username:$password" - return Base64.getEncoder().encodeToString(credentialsString.toByteArray(Charset.defaultCharset())) - } - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt deleted file mode 100644 index 3888bb724..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.rest.service - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.BasicAuthRestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.DME2RestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.PolicyManagerRestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.RestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.RestLibConstants -import org.onap.ccsdk.apps.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.TokenAuthRestClientProperties -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.springframework.stereotype.Service - -@Service(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) -open class BluePrintRestLibPropertyService(private var bluePrintProperties: BluePrintProperties) { - - fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService { - val restClientProperties = restClientProperties(jsonNode) - return blueprintWebClientService(restClientProperties) - } - - fun blueprintWebClientService(selector: String): BlueprintWebClientService { - val prefix = "blueprintsprocessor.restclient.$selector" - val restClientProperties = restClientProperties(prefix) - return blueprintWebClientService(restClientProperties) - } - - fun restClientProperties(prefix: String): RestClientProperties { - val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) - return when (type) { - RestLibConstants.TYPE_BASIC_AUTH -> { - basicAuthRestClientProperties(prefix) - } - RestLibConstants.TYPE_SSL_BASIC_AUTH -> { - sslBasicAuthRestClientProperties(prefix) - } - RestLibConstants.TYPE_DME2_PROXY -> { - dme2ProxyClientProperties(prefix) - } - RestLibConstants.TYPE_POLICY_MANAGER -> { - policyManagerRestClientProperties(prefix) - } - else -> { - throw BluePrintProcessorException("Rest adaptor($type) is not supported") - } - } - } - - private fun restClientProperties(jsonNode: JsonNode): RestClientProperties { - val type = jsonNode.get("type").textValue() - return when (type) { - RestLibConstants.TYPE_TOKEN_AUTH -> { - JacksonUtils.readValue(jsonNode, TokenAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, BasicAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_SSL_BASIC_AUTH -> { - JacksonUtils.readValue(jsonNode, SSLBasicAuthRestClientProperties::class.java)!! - } - RestLibConstants.TYPE_DME2_PROXY -> { - JacksonUtils.readValue(jsonNode, DME2RestClientProperties::class.java)!! - } - RestLibConstants.TYPE_POLICY_MANAGER -> { - JacksonUtils.readValue(jsonNode, PolicyManagerRestClientProperties::class.java)!! - } - else -> { - throw BluePrintProcessorException("Rest adaptor($type) is not supported") - } - } - } - - private fun blueprintWebClientService(restClientProperties: RestClientProperties): BlueprintWebClientService { - when (restClientProperties) { - is TokenAuthRestClientProperties -> { - return TokenAuthRestClientService(restClientProperties) - } - is BasicAuthRestClientProperties -> { - return BasicAuthRestClientService(restClientProperties) - } - is SSLBasicAuthRestClientProperties -> { - return SSLBasicAuthRestClientService(restClientProperties) - } - is DME2RestClientProperties -> { - return DME2ProxyRestClientService(restClientProperties) - } - else -> { - throw BluePrintProcessorException("couldn't get rest service for") - } - } - } - - private fun basicAuthRestClientProperties(prefix: String): BasicAuthRestClientProperties { - return bluePrintProperties.propertyBeanType(prefix, BasicAuthRestClientProperties::class.java) - } - - private fun sslBasicAuthRestClientProperties(prefix: String): SSLBasicAuthRestClientProperties { - return bluePrintProperties.propertyBeanType(prefix, SSLBasicAuthRestClientProperties::class.java) - } - - private fun dme2ProxyClientProperties(prefix: String): DME2RestClientProperties { - return bluePrintProperties.propertyBeanType(prefix, DME2RestClientProperties::class.java) - } - - private fun policyManagerRestClientProperties(prefix: String): PolicyManagerRestClientProperties { - return bluePrintProperties.propertyBeanType(prefix, PolicyManagerRestClientProperties::class.java) - } -} - - diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BlueprintWebClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BlueprintWebClientService.kt deleted file mode 100644 index 0629909ec..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BlueprintWebClientService.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, Bell Canada, 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.service - -import org.apache.commons.io.IOUtils -import org.apache.http.client.methods.* -import org.apache.http.entity.StringEntity -import org.apache.http.impl.client.CloseableHttpClient -import org.apache.http.impl.client.HttpClients -import org.apache.http.message.BasicHeader -import org.onap.ccsdk.apps.blueprintsprocessor.rest.utils.WebClientUtils -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.springframework.http.HttpMethod -import java.nio.charset.Charset - -interface BlueprintWebClientService { - - fun defaultHeaders(): Map - - fun host(uri: String): String - - fun httpClient(): CloseableHttpClient { - return HttpClients.custom() - .addInterceptorFirst(WebClientUtils.logRequest()) - .addInterceptorLast(WebClientUtils.logResponse()) - .build() - } - - fun exchangeResource(methodType: String, path: String, request: String): String { - return this.exchangeResource(methodType, path, request, defaultHeaders()) - } - - fun exchangeResource(methodType: String, path: String, request: String, headers: Map): String { - val convertedHeaders: Array = convertToBasicHeaders(headers) - return when (HttpMethod.resolve(methodType)) { - HttpMethod.DELETE -> delete(path, convertedHeaders) - HttpMethod.GET -> get(path, convertedHeaders) - HttpMethod.POST -> post(path, request, convertedHeaders) - HttpMethod.PUT -> put(path, request, convertedHeaders) - HttpMethod.PATCH -> patch(path, request, convertedHeaders) - else -> throw BluePrintProcessorException("Unsupported methodType($methodType)") - } - } - - fun convertToBasicHeaders(headers: Map): Array { - val convertedHeaders = Array(headers.size){ BasicHeader("","") } - var currentElement = 0 - for ((name, value) in headers) { - convertedHeaders[currentElement++] = BasicHeader(name, value) - } - return convertedHeaders - } - - fun delete(path: String, headers: Array): String { - val httpDelete = HttpDelete(host(path)) - httpDelete.setHeaders(headers) - httpClient().execute(httpDelete).entity.content.use { - return IOUtils.toString(it, Charset.defaultCharset()) - } - } - - fun get(path: String, headers: Array): String { - val httpGet = HttpGet(host(path)) - httpGet.setHeaders(headers) - httpClient().execute(httpGet).entity.content.use { - return IOUtils.toString(it, Charset.defaultCharset()) - } - } - - fun post(path: String, request: String, headers: Array): String { - val httpPost = HttpPost(host(path)) - val entity = StringEntity(request) - httpPost.entity = entity - httpPost.setHeaders(headers) - httpClient().execute(httpPost).entity.content.use { - return IOUtils.toString(it, Charset.defaultCharset()) - } - } - - fun put(path: String, request: String, headers: Array): String { - val httpPut = HttpPut(host(path)) - val entity = StringEntity(request) - httpPut.entity = entity - httpPut.setHeaders(headers) - httpClient().execute(httpPut).entity.content.use { - return IOUtils.toString(it, Charset.defaultCharset()) - } - } - - fun patch(path: String, request: String, headers: Array): String { - val httpPatch = HttpPatch(host(path)) - val entity = StringEntity(request) - httpPatch.entity = entity - httpPatch.setHeaders(headers) - httpClient().execute(httpPatch).entity.content.use { - return IOUtils.toString(it, Charset.defaultCharset()) - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt deleted file mode 100644 index 94e146d8b..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.rest.service - -import org.onap.ccsdk.apps.blueprintsprocessor.rest.RestClientProperties - -class DME2ProxyRestClientService(restClientProperties: RestClientProperties) : BlueprintWebClientService { - override fun defaultHeaders(): Map { - TODO("not implemented") //To change body of created functions use File | Settings | File Templates. - } - - override fun host(uri: String): String { - 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/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt deleted file mode 100644 index 2bfacf417..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright © 2017-2019 AT&T, 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.apps.blueprintsprocessor.rest.service - -import org.apache.http.conn.ssl.SSLConnectionSocketFactory -import org.apache.http.impl.client.CloseableHttpClient -import org.apache.http.impl.client.HttpClients -import org.apache.http.ssl.SSLContextBuilder -import org.onap.ccsdk.apps.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties -import org.onap.ccsdk.apps.blueprintsprocessor.rest.utils.WebClientUtils -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType -import java.io.File -import java.io.FileInputStream -import java.security.KeyStore -import java.security.cert.X509Certificate - -class SSLBasicAuthRestClientService(private val restClientProperties: SSLBasicAuthRestClientProperties) : - BlueprintWebClientService { - - override fun defaultHeaders(): Map { - return mapOf( - HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE) - } - - override fun host(uri: String): String { - return restClientProperties.url + uri - } - - override fun httpClient(): CloseableHttpClient { - - val keystoreInstance = restClientProperties.keyStoreInstance - val sslKey = restClientProperties.sslKey - val sslKeyPwd = restClientProperties.sslKeyPassword - val sslTrust = restClientProperties.sslTrust - val sslTrustPwd = restClientProperties.sslTrustPassword - - val acceptingTrustStrategy = { chain: Array, authType: String -> true } - - FileInputStream(sslKey).use { keyInput -> - val keyStore = KeyStore.getInstance(keystoreInstance) - keyStore.load(keyInput, sslKeyPwd.toCharArray()) - - val sslContext = - SSLContextBuilder.create() - .loadKeyMaterial(keyStore, sslKeyPwd.toCharArray()) - .loadTrustMaterial(File(sslTrust), sslTrustPwd.toCharArray(), acceptingTrustStrategy).build() - - val csf = SSLConnectionSocketFactory(sslContext!!) - - return HttpClients.custom() - .addInterceptorFirst(WebClientUtils.logRequest()) - .addInterceptorLast(WebClientUtils.logResponse()) - .setSSLSocketFactory(csf).build() - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt deleted file mode 100644 index d5dec3ae5..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright © 2019 Bell Canada, 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.service - -import org.apache.http.message.BasicHeader -import org.onap.ccsdk.apps.blueprintsprocessor.rest.TokenAuthRestClientProperties -import org.springframework.http.HttpHeaders -import org.springframework.http.MediaType - -class TokenAuthRestClientService(private val restClientProperties: TokenAuthRestClientProperties) : - BlueprintWebClientService { - - override fun defaultHeaders(): Map { - return mapOf( - HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, - HttpHeaders.AUTHORIZATION to restClientProperties.token!!) - } - - override fun convertToBasicHeaders(headers: Map): Array { - val customHeaders: MutableMap = headers.toMutableMap() - if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { - customHeaders[HttpHeaders.AUTHORIZATION] = restClientProperties.token!! - } - return super.convertToBasicHeaders(customHeaders) - } - - override fun host(uri: String): String { - return restClientProperties.url + uri - } -} diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/utils/WebClientUtils.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/utils/WebClientUtils.kt deleted file mode 100644 index b9a014e35..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/utils/WebClientUtils.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.utils - -import org.apache.http.HttpRequestInterceptor -import org.apache.http.HttpResponseInterceptor -import org.slf4j.Logger -import org.slf4j.LoggerFactory - -class WebClientUtils { - companion object { - - val log: Logger = LoggerFactory.getLogger(WebClientUtils::class.java) - - fun logRequest(): HttpRequestInterceptor = - HttpRequestInterceptor { request, _ -> log.info("Rest request method(${request?.requestLine?.method}), url(${request?.requestLine?.uri})") } - - 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/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt new file mode 100644 index 000000000..05143f3d8 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibConfiguration.kt @@ -0,0 +1,39 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest + +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@Configuration +@ComponentScan +@EnableConfigurationProperties +open class BluePrintRestLibConfiguration + + +class RestLibConstants { + companion object { + const val SERVICE_BLUEPRINT_REST_LIB_PROPERTY = "blueprint-rest-lib-property-service" + const val TYPE_TOKEN_AUTH = "token-auth" + const val TYPE_BASIC_AUTH = "basic-auth" + const val TYPE_SSL_BASIC_AUTH = "ssl-basic-auth" + const val TYPE_DME2_PROXY = "dme2-proxy" + const val TYPE_POLICY_MANAGER = "policy-manager" + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt new file mode 100644 index 000000000..4e6e62efb --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/BluePrintRestLibData.kt @@ -0,0 +1,55 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest + +open class RestClientProperties { + lateinit var type: String + lateinit var url: String +} + +open class BasicAuthRestClientProperties : RestClientProperties() { + lateinit var password: String + lateinit var username: String +} + +open class TokenAuthRestClientProperties : RestClientProperties() { + var token: String? = null +} + +open class SSLBasicAuthRestClientProperties : RestClientProperties() { + lateinit var keyStoreInstance: String // JKS, PKCS12 + lateinit var sslTrust: String + lateinit var sslTrustPassword: String + lateinit var sslKey: String + lateinit var sslKeyPassword: String +} + +open class DME2RestClientProperties : RestClientProperties() { + lateinit var service: String + lateinit var subContext: String + lateinit var version: String + lateinit var envContext: String + lateinit var routeOffer: String + var partner: String? = null + lateinit var appId: String +} + +open class PolicyManagerRestClientProperties : RestClientProperties() { + lateinit var env: String + lateinit var clientAuth: String + lateinit var authorisation: String +} \ 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 new file mode 100644 index 000000000..7737fd1a5 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BasicAuthRestClientService.kt @@ -0,0 +1,58 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada, 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.apache.http.message.BasicHeader +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.* + +class BasicAuthRestClientService(private val restClientProperties: BasicAuthRestClientProperties) : + BlueprintWebClientService { + + override fun defaultHeaders(): Map { + 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") + } + + override fun host(uri: String): String { + return restClientProperties.url + uri + } + + override fun convertToBasicHeaders(headers: Map): Array { + val customHeaders: MutableMap = headers.toMutableMap() + if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { + val encodedCredentials = setBasicAuth(restClientProperties.username, restClientProperties.password) + customHeaders[HttpHeaders.AUTHORIZATION] = "Basic $encodedCredentials" + } + return super.convertToBasicHeaders(customHeaders) + } + + private fun setBasicAuth(username: String, password: String): String { + val credentialsString = "$username:$password" + return Base64.getEncoder().encodeToString(credentialsString.toByteArray(Charset.defaultCharset())) + } + + +} \ 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/BluePrintRestLibPropertyService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt new file mode 100644 index 000000000..dc974468b --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyService.kt @@ -0,0 +1,129 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.DME2RestClientProperties +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.TokenAuthRestClientProperties +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.stereotype.Service + +@Service(RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY) +open class BluePrintRestLibPropertyService(private var bluePrintProperties: BluePrintProperties) { + + fun blueprintWebClientService(jsonNode: JsonNode): BlueprintWebClientService { + val restClientProperties = restClientProperties(jsonNode) + return blueprintWebClientService(restClientProperties) + } + + fun blueprintWebClientService(selector: String): BlueprintWebClientService { + val prefix = "blueprintsprocessor.restclient.$selector" + val restClientProperties = restClientProperties(prefix) + return blueprintWebClientService(restClientProperties) + } + + fun restClientProperties(prefix: String): RestClientProperties { + val type = bluePrintProperties.propertyBeanType("$prefix.type", String::class.java) + return when (type) { + RestLibConstants.TYPE_BASIC_AUTH -> { + basicAuthRestClientProperties(prefix) + } + RestLibConstants.TYPE_SSL_BASIC_AUTH -> { + sslBasicAuthRestClientProperties(prefix) + } + RestLibConstants.TYPE_DME2_PROXY -> { + dme2ProxyClientProperties(prefix) + } + RestLibConstants.TYPE_POLICY_MANAGER -> { + policyManagerRestClientProperties(prefix) + } + else -> { + throw BluePrintProcessorException("Rest adaptor($type) is not supported") + } + } + } + + private fun restClientProperties(jsonNode: JsonNode): RestClientProperties { + val type = jsonNode.get("type").textValue() + return when (type) { + RestLibConstants.TYPE_TOKEN_AUTH -> { + JacksonUtils.readValue(jsonNode, TokenAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, BasicAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_SSL_BASIC_AUTH -> { + JacksonUtils.readValue(jsonNode, SSLBasicAuthRestClientProperties::class.java)!! + } + RestLibConstants.TYPE_DME2_PROXY -> { + JacksonUtils.readValue(jsonNode, DME2RestClientProperties::class.java)!! + } + RestLibConstants.TYPE_POLICY_MANAGER -> { + JacksonUtils.readValue(jsonNode, PolicyManagerRestClientProperties::class.java)!! + } + else -> { + throw BluePrintProcessorException("Rest adaptor($type) is not supported") + } + } + } + + private fun blueprintWebClientService(restClientProperties: RestClientProperties): BlueprintWebClientService { + when (restClientProperties) { + is TokenAuthRestClientProperties -> { + return TokenAuthRestClientService(restClientProperties) + } + is BasicAuthRestClientProperties -> { + return BasicAuthRestClientService(restClientProperties) + } + is SSLBasicAuthRestClientProperties -> { + return SSLBasicAuthRestClientService(restClientProperties) + } + is DME2RestClientProperties -> { + return DME2ProxyRestClientService(restClientProperties) + } + else -> { + throw BluePrintProcessorException("couldn't get rest service for") + } + } + } + + private fun basicAuthRestClientProperties(prefix: String): BasicAuthRestClientProperties { + return bluePrintProperties.propertyBeanType(prefix, BasicAuthRestClientProperties::class.java) + } + + private fun sslBasicAuthRestClientProperties(prefix: String): SSLBasicAuthRestClientProperties { + return bluePrintProperties.propertyBeanType(prefix, SSLBasicAuthRestClientProperties::class.java) + } + + private fun dme2ProxyClientProperties(prefix: String): DME2RestClientProperties { + return bluePrintProperties.propertyBeanType(prefix, DME2RestClientProperties::class.java) + } + + private fun policyManagerRestClientProperties(prefix: String): PolicyManagerRestClientProperties { + return bluePrintProperties.propertyBeanType(prefix, PolicyManagerRestClientProperties::class.java) + } +} + + 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 new file mode 100644 index 000000000..b34d66d19 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BlueprintWebClientService.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada, 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.apache.commons.io.IOUtils +import org.apache.http.client.methods.* +import org.apache.http.entity.StringEntity +import org.apache.http.impl.client.CloseableHttpClient +import org.apache.http.impl.client.HttpClients +import org.apache.http.message.BasicHeader +import org.onap.ccsdk.cds.blueprintsprocessor.rest.utils.WebClientUtils +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.springframework.http.HttpMethod +import java.nio.charset.Charset + +interface BlueprintWebClientService { + + fun defaultHeaders(): Map + + fun host(uri: String): String + + fun httpClient(): CloseableHttpClient { + return HttpClients.custom() + .addInterceptorFirst(WebClientUtils.logRequest()) + .addInterceptorLast(WebClientUtils.logResponse()) + .build() + } + + fun exchangeResource(methodType: String, path: String, request: String): String { + return this.exchangeResource(methodType, path, request, defaultHeaders()) + } + + fun exchangeResource(methodType: String, path: String, request: String, headers: Map): String { + val convertedHeaders: Array = convertToBasicHeaders(headers) + return when (HttpMethod.resolve(methodType)) { + HttpMethod.DELETE -> delete(path, convertedHeaders) + HttpMethod.GET -> get(path, convertedHeaders) + HttpMethod.POST -> post(path, request, convertedHeaders) + HttpMethod.PUT -> put(path, request, convertedHeaders) + HttpMethod.PATCH -> patch(path, request, convertedHeaders) + else -> throw BluePrintProcessorException("Unsupported methodType($methodType)") + } + } + + fun convertToBasicHeaders(headers: Map): Array { + val convertedHeaders = Array(headers.size){ BasicHeader("","") } + var currentElement = 0 + for ((name, value) in headers) { + convertedHeaders[currentElement++] = BasicHeader(name, value) + } + return convertedHeaders + } + + fun delete(path: String, headers: Array): String { + val httpDelete = HttpDelete(host(path)) + httpDelete.setHeaders(headers) + httpClient().execute(httpDelete).entity.content.use { + return IOUtils.toString(it, Charset.defaultCharset()) + } + } + + fun get(path: String, headers: Array): String { + val httpGet = HttpGet(host(path)) + httpGet.setHeaders(headers) + httpClient().execute(httpGet).entity.content.use { + return IOUtils.toString(it, Charset.defaultCharset()) + } + } + + fun post(path: String, request: String, headers: Array): String { + val httpPost = HttpPost(host(path)) + val entity = StringEntity(request) + httpPost.entity = entity + httpPost.setHeaders(headers) + httpClient().execute(httpPost).entity.content.use { + return IOUtils.toString(it, Charset.defaultCharset()) + } + } + + fun put(path: String, request: String, headers: Array): String { + val httpPut = HttpPut(host(path)) + val entity = StringEntity(request) + httpPut.entity = entity + httpPut.setHeaders(headers) + httpClient().execute(httpPut).entity.content.use { + return IOUtils.toString(it, Charset.defaultCharset()) + } + } + + fun patch(path: String, request: String, headers: Array): String { + val httpPatch = HttpPatch(host(path)) + val entity = StringEntity(request) + httpPatch.entity = entity + httpPatch.setHeaders(headers) + httpClient().execute(httpPatch).entity.content.use { + return IOUtils.toString(it, Charset.defaultCharset()) + } + } +} \ 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/DME2ProxyRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt new file mode 100644 index 000000000..8e0a2d3f0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/DME2ProxyRestClientService.kt @@ -0,0 +1,29 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestClientProperties + +class DME2ProxyRestClientService(restClientProperties: RestClientProperties) : BlueprintWebClientService { + override fun defaultHeaders(): Map { + TODO("not implemented") //To change body of created functions use File | Settings | File Templates. + } + + override fun host(uri: String): String { + 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/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt new file mode 100644 index 000000000..3d3b0a57e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/SSLBasicAuthRestClientService.kt @@ -0,0 +1,72 @@ +/* + * Copyright © 2017-2019 AT&T, Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.apache.http.conn.ssl.SSLConnectionSocketFactory +import org.apache.http.impl.client.CloseableHttpClient +import org.apache.http.impl.client.HttpClients +import org.apache.http.ssl.SSLContextBuilder +import org.onap.ccsdk.cds.blueprintsprocessor.rest.SSLBasicAuthRestClientProperties +import org.onap.ccsdk.cds.blueprintsprocessor.rest.utils.WebClientUtils +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType +import java.io.File +import java.io.FileInputStream +import java.security.KeyStore +import java.security.cert.X509Certificate + +class SSLBasicAuthRestClientService(private val restClientProperties: SSLBasicAuthRestClientProperties) : + BlueprintWebClientService { + + override fun defaultHeaders(): Map { + return mapOf( + HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE) + } + + override fun host(uri: String): String { + return restClientProperties.url + uri + } + + override fun httpClient(): CloseableHttpClient { + + val keystoreInstance = restClientProperties.keyStoreInstance + val sslKey = restClientProperties.sslKey + val sslKeyPwd = restClientProperties.sslKeyPassword + val sslTrust = restClientProperties.sslTrust + val sslTrustPwd = restClientProperties.sslTrustPassword + + val acceptingTrustStrategy = { chain: Array, authType: String -> true } + + FileInputStream(sslKey).use { keyInput -> + val keyStore = KeyStore.getInstance(keystoreInstance) + keyStore.load(keyInput, sslKeyPwd.toCharArray()) + + val sslContext = + SSLContextBuilder.create() + .loadKeyMaterial(keyStore, sslKeyPwd.toCharArray()) + .loadTrustMaterial(File(sslTrust), sslTrustPwd.toCharArray(), acceptingTrustStrategy).build() + + val csf = SSLConnectionSocketFactory(sslContext!!) + + return HttpClients.custom() + .addInterceptorFirst(WebClientUtils.logRequest()) + .addInterceptorLast(WebClientUtils.logResponse()) + .setSSLSocketFactory(csf).build() + } + } +} \ 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/TokenAuthRestClientService.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt new file mode 100644 index 000000000..609267eb9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/TokenAuthRestClientService.kt @@ -0,0 +1,47 @@ +/* + * Copyright © 2019 Bell Canada, 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.apache.http.message.BasicHeader +import org.onap.ccsdk.cds.blueprintsprocessor.rest.TokenAuthRestClientProperties +import org.springframework.http.HttpHeaders +import org.springframework.http.MediaType + +class TokenAuthRestClientService(private val restClientProperties: TokenAuthRestClientProperties) : + BlueprintWebClientService { + + override fun defaultHeaders(): Map { + return mapOf( + HttpHeaders.CONTENT_TYPE to MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.ACCEPT to MediaType.APPLICATION_JSON_VALUE, + HttpHeaders.AUTHORIZATION to restClientProperties.token!!) + } + + override fun convertToBasicHeaders(headers: Map): Array { + val customHeaders: MutableMap = headers.toMutableMap() + if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) { + customHeaders[HttpHeaders.AUTHORIZATION] = restClientProperties.token!! + } + return super.convertToBasicHeaders(customHeaders) + } + + override fun host(uri: String): String { + return restClientProperties.url + uri + } +} 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 new file mode 100644 index 000000000..42006569f --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/utils/WebClientUtils.kt @@ -0,0 +1,35 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.utils + +import org.apache.http.HttpRequestInterceptor +import org.apache.http.HttpResponseInterceptor +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +class WebClientUtils { + companion object { + + val log: Logger = LoggerFactory.getLogger(WebClientUtils::class.java) + + fun logRequest(): HttpRequestInterceptor = + HttpRequestInterceptor { request, _ -> log.info("Rest request method(${request?.requestLine?.method}), url(${request?.requestLine?.uri})") } + + 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/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt deleted file mode 100644 index d6e5549a6..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.service - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.rest.BluePrintRestLibConfiguration -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 - - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, BlueprintPropertyConfiguration::class, BluePrintProperties::class]) -@TestPropertySource(properties = -["blueprintsprocessor.restclient.sample.type=basic-auth", - "blueprintsprocessor.restclient.sample.url=http://localhost:8080", - "blueprintsprocessor.restclient.sample.userId=sampleuser"]) - -class BluePrintRestLibPropertyServiceTest { - - @Autowired - lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService - - @Test - fun testRestClientProperties() { - val properties = bluePrintRestLibPropertyService.restClientProperties("blueprintsprocessor.restclient.sample") - assertNotNull(properties, "failed to create property bean") - assertNotNull(properties.url, "failed to get url property in property bean") - } - - @Test - fun testBlueprintWebClientService() { - val blueprintWebClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") - assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService") - } - -} - diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/RestClientServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/RestClientServiceTest.kt deleted file mode 100644 index 0390550cc..000000000 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/rest/service/RestClientServiceTest.kt +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Copyright (C) 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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.rest.service - -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintProperties -import org.onap.ccsdk.apps.blueprintsprocessor.core.BlueprintPropertyConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.rest.BluePrintRestLibConfiguration -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration -import org.springframework.boot.test.context.SpringBootTest -import org.springframework.http.HttpMethod -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.GetMapping -import org.springframework.web.bind.annotation.PatchMapping -import org.springframework.web.bind.annotation.RequestMapping -import org.springframework.web.bind.annotation.RestController -import kotlin.test.Test -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, BlueprintPropertyConfiguration::class, - SampleController::class, BluePrintProperties::class, BluePrintProperties::class]) -@TestPropertySource(properties = -["blueprintsprocessor.restclient.sample.type=basic-auth", - "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8080", - "blueprintsprocessor.restclient.sample.username=sampleuser", - "blueprintsprocessor.restclient.sample.password=sampletoken"]) -class RestClientServiceTest { - - @Autowired - lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService - - @Test - fun testBaseAuth() { - val restClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") - val headers = mutableMapOf() - headers["X-Transaction-Id"] = "1234" - val response = restClientService.exchangeResource(HttpMethod.GET.name, "/sample/name", "") - assertNotNull(response, "failed to get response") - } - - @Test - fun testPatch() { - val restClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") - val response = restClientService.exchangeResource(HttpMethod.PATCH.name, "/sample/name", "") - assertEquals("Patch request successful", response, "failed to get patch response") - } - -} - -@RestController -@RequestMapping("/sample") -open class SampleController { - @GetMapping("/name") - fun getName(): String = "Sample Controller" - @PatchMapping("/name") - fun patchName(): String = "Patch request successful" -} - diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.kt new file mode 100644 index 000000000..c57745713 --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/BluePrintRestLibPropertyServiceTest.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.blueprintsprocessor.rest.service + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BluePrintRestLibConfiguration +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull + + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [BluePrintRestLibConfiguration::class, BlueprintPropertyConfiguration::class, BluePrintProperties::class]) +@TestPropertySource(properties = +["blueprintsprocessor.restclient.sample.type=basic-auth", + "blueprintsprocessor.restclient.sample.url=http://localhost:8080", + "blueprintsprocessor.restclient.sample.userId=sampleuser"]) + +class BluePrintRestLibPropertyServiceTest { + + @Autowired + lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService + + @Test + fun testRestClientProperties() { + val properties = bluePrintRestLibPropertyService.restClientProperties("blueprintsprocessor.restclient.sample") + assertNotNull(properties, "failed to create property bean") + assertNotNull(properties.url, "failed to get url property in property bean") + } + + @Test + fun testBlueprintWebClientService() { + val blueprintWebClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") + assertNotNull(blueprintWebClientService, "failed to create blueprintWebClientService") + } + +} + 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 new file mode 100644 index 000000000..6da59399e --- /dev/null +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/rest/service/RestClientServiceTest.kt @@ -0,0 +1,83 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Copyright (C) 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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.rest.service + +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintProperties +import org.onap.ccsdk.cds.blueprintsprocessor.core.BlueprintPropertyConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.rest.BluePrintRestLibConfiguration +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.http.HttpMethod +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.GetMapping +import org.springframework.web.bind.annotation.PatchMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController +import kotlin.test.Test +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, BlueprintPropertyConfiguration::class, + SampleController::class, BluePrintProperties::class, BluePrintProperties::class]) +@TestPropertySource(properties = +["blueprintsprocessor.restclient.sample.type=basic-auth", + "blueprintsprocessor.restclient.sample.url=http://127.0.0.1:8080", + "blueprintsprocessor.restclient.sample.username=sampleuser", + "blueprintsprocessor.restclient.sample.password=sampletoken"]) +class RestClientServiceTest { + + @Autowired + lateinit var bluePrintRestLibPropertyService: BluePrintRestLibPropertyService + + @Test + fun testBaseAuth() { + val restClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") + val headers = mutableMapOf() + headers["X-Transaction-Id"] = "1234" + val response = restClientService.exchangeResource(HttpMethod.GET.name, "/sample/name", "") + assertNotNull(response, "failed to get response") + } + + @Test + fun testPatch() { + val restClientService = bluePrintRestLibPropertyService.blueprintWebClientService("sample") + val response = restClientService.exchangeResource(HttpMethod.PATCH.name, "/sample/name", "") + assertEquals("Patch request successful", response, "failed to get patch response") + } + +} + +@RestController +@RequestMapping("/sample") +open class SampleController { + @GetMapping("/name") + fun getName(): String = "Sample Controller" + @PatchMapping("/name") + fun patchName(): String = "Patch request successful" +} + diff --git a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/resources/logback-test.xml b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/resources/logback-test.xml index f9ec9fe57..355cd3ace 100644 --- a/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/resources/logback-test.xml +++ b/ms/blueprintsprocessor/modules/commons/rest-lib/src/test/resources/logback-test.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/modules/inbounds/pom.xml b/ms/blueprintsprocessor/modules/inbounds/pom.xml index 060c7e42d..c8f6b9e42 100644 --- a/ms/blueprintsprocessor/modules/inbounds/pom.xml +++ b/ms/blueprintsprocessor/modules/inbounds/pom.xml @@ -18,7 +18,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor modules 0.4.2-SNAPSHOT @@ -34,11 +34,11 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor workflow-service - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions resource-resolution diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml index 26ce4a8c7..4d5857651 100644 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/pom.xml @@ -17,7 +17,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor inbounds 0.4.2-SNAPSHOT diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionController.java b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionController.java deleted file mode 100644 index fb833a573..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionController.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.resource.api; - -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService; -import org.springframework.http.MediaType; -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; - -/** - * ResourceResolutionController - * - * @author Brinda Santh Date : 8/13/2018 - */ - -@RestController -@RequestMapping("/api/v1/resource") -public class ResourceResolutionController { - - private ResourceResolutionService resourceResolutionService; - - public ResourceResolutionController(ResourceResolutionService resourceResolutionService) { - this.resourceResolutionService = resourceResolutionService; - } - - @RequestMapping(path = "/ping", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public @ResponseBody - Mono ping() { - return Mono.just("Success"); - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionController.java b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionController.java new file mode 100644 index 000000000..3e94d79ee --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/main/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionController.java @@ -0,0 +1,48 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.resource.api; + +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionService; +import org.springframework.http.MediaType; +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; + +/** + * ResourceResolutionController + * + * @author Brinda Santh Date : 8/13/2018 + */ + +@RestController +@RequestMapping("/api/v1/resource") +public class ResourceResolutionController { + + private ResourceResolutionService resourceResolutionService; + + public ResourceResolutionController(ResourceResolutionService resourceResolutionService) { + this.resourceResolutionService = resourceResolutionService; + } + + @RequestMapping(path = "/ping", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public @ResponseBody + Mono ping() { + return Mono.just("Success"); + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java deleted file mode 100644 index 53718654c..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/apps/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright © 2019 Bell Canada - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.resource.api; - -// TODO -public class ResourceResolutionControllerTest { - -} diff --git a/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java new file mode 100644 index 000000000..f8c37f828 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/resource-api/src/test/java/org/onap/ccsdk/cds/blueprintsprocessor/resource/api/ResourceResolutionControllerTest.java @@ -0,0 +1,22 @@ +/* + * Copyright © 2019 Bell Canada + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.resource.api; + +// TODO +public class ResourceResolutionControllerTest { + +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml index 0c6b8e77d..d3f8b4616 100755 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/pom.xml @@ -20,7 +20,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor inbounds 0.4.2-SNAPSHOT @@ -38,16 +38,16 @@ - org.onap.ccsdk.apps.components + org.onap.ccsdk.cds.components proto-definition ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-validation diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt deleted file mode 100644 index d689187e8..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * 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.apps.blueprintsprocessor.selfservice.api - -import io.grpc.StatusException -import io.grpc.stub.StreamObserver -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.currentTimestamp -import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.apps.controllerblueprints.common.api.Status -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementInput -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementOutput -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementServiceGrpc -import org.slf4j.LoggerFactory -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.stereotype.Service -import java.io.File - -@Service -open class BluePrintManagementGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, - private val bluePrintCatalogService: BluePrintCatalogService) - : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() { - - private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java) - - @PreAuthorize("hasRole('USER')") - override fun uploadBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver) { - val blueprintName = request.blueprintName - val blueprintVersion = request.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - log.info("request(${request.commonHeader.requestId}): Received upload $blueprint") - - val blueprintArchivedFilePath = "${bluePrintCoreConfiguration.archivePath}/$blueprintName/$blueprintVersion/$blueprintName.zip" - try { - val blueprintArchivedFile = File(blueprintArchivedFilePath) - - saveToDisk(request, blueprintArchivedFile) - val blueprintId = bluePrintCatalogService.saveToDatabase(blueprintArchivedFile) - - File("${bluePrintCoreConfiguration.archivePath}/$blueprintName").deleteRecursively() - - responseObserver.onNext(successStatus("Successfully uploaded $blueprint with id($blueprintId)", request.commonHeader)) - responseObserver.onCompleted() - } catch (e: Exception) { - failStatus("request(${request.commonHeader.requestId}): Failed to upload $blueprint at path $blueprintArchivedFilePath", e) - } - } - - @PreAuthorize("hasRole('USER')") - override fun removeBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver) { - val blueprintName = request.blueprintName - val blueprintVersion = request.blueprintVersion - val blueprint = "blueprint $blueprintName:$blueprintVersion" - - log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") - - try { - bluePrintCatalogService.deleteFromDatabase(blueprintName, blueprintVersion) - responseObserver.onNext(successStatus("Successfully deleted $blueprint", request.commonHeader)) - responseObserver.onCompleted() - } catch (e: Exception) { - failStatus("request(${request.commonHeader.requestId}): Failed to delete $blueprint", e) - } - } - - private fun saveToDisk(request: BluePrintManagementInput, blueprintDir: File) { - log.info("request(${request.commonHeader.requestId}): Writing CBA File under :${blueprintDir.absolutePath}") - if (blueprintDir.exists()) { - log.info("request(${request.commonHeader.requestId}): Re-creating blueprint directory(${blueprintDir.absolutePath})") - //FileUtils.deleteDirectory(blueprintDir.parentFile) - blueprintDir.parentFile.deleteRecursively() - } - blueprintDir.parentFile.mkdirs() - //FileUtils.forceMkdir(blueprintDir.parentFile) - blueprintDir.writeBytes(request.fileChunk.chunk.toByteArray()).apply { - log.info("request(${request.commonHeader.requestId}): CBA file(${blueprintDir.absolutePath} written successfully") - } - - } - - private fun successStatus(message: String, header: CommonHeader): BluePrintManagementOutput = - BluePrintManagementOutput.newBuilder() - .setCommonHeader(header) - .setStatus(Status.newBuilder() - .setTimestamp(currentTimestamp()) - .setMessage(message) - .setCode(200) - .build()) - .build() - - private fun failStatus(message: String, e: Exception): StatusException { - log.error(message, e) - return io.grpc.Status.INTERNAL - .withDescription(message) - .withCause(e) - .asException() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt deleted file mode 100644 index ebeda69b5..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api - -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.toJava -import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput -import org.slf4j.LoggerFactory -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.stereotype.Service - -@Service -open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, - private val executionServiceHandler: ExecutionServiceHandler) - : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { - private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java) - - @PreAuthorize("hasRole('USER')") - override fun process( - responseObserver: StreamObserver): StreamObserver { - - return object : StreamObserver { - override fun onNext(executionServiceInput: ExecutionServiceInput) { - try { - runBlocking { - executionServiceHandler.process(executionServiceInput.toJava(), responseObserver) - } - } catch (e: Exception) { - onError(e) - } - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - responseObserver.onError(io.grpc.Status.INTERNAL - .withDescription(error.message) - .asException()) - } - - override fun onCompleted() { - log.info("Completed") - } - } - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt deleted file mode 100644 index 6e7294791..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api - -import io.swagger.annotations.ApiOperation -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.http.MediaType -import org.springframework.http.codec.multipart.FilePart -import org.springframework.security.access.prepost.PreAuthorize -import org.springframework.web.bind.annotation.* -import reactor.core.publisher.Mono - -@RestController -@RequestMapping("/api/v1/execution-service") -open class ExecutionServiceController { - - @Autowired - lateinit var executionServiceHandler: ExecutionServiceHandler - - @RequestMapping(path = ["/ping"], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]) - @ResponseBody - fun ping(): String = runBlocking { - "Success" - } - - @PostMapping(path = ["/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) - @ApiOperation(value = "Upload CBA", notes = "Takes a File and load it in the runtime database") - @ResponseBody - @PreAuthorize("hasRole('USER')") - fun upload(@RequestPart("file") parts: Mono): Mono { - return parts - .filter { it is FilePart } - .ofType(FilePart::class.java) - .flatMap(executionServiceHandler::upload) - } - - @RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) - @ApiOperation(value = "Resolve Resource Mappings", - notes = "Takes the blueprint information and process as per the payload") - @ResponseBody - @PreAuthorize("hasRole('USER')") - fun process(@RequestBody executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput = runBlocking { - if (executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC) { - throw IllegalStateException("Can't process async request through the REST endpoint. Use gRPC for async processing.") - } - executionServiceHandler.doProcess(executionServiceInput) - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt deleted file mode 100644 index 05a569cb8..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api - -import com.fasterxml.jackson.databind.node.JsonNodeFactory -import io.grpc.stub.StreamObserver -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ACTION_MODE_SYNC -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.saveCBAFile -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils.toProto -import org.onap.ccsdk.apps.controllerblueprints.common.api.EventType -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintFileUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.slf4j.LoggerFactory -import org.springframework.http.codec.multipart.FilePart -import org.springframework.stereotype.Service -import reactor.core.publisher.Mono -import java.util.stream.Collectors - -@Service -class ExecutionServiceHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, - private val bluePrintCatalogService: BluePrintCatalogService, - private val bluePrintWorkflowExecutionService - : BluePrintWorkflowExecutionService) { - - private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString()) - - fun upload(filePart: FilePart): Mono { - try { - val archivedPath = BluePrintFileUtils.getCbaStorageDirectory(bluePrintCoreConfiguration.archivePath) - val cbaPath = saveCBAFile(filePart, archivedPath) - bluePrintCatalogService.saveToDatabase(cbaPath.toFile()).let { - return Mono.just("{\"status\": \"Successfully uploaded blueprint with id($it)\"}") - } - } catch (e: Exception) { - return Mono.error(BluePrintException("Error uploading the CBA file.", e)) - } - } - - suspend fun process(executionServiceInput: ExecutionServiceInput, - responseObserver: StreamObserver) { - when { - executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> { - GlobalScope.launch(Dispatchers.Default) { - val executionServiceOutput = doProcess(executionServiceInput) - responseObserver.onNext(executionServiceOutput.toProto()) - responseObserver.onCompleted() - } - responseObserver.onNext(response(executionServiceInput).toProto()) - } - executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> { - val executionServiceOutput = doProcess(executionServiceInput) - responseObserver.onNext(executionServiceOutput.toProto()) - responseObserver.onCompleted() - } - else -> responseObserver.onNext(response(executionServiceInput, - "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.", - true).toProto()); - } - } - - suspend fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - val requestId = executionServiceInput.commonHeader.requestId - log.info("processing request id $requestId") - - val actionIdentifiers = executionServiceInput.actionIdentifiers - - val blueprintName = actionIdentifiers.blueprintName - val blueprintVersion = actionIdentifiers.blueprintVersion - - val basePath = bluePrintCatalogService.getFromDatabase(blueprintName, blueprintVersion) - log.info("blueprint base path $basePath") - - val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString()) - - val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(blueprintRuntimeService, - executionServiceInput, hashMapOf()) - - val errors = blueprintRuntimeService.getBluePrintError().errors - if (errors.isNotEmpty()) { - val errorMessage = errors.stream().map { it.toString() }.collect(Collectors.joining(", ")) - setErrorStatus(errorMessage, output.status) - } - - return output - } - - private fun setErrorStatus(errorMessage: String, status: Status) { - status.errorMessage = errorMessage - status.eventType = EventType.EVENT_COMPONENT_FAILURE.name - status.code = 500 - status.message = BluePrintConstants.STATUS_FAILURE - } - - private fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "", - failure: Boolean = false): ExecutionServiceOutput { - val executionServiceOutput = ExecutionServiceOutput() - executionServiceOutput.commonHeader = executionServiceInput.commonHeader - executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers - executionServiceOutput.payload = JsonNodeFactory.instance.objectNode() - - val status = Status() - if (failure) { - setErrorStatus(errorMessage, status) - } else { - status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name - status.code = 200 - status.message = BluePrintConstants.STATUS_PROCESSING - } - - executionServiceOutput.status = status - - return executionServiceOutput - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt deleted file mode 100644 index c344ca00a..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.selfservice.api.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.apps.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.apps.controllerblueprints.common.api.EventType -import org.onap.ccsdk.apps.controllerblueprints.common.api.Flag -import org.onap.ccsdk.apps.controllerblueprints.common.api.Status -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.apps.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 - -fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers.toProto(): ActionIdentifiers { - val actionIdentifier = ActionIdentifiers.newBuilder() - actionIdentifier.actionName = this.actionName - actionIdentifier.blueprintName = this.blueprintName - actionIdentifier.blueprintVersion = this.blueprintVersion - actionIdentifier.mode = this.mode - return actionIdentifier.build() -} - -fun ActionIdentifiers.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers { - val actionIdentifier = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers() - actionIdentifier.actionName = this.actionName - actionIdentifier.blueprintName = this.blueprintName - actionIdentifier.blueprintVersion = this.blueprintVersion - actionIdentifier.mode = this.mode - return actionIdentifier -} - -// COMMON HEADER - -fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader.toProto(): CommonHeader { - val commonHeader = CommonHeader.newBuilder() - commonHeader.originatorId = this.originatorId - commonHeader.requestId = this.requestId - commonHeader.subRequestId = this.subRequestId - commonHeader.timestamp = this.timestamp.toString() - commonHeader.flag = this.flags?.toProto() - return commonHeader.build() -} - -fun CommonHeader.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader { - val commonHeader = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader() - commonHeader.originatorId = this.originatorId - commonHeader.requestId = this.requestId - commonHeader.subRequestId = this.subRequestId - commonHeader.timestamp = if (!Strings.isNullOrEmpty(this.timestamp)) { - formatter.parse(this.timestamp) - } else { - Date() - } - commonHeader.flags = this.flag?.toJava() - return commonHeader -} - -// FLAG - -fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags.toProto(): Flag { - val flag = Flag.newBuilder() - flag.isForce = this.isForce - flag.ttl = this.ttl - return flag.build() -} - -fun Flag.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags { - val flag = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags() - flag.isForce = this.isForce - flag.ttl = this.ttl - return flag -} - -// STATUS - -fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status.toProto(): Status { - val status = Status.newBuilder() - status.code = this.code - status.errorMessage = this.errorMessage ?: "" - status.message = this.message - status.timestamp = this.timestamp.toString() - status.eventType = EventType.valueOf(this.eventType) - return status.build() -} - -// EXECUTION INPUT - -fun ExecutionServiceInput.toJava(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput { - val executionServiceInput = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput() - executionServiceInput.actionIdentifiers = this.actionIdentifiers.toJava() - executionServiceInput.commonHeader = this.commonHeader.toJava() - executionServiceInput.payload = JacksonUtils.jsonNode(JsonFormat.printer().print(this.payload)) as ObjectNode - return executionServiceInput -} - -// EXECUTION OUPUT - -fun org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput.toProto(): ExecutionServiceOutput { - val executionServiceOuput = ExecutionServiceOutput.newBuilder() - executionServiceOuput.actionIdentifiers = this.actionIdentifiers.toProto() - executionServiceOuput.commonHeader = this.commonHeader.toProto() - executionServiceOuput.status = this.status.toProto() - val struct = Struct.newBuilder() - JsonFormat.parser().merge(JacksonUtils.getJson(this.payload), struct) - executionServiceOuput.payload = struct.build() - return executionServiceOuput.build() -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt deleted file mode 100644 index 6d22fdab5..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/Utils.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.selfservice.api.utils - -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintException -import org.springframework.http.codec.multipart.FilePart -import org.springframework.util.StringUtils -import java.io.File -import java.io.IOException -import java.nio.file.Path -import java.time.LocalDateTime -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.util.* - - -fun currentTimestamp(): String { - val now = LocalDateTime.now(ZoneId.systemDefault()) - val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - return formatter.format(now) -} - - -@Throws(BluePrintException::class, IOException::class) -fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Path { - - val fileName = StringUtils.cleanPath(filePart.filename()) - - if (StringUtils.getFilenameExtension(fileName) != "zip") { - throw BluePrintException("Invalid file extension required ZIP") - } - - val changedFileName = UUID.randomUUID().toString() + ".zip" - - val targetLocation = targetDirectory.resolve(changedFileName) - - val file = File(targetLocation.toString()) - if (file.exists()) { - file.delete() - } - file.createNewFile() - - filePart.transferTo(file) - - return targetLocation -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt deleted file mode 100644 index 100bd320b..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.validation - -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintTypeValidatorService -import org.onap.ccsdk.apps.controllerblueprints.validation.BluePrintDesignTimeValidatorService -import org.onap.ccsdk.apps.controllerblueprints.validation.extension.ResourceDefinitionValidator -import org.springframework.stereotype.Service - -@Service -open class BluePrintRuntimeValidatorService(bluePrintTypeValidatorService: BluePrintTypeValidatorService, - resourceDefinitionValidator: ResourceDefinitionValidator) - : BluePrintDesignTimeValidatorService(bluePrintTypeValidatorService, resourceDefinitionValidator) diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt new file mode 100644 index 000000000..1fa141034 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandler.kt @@ -0,0 +1,115 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.grpc.StatusException +import io.grpc.stub.StreamObserver +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.currentTimestamp +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.Status +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementOutput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.slf4j.LoggerFactory +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.stereotype.Service +import java.io.File + +@Service +open class BluePrintManagementGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val bluePrintCatalogService: BluePrintCatalogService) + : BluePrintManagementServiceGrpc.BluePrintManagementServiceImplBase() { + + private val log = LoggerFactory.getLogger(BluePrintManagementGRPCHandler::class.java) + + @PreAuthorize("hasRole('USER')") + override fun uploadBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver) { + val blueprintName = request.blueprintName + val blueprintVersion = request.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + log.info("request(${request.commonHeader.requestId}): Received upload $blueprint") + + val blueprintArchivedFilePath = "${bluePrintCoreConfiguration.archivePath}/$blueprintName/$blueprintVersion/$blueprintName.zip" + try { + val blueprintArchivedFile = File(blueprintArchivedFilePath) + + saveToDisk(request, blueprintArchivedFile) + val blueprintId = bluePrintCatalogService.saveToDatabase(blueprintArchivedFile) + + File("${bluePrintCoreConfiguration.archivePath}/$blueprintName").deleteRecursively() + + responseObserver.onNext(successStatus("Successfully uploaded $blueprint with id($blueprintId)", request.commonHeader)) + responseObserver.onCompleted() + } catch (e: Exception) { + failStatus("request(${request.commonHeader.requestId}): Failed to upload $blueprint at path $blueprintArchivedFilePath", e) + } + } + + @PreAuthorize("hasRole('USER')") + override fun removeBlueprint(request: BluePrintManagementInput, responseObserver: StreamObserver) { + val blueprintName = request.blueprintName + val blueprintVersion = request.blueprintVersion + val blueprint = "blueprint $blueprintName:$blueprintVersion" + + log.info("request(${request.commonHeader.requestId}): Received delete $blueprint") + + try { + bluePrintCatalogService.deleteFromDatabase(blueprintName, blueprintVersion) + responseObserver.onNext(successStatus("Successfully deleted $blueprint", request.commonHeader)) + responseObserver.onCompleted() + } catch (e: Exception) { + failStatus("request(${request.commonHeader.requestId}): Failed to delete $blueprint", e) + } + } + + private fun saveToDisk(request: BluePrintManagementInput, blueprintDir: File) { + log.info("request(${request.commonHeader.requestId}): Writing CBA File under :${blueprintDir.absolutePath}") + if (blueprintDir.exists()) { + log.info("request(${request.commonHeader.requestId}): Re-creating blueprint directory(${blueprintDir.absolutePath})") + //FileUtils.deleteDirectory(blueprintDir.parentFile) + blueprintDir.parentFile.deleteRecursively() + } + blueprintDir.parentFile.mkdirs() + //FileUtils.forceMkdir(blueprintDir.parentFile) + blueprintDir.writeBytes(request.fileChunk.chunk.toByteArray()).apply { + log.info("request(${request.commonHeader.requestId}): CBA file(${blueprintDir.absolutePath} written successfully") + } + + } + + private fun successStatus(message: String, header: CommonHeader): BluePrintManagementOutput = + BluePrintManagementOutput.newBuilder() + .setCommonHeader(header) + .setStatus(Status.newBuilder() + .setTimestamp(currentTimestamp()) + .setMessage(message) + .setCode(200) + .build()) + .build() + + private fun failStatus(message: String, e: Exception): StatusException { + log.error(message, e) + return io.grpc.Status.INTERNAL + .withDescription(message) + .withCause(e) + .asException() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt new file mode 100644 index 000000000..eb450d73b --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandler.kt @@ -0,0 +1,64 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.toJava +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput +import org.slf4j.LoggerFactory +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.stereotype.Service + +@Service +open class BluePrintProcessingGRPCHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val executionServiceHandler: ExecutionServiceHandler) + : BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase() { + private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandler::class.java) + + @PreAuthorize("hasRole('USER')") + override fun process( + responseObserver: StreamObserver): StreamObserver { + + return object : StreamObserver { + override fun onNext(executionServiceInput: ExecutionServiceInput) { + try { + runBlocking { + executionServiceHandler.process(executionServiceInput.toJava(), responseObserver) + } + } catch (e: Exception) { + onError(e) + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + responseObserver.onError(io.grpc.Status.INTERNAL + .withDescription(error.message) + .asException()) + } + + override fun onCompleted() { + log.info("Completed") + } + } + } +} \ 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 new file mode 100644 index 000000000..1039d5cd2 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceController.kt @@ -0,0 +1,67 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import io.swagger.annotations.ApiOperation +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ACTION_MODE_ASYNC +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.MediaType +import org.springframework.http.codec.multipart.FilePart +import org.springframework.security.access.prepost.PreAuthorize +import org.springframework.web.bind.annotation.* +import reactor.core.publisher.Mono + +@RestController +@RequestMapping("/api/v1/execution-service") +open class ExecutionServiceController { + + @Autowired + lateinit var executionServiceHandler: ExecutionServiceHandler + + @RequestMapping(path = ["/ping"], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]) + @ResponseBody + fun ping(): String = runBlocking { + "Success" + } + + @PostMapping(path = ["/upload"], consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]) + @ApiOperation(value = "Upload CBA", notes = "Takes a File and load it in the runtime database") + @ResponseBody + @PreAuthorize("hasRole('USER')") + fun upload(@RequestPart("file") parts: Mono): Mono { + return parts + .filter { it is FilePart } + .ofType(FilePart::class.java) + .flatMap(executionServiceHandler::upload) + } + + @RequestMapping(path = ["/process"], method = [RequestMethod.POST], produces = [MediaType.APPLICATION_JSON_VALUE]) + @ApiOperation(value = "Resolve Resource Mappings", + notes = "Takes the blueprint information and process as per the payload") + @ResponseBody + @PreAuthorize("hasRole('USER')") + fun process(@RequestBody executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput = runBlocking { + if (executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC) { + throw IllegalStateException("Can't process async request through the REST endpoint. Use gRPC for async processing.") + } + executionServiceHandler.doProcess(executionServiceInput) + } +} 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 new file mode 100644 index 000000000..f3af254be --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandler.kt @@ -0,0 +1,142 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import io.grpc.stub.StreamObserver +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.launch +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +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.selfservice.api.utils.saveCBAFile +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils.toProto +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintFileUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.slf4j.LoggerFactory +import org.springframework.http.codec.multipart.FilePart +import org.springframework.stereotype.Service +import reactor.core.publisher.Mono +import java.util.stream.Collectors + +@Service +class ExecutionServiceHandler(private val bluePrintCoreConfiguration: BluePrintCoreConfiguration, + private val bluePrintCatalogService: BluePrintCatalogService, + private val bluePrintWorkflowExecutionService + : BluePrintWorkflowExecutionService) { + + private val log = LoggerFactory.getLogger(ExecutionServiceHandler::class.toString()) + + fun upload(filePart: FilePart): Mono { + try { + val archivedPath = BluePrintFileUtils.getCbaStorageDirectory(bluePrintCoreConfiguration.archivePath) + val cbaPath = saveCBAFile(filePart, archivedPath) + bluePrintCatalogService.saveToDatabase(cbaPath.toFile()).let { + return Mono.just("{\"status\": \"Successfully uploaded blueprint with id($it)\"}") + } + } catch (e: Exception) { + return Mono.error(BluePrintException("Error uploading the CBA file.", e)) + } + } + + suspend fun process(executionServiceInput: ExecutionServiceInput, + responseObserver: StreamObserver) { + when { + executionServiceInput.actionIdentifiers.mode == ACTION_MODE_ASYNC -> { + GlobalScope.launch(Dispatchers.Default) { + val executionServiceOutput = doProcess(executionServiceInput) + responseObserver.onNext(executionServiceOutput.toProto()) + responseObserver.onCompleted() + } + responseObserver.onNext(response(executionServiceInput).toProto()) + } + executionServiceInput.actionIdentifiers.mode == ACTION_MODE_SYNC -> { + val executionServiceOutput = doProcess(executionServiceInput) + responseObserver.onNext(executionServiceOutput.toProto()) + responseObserver.onCompleted() + } + else -> responseObserver.onNext(response(executionServiceInput, + "Failed to process request, 'actionIdentifiers.mode' not specified. Valid value are: 'sync' or 'async'.", + true).toProto()); + } + } + + suspend fun doProcess(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { + val requestId = executionServiceInput.commonHeader.requestId + log.info("processing request id $requestId") + + val actionIdentifiers = executionServiceInput.actionIdentifiers + + val blueprintName = actionIdentifiers.blueprintName + val blueprintVersion = actionIdentifiers.blueprintVersion + + val basePath = bluePrintCatalogService.getFromDatabase(blueprintName, blueprintVersion) + log.info("blueprint base path $basePath") + + val blueprintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime(requestId, basePath.toString()) + + val output = bluePrintWorkflowExecutionService.executeBluePrintWorkflow(blueprintRuntimeService, + executionServiceInput, hashMapOf()) + + val errors = blueprintRuntimeService.getBluePrintError().errors + if (errors.isNotEmpty()) { + val errorMessage = errors.stream().map { it.toString() }.collect(Collectors.joining(", ")) + setErrorStatus(errorMessage, output.status) + } + + return output + } + + private fun setErrorStatus(errorMessage: String, status: Status) { + status.errorMessage = errorMessage + status.eventType = EventType.EVENT_COMPONENT_FAILURE.name + status.code = 500 + status.message = BluePrintConstants.STATUS_FAILURE + } + + private fun response(executionServiceInput: ExecutionServiceInput, errorMessage: String = "", + failure: Boolean = false): ExecutionServiceOutput { + val executionServiceOutput = ExecutionServiceOutput() + executionServiceOutput.commonHeader = executionServiceInput.commonHeader + executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + executionServiceOutput.payload = JsonNodeFactory.instance.objectNode() + + val status = Status() + if (failure) { + setErrorStatus(errorMessage, status) + } else { + status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name + status.code = 200 + status.message = BluePrintConstants.STATUS_PROCESSING + } + + executionServiceOutput.status = status + + return executionServiceOutput + } + +} \ 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/utils/BluePrintMappings.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt new file mode 100644 index 000000000..b5984d738 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappings.kt @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.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.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.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 + +fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers.toProto(): ActionIdentifiers { + val actionIdentifier = ActionIdentifiers.newBuilder() + actionIdentifier.actionName = this.actionName + actionIdentifier.blueprintName = this.blueprintName + actionIdentifier.blueprintVersion = this.blueprintVersion + actionIdentifier.mode = this.mode + return actionIdentifier.build() +} + +fun ActionIdentifiers.toJava(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers { + val actionIdentifier = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers() + actionIdentifier.actionName = this.actionName + actionIdentifier.blueprintName = this.blueprintName + actionIdentifier.blueprintVersion = this.blueprintVersion + actionIdentifier.mode = this.mode + return actionIdentifier +} + +// COMMON HEADER + +fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader.toProto(): CommonHeader { + val commonHeader = CommonHeader.newBuilder() + commonHeader.originatorId = this.originatorId + commonHeader.requestId = this.requestId + commonHeader.subRequestId = this.subRequestId + commonHeader.timestamp = this.timestamp.toString() + commonHeader.flag = this.flags?.toProto() + return commonHeader.build() +} + +fun CommonHeader.toJava(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader { + val commonHeader = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader() + commonHeader.originatorId = this.originatorId + commonHeader.requestId = this.requestId + commonHeader.subRequestId = this.subRequestId + commonHeader.timestamp = if (!Strings.isNullOrEmpty(this.timestamp)) { + formatter.parse(this.timestamp) + } else { + Date() + } + commonHeader.flags = this.flag?.toJava() + return commonHeader +} + +// FLAG + +fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags.toProto(): Flag { + val flag = Flag.newBuilder() + flag.isForce = this.isForce + flag.ttl = this.ttl + return flag.build() +} + +fun Flag.toJava(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags { + val flag = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags() + flag.isForce = this.isForce + flag.ttl = this.ttl + return flag +} + +// STATUS + +fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status.toProto(): Status { + val status = Status.newBuilder() + status.code = this.code + status.errorMessage = this.errorMessage ?: "" + status.message = this.message + status.timestamp = this.timestamp.toString() + status.eventType = EventType.valueOf(this.eventType) + return status.build() +} + +// EXECUTION INPUT + +fun ExecutionServiceInput.toJava(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput { + val executionServiceInput = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput() + executionServiceInput.actionIdentifiers = this.actionIdentifiers.toJava() + executionServiceInput.commonHeader = this.commonHeader.toJava() + executionServiceInput.payload = JacksonUtils.jsonNode(JsonFormat.printer().print(this.payload)) as ObjectNode + return executionServiceInput +} + +// EXECUTION OUPUT + +fun org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput.toProto(): ExecutionServiceOutput { + val executionServiceOuput = ExecutionServiceOutput.newBuilder() + executionServiceOuput.actionIdentifiers = this.actionIdentifiers.toProto() + executionServiceOuput.commonHeader = this.commonHeader.toProto() + executionServiceOuput.status = this.status.toProto() + val struct = Struct.newBuilder() + JsonFormat.parser().merge(JacksonUtils.getJson(this.payload), struct) + executionServiceOuput.payload = struct.build() + return executionServiceOuput.build() +} \ 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/utils/Utils.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt new file mode 100644 index 000000000..32be3e0a0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/Utils.kt @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils + +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException +import org.springframework.http.codec.multipart.FilePart +import org.springframework.util.StringUtils +import java.io.File +import java.io.IOException +import java.nio.file.Path +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.* + + +fun currentTimestamp(): String { + val now = LocalDateTime.now(ZoneId.systemDefault()) + val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + return formatter.format(now) +} + + +@Throws(BluePrintException::class, IOException::class) +fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Path { + + val fileName = StringUtils.cleanPath(filePart.filename()) + + if (StringUtils.getFilenameExtension(fileName) != "zip") { + throw BluePrintException("Invalid file extension required ZIP") + } + + val changedFileName = UUID.randomUUID().toString() + ".zip" + + val targetLocation = targetDirectory.resolve(changedFileName) + + val file = File(targetLocation.toString()) + if (file.exists()) { + file.delete() + } + file.createNewFile() + + filePart.transferTo(file) + + return targetLocation +} \ 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 new file mode 100644 index 000000000..707439ddb --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorService.kt @@ -0,0 +1,27 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation + +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintTypeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.validation.BluePrintDesignTimeValidatorService +import org.onap.ccsdk.cds.controllerblueprints.validation.extension.ResourceDefinitionValidator +import org.springframework.stereotype.Service + +@Service +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/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt deleted file mode 100644 index 264e2aea6..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * 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.apps.blueprintsprocessor.selfservice.api - -import com.google.protobuf.ByteString -import io.grpc.testing.GrpcServerRule -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementInput -import org.onap.ccsdk.apps.controllerblueprints.management.api.BluePrintManagementServiceGrpc -import org.onap.ccsdk.apps.controllerblueprints.management.api.FileChunk -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.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import java.io.File -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@EnableAutoConfiguration -@DirtiesContext -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BluePrintManagementGRPCHandlerTest { - - @get:Rule - val grpcServerRule = GrpcServerRule().directExecutor() - - @Autowired - lateinit var bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler - - @BeforeTest - fun init() { - // Create a server, add service, start, and register for automatic graceful shutdown. - grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) - } - - @AfterTest - fun cleanDir() { - //TODO It's giving fluctuating results, need to look for another way to cleanup - // works sometimes otherwise results IO Exception - // Most probably bufferReader stream is not getting closed when cleanDir is getting invoked - File("./target/blueprints").deleteRecursively() - } - - @Test - fun `test upload blueprint`() { - val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_upload" - val req = createInputRequest(id) - val output = blockingStub.uploadBlueprint(req) - - assertEquals(200, output.status.code) - assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) - assertEquals(id, output.commonHeader.requestId) - } - - @Test - fun `test delete blueprint`() { - val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) - val id = "123_delete" - val req = createInputRequest(id) - - var output = blockingStub.uploadBlueprint(req) - assertEquals(200, output.status.code) - assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) - assertEquals(id, output.commonHeader.requestId) - - output = blockingStub.removeBlueprint(req) - assertEquals(200, output.status.code) - } - - private fun createInputRequest(id: String): BluePrintManagementInput { - val file = File("./src/test/resources/test-cba.zip") - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - - val commonHeader = CommonHeader - .newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId(id) - .setSubRequestId("1234-56").build() - - val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) - .build() - - return BluePrintManagementInput.newBuilder() - .setCommonHeader(commonHeader) - .setBlueprintName("sample") - .setBlueprintVersion("1.0.0") - .setFileChunk(fileChunk) - .build() - } -} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt deleted file mode 100644 index 01984b21d..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * 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.apps.blueprintsprocessor.selfservice.api - - -import com.google.protobuf.util.JsonFormat -import io.grpc.stub.StreamObserver -import io.grpc.testing.GrpcServerRule -import org.junit.Assert -import org.junit.Ignore -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput -import org.onap.ccsdk.apps.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.TestPropertySource -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.BeforeTest - -@Ignore -@RunWith(SpringRunner::class) -@DirtiesContext -@EnableAutoConfiguration -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class BluePrintProcessingGRPCHandlerTest { - private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java) - - @get:Rule - val grpcServerRule = GrpcServerRule().directExecutor() - - @Autowired - lateinit var bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler - - lateinit var requestObs: StreamObserver - - @BeforeTest - fun init() { - grpcServerRule.serviceRegistry.addService(bluePrintProcessingGRPCHandler) - - val blockingStub = BluePrintProcessingServiceGrpc.newStub(grpcServerRule.channel) - - requestObs = blockingStub.process(object : StreamObserver { - override fun onNext(executionServiceOuput: ExecutionServiceOutput) { - log.debug("onNext {}", executionServiceOuput) - if ("1234".equals(executionServiceOuput.commonHeader.requestId)) { - Assert.assertEquals("Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", executionServiceOuput.status.errorMessage) - } - } - - override fun onError(error: Throwable) { - log.debug("Fail to process message", error) - Assert.assertEquals("INTERNAL: Could not find blueprint : from database", error.message) - } - - override fun onCompleted() { - log.info("Done") - } - }) - } - - @Test - fun testSelfServiceGRPCHandler() { - val commonHeader = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId("1234") - .setSubRequestId("1234-56").build() - - val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") - val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder - JsonFormat.parser().merge(jsonContent, payloadBuilder) - - val input = ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader) - .setPayload(payloadBuilder.build()) - .build() - - requestObs.onNext(input) - - val commonHeader2 = CommonHeader.newBuilder() - .setTimestamp("2012-04-23T18:25:43.511Z") - .setOriginatorId("System") - .setRequestId("2345") - .setSubRequestId("1234-56").build() - - val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build() - - val input2 = ExecutionServiceInput.newBuilder() - .setCommonHeader(commonHeader2) - .setActionIdentifiers(actionIdentifier) - .setPayload(payloadBuilder.build()) - .build() - - requestObs.onNext(input2) - - requestObs.onCompleted() - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt deleted file mode 100644 index b730472e8..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * 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.apps.blueprintsprocessor.selfservice.api - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.BluePrintCoreConfiguration -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintCatalogService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.security.SecurityProperties -import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest -import org.springframework.context.annotation.ComponentScan -import org.springframework.core.io.ByteArrayResource -import org.springframework.http.client.MultipartBodyBuilder -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.springframework.web.reactive.function.BodyInserters -import java.nio.file.Files -import java.nio.file.Paths -import kotlin.test.assertTrue - -@RunWith(SpringRunner::class) -@WebFluxTest -@ContextConfiguration(classes = [ExecutionServiceHandler::class, BluePrintCoreConfiguration::class, BluePrintCatalogService::class, SecurityProperties::class]) -@ComponentScan(basePackages = ["org.onap.ccsdk.apps.blueprintsprocessor", "org.onap.ccsdk.apps.controllerblueprints"]) -@TestPropertySource(locations = ["classpath:application-test.properties"]) -class ExecutionServiceHandlerTest { - - @Autowired - lateinit var blueprintCatalog: BluePrintCatalogService - @Autowired - lateinit var webTestClient: WebTestClient - - - @Test - fun `test rest upload blueprint`() { - val file = Paths.get("./src/test/resources/test-cba.zip").toFile() - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - - val body = MultipartBodyBuilder().apply { - part("file", object : ByteArrayResource(Files.readAllBytes(Paths.get("./src/test/resources/test-cba.zip"))) { - override fun getFilename(): String { - return "test-cba.zip" - } - }) - }.build() - - webTestClient - .post() - .uri("/api/v1/execution-service/upload") - .body(BodyInserters.fromMultipartData(body)) - .exchange() - .expectStatus().isOk - } - - @Test - fun `test rest process`() { - val file = Paths.get("./src/test/resources/test-cba.zip").toFile() - assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") - blueprintCatalog.saveToDatabase(file) - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/default-input.json", ExecutionServiceInput::class.java)!! - webTestClient - .post() - .uri("/api/v1/execution-service/process") - .body(BodyInserters.fromObject(executionServiceInput)) - .exchange() - .expectStatus().isOk - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt deleted file mode 100644 index 19c624bc0..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/mock/Mock.kt +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 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.apps.blueprintsprocessor.selfservice.api.mock - -import io.mockk.mockk -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive -import org.slf4j.LoggerFactory -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration - -@Configuration -open class MockComponentConfiguration { - - @Bean(name = ["component-resource-assignment", "component-netconf-executor", "component-jython-executor"]) - open fun createComponentFunction(): AbstractComponentFunction { - return MockComponentFunction() - } -} - -class MockComponentFunction : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) - - override fun process(executionRequest: ExecutionServiceInput) { - log.info("Processing component : $operationInputs") - - bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, - "assignment-params", "params".asJsonPrimitive()) - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recovering component..") - } -} - -open class MockResourceSource { - @Bean(name = [ - "rr-processor-source-input", - "rr-processor-source-default", - "rr-processor-source-primary-db", - "rr-processor-source-rest"]) - open fun sourceInstance(): ResourceAssignmentProcessor { - return mockk() - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt deleted file mode 100644 index 770e4a9b3..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt +++ /dev/null @@ -1,132 +0,0 @@ -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.utils - -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Flags -import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers -import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader -import org.onap.ccsdk.apps.controllerblueprints.common.api.EventType -import org.onap.ccsdk.apps.controllerblueprints.common.api.Flag -import org.springframework.test.context.junit4.SpringRunner -import java.text.SimpleDateFormat - -@RunWith(SpringRunner::class) -class BluePrintMappingsTest { - - val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") - val dateString = "2019-01-16T18:25:43.511Z" - val dateForTest = formatter.parse(dateString) - - val flag = Flag.newBuilder().setIsForce(false).setTtl(1).build() - - fun createFlag(): Flags { - val flag = Flags() - flag.isForce = false - flag.ttl = 1 - return flag - } - - @Test - fun flagToJavaTest() { - val flag2 = flag.toJava() - - Assert.assertEquals(flag.isForce, flag2.isForce) - Assert.assertEquals(flag.ttl, flag2.ttl) - } - - @Test - fun flagToProtoTest() { - val flag = createFlag() - val flag2 = flag.toProto() - - Assert.assertEquals(flag.isForce, flag2.isForce) - Assert.assertEquals(flag.ttl, flag2.ttl) - } - - fun createStatus(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status { - val status = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status() - status.code = 400 - status.errorMessage = "Concurrent modification exception" - status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name - status.message = "Error uploading data" - status.timestamp = dateForTest - return status - } - - @Test - fun statusToProtoTest() { - val status = createStatus() - val status2 = status.toProto() - - Assert.assertEquals(status.code, status2.code) - Assert.assertEquals(status.errorMessage, status2.errorMessage) - Assert.assertEquals(status.eventType, status2.eventType.name) - Assert.assertEquals(status.message, status2.message) - Assert.assertEquals(status.timestamp.toString(), status2.timestamp) - } - - @Test - fun commonHeaderToJavaTest() { - val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build() - - val commonHeader = CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString).setFlag(flag).build() - val commonHeader2 = commonHeader.toJava() - - Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) - Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) - Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) - Assert.assertEquals(commonHeader.timestamp, formatter.format(commonHeader2.timestamp)) - } - - fun createCommonHeader(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader { - val commonHeader = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.CommonHeader() - commonHeader.flags = createFlag() - commonHeader.originatorId = "1234" - commonHeader.requestId = "2345" - commonHeader.subRequestId = "0123" - commonHeader.timestamp = dateForTest - return commonHeader - } - - @Test - fun commonHeaderToProtoTest() { - val commonHeader = createCommonHeader() - val commonHeader2 = commonHeader.toProto() - Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) - Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) - Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) - Assert.assertEquals(commonHeader.timestamp.toString(), commonHeader2.timestamp) - } - - @Test - fun actionIdentifierToJavaTest() { - val actionIdentifiers = ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0").setMode("Execution").build() - val actionIdentifiers2 = actionIdentifiers.toJava() - - Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) - Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) - Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) - Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) - } - - fun createActionIdentifier(): org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers { - val ac = org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ActionIdentifiers() - ac.mode = "mode" - ac.blueprintVersion = "version" - ac.blueprintName = "name" - ac.actionName = "action" - return ac - } - - @Test - fun actionIdentifierToProtoTest() { - val actionIdentifiers = createActionIdentifier() - val actionIdentifiers2 = actionIdentifiers.toProto() - - Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) - Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) - Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) - Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt deleted file mode 100644 index 1cafead7f..000000000 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.validation - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.selfservice.api.mock.MockResourceSource -import org.onap.ccsdk.apps.controllerblueprints.validation.BluePrintValidationConfiguration -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertNotNull - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [BluePrintRuntimeValidatorService::class, - BluePrintValidationConfiguration::class, MockResourceSource::class]) -class BluePrintRuntimeValidatorServiceTest { - - @Autowired - lateinit var bluePrintRuntimeValidatorService: BluePrintRuntimeValidatorService - - @Test - fun testBlueprintRuntimeValidation() { - 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/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt new file mode 100644 index 000000000..a03ad9e47 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintManagementGRPCHandlerTest.kt @@ -0,0 +1,116 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import com.google.protobuf.ByteString +import io.grpc.testing.GrpcServerRule +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementInput +import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintManagementServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk +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.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +@RunWith(SpringRunner::class) +@EnableAutoConfiguration +@DirtiesContext +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintManagementGRPCHandlerTest { + + @get:Rule + val grpcServerRule = GrpcServerRule().directExecutor() + + @Autowired + lateinit var bluePrintManagementGRPCHandler: BluePrintManagementGRPCHandler + + @BeforeTest + fun init() { + // Create a server, add service, start, and register for automatic graceful shutdown. + grpcServerRule.serviceRegistry.addService(bluePrintManagementGRPCHandler) + } + + @AfterTest + fun cleanDir() { + //TODO It's giving fluctuating results, need to look for another way to cleanup + // works sometimes otherwise results IO Exception + // Most probably bufferReader stream is not getting closed when cleanDir is getting invoked + File("./target/blueprints").deleteRecursively() + } + + @Test + fun `test upload blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_upload" + val req = createInputRequest(id) + val output = blockingStub.uploadBlueprint(req) + + assertEquals(200, output.status.code) + assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) + assertEquals(id, output.commonHeader.requestId) + } + + @Test + fun `test delete blueprint`() { + val blockingStub = BluePrintManagementServiceGrpc.newBlockingStub(grpcServerRule.channel) + val id = "123_delete" + val req = createInputRequest(id) + + var output = blockingStub.uploadBlueprint(req) + assertEquals(200, output.status.code) + assertTrue(output.status.message.contains("Successfully uploaded blueprint sample:1.0.0 with id(")) + assertEquals(id, output.commonHeader.requestId) + + output = blockingStub.removeBlueprint(req) + assertEquals(200, output.status.code) + } + + private fun createInputRequest(id: String): BluePrintManagementInput { + val file = File("./src/test/resources/test-cba.zip") + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + val commonHeader = CommonHeader + .newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId(id) + .setSubRequestId("1234-56").build() + + val fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(file.inputStream().readBytes())) + .build() + + return BluePrintManagementInput.newBuilder() + .setCommonHeader(commonHeader) + .setBlueprintName("sample") + .setBlueprintVersion("1.0.0") + .setFileChunk(fileChunk) + .build() + } +} diff --git a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt new file mode 100644 index 000000000..f8b972e64 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/BluePrintProcessingGRPCHandlerTest.kt @@ -0,0 +1,124 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + + +import com.google.protobuf.util.JsonFormat +import io.grpc.stub.StreamObserver +import io.grpc.testing.GrpcServerRule +import org.junit.Assert +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.EnableAutoConfiguration +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.annotation.DirtiesContext +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.BeforeTest + +@Ignore +@RunWith(SpringRunner::class) +@DirtiesContext +@EnableAutoConfiguration +@ComponentScan(basePackages = ["org.onap.ccsdk.cds.blueprintsprocessor", "org.onap.ccsdk.cds.controllerblueprints"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class BluePrintProcessingGRPCHandlerTest { + private val log = LoggerFactory.getLogger(BluePrintProcessingGRPCHandlerTest::class.java) + + @get:Rule + val grpcServerRule = GrpcServerRule().directExecutor() + + @Autowired + lateinit var bluePrintProcessingGRPCHandler: BluePrintProcessingGRPCHandler + + lateinit var requestObs: StreamObserver + + @BeforeTest + fun init() { + grpcServerRule.serviceRegistry.addService(bluePrintProcessingGRPCHandler) + + val blockingStub = BluePrintProcessingServiceGrpc.newStub(grpcServerRule.channel) + + requestObs = blockingStub.process(object : StreamObserver { + override fun onNext(executionServiceOuput: ExecutionServiceOutput) { + log.debug("onNext {}", executionServiceOuput) + if ("1234".equals(executionServiceOuput.commonHeader.requestId)) { + Assert.assertEquals("Failed to process request, \'actionIdentifiers.mode\' not specified. Valid value are: \'sync\' or \'async\'.", executionServiceOuput.status.errorMessage) + } + } + + override fun onError(error: Throwable) { + log.debug("Fail to process message", error) + Assert.assertEquals("INTERNAL: Could not find blueprint : from database", error.message) + } + + override fun onCompleted() { + log.info("Done") + } + }) + } + + @Test + fun testSelfServiceGRPCHandler() { + val commonHeader = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("1234") + .setSubRequestId("1234-56").build() + + val jsonContent = JacksonUtils.getClassPathFileContent("execution-input/sample-payload.json") + val payloadBuilder = ExecutionServiceInput.newBuilder().payloadBuilder + JsonFormat.parser().merge(jsonContent, payloadBuilder) + + val input = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input) + + val commonHeader2 = CommonHeader.newBuilder() + .setTimestamp("2012-04-23T18:25:43.511Z") + .setOriginatorId("System") + .setRequestId("2345") + .setSubRequestId("1234-56").build() + + val actionIdentifier = ActionIdentifiers.newBuilder().setMode("sync").build() + + val input2 = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader2) + .setActionIdentifiers(actionIdentifier) + .setPayload(payloadBuilder.build()) + .build() + + requestObs.onNext(input2) + + requestObs.onCompleted() + } + +} \ 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 new file mode 100644 index 000000000..b131fb7d1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/ExecutionServiceHandlerTest.kt @@ -0,0 +1,89 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.BluePrintCoreConfiguration +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.boot.autoconfigure.security.SecurityProperties +import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest +import org.springframework.context.annotation.ComponentScan +import org.springframework.core.io.ByteArrayResource +import org.springframework.http.client.MultipartBodyBuilder +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.springframework.web.reactive.function.BodyInserters +import java.nio.file.Files +import java.nio.file.Paths +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"]) +@TestPropertySource(locations = ["classpath:application-test.properties"]) +class ExecutionServiceHandlerTest { + + @Autowired + lateinit var blueprintCatalog: BluePrintCatalogService + @Autowired + lateinit var webTestClient: WebTestClient + + + @Test + fun `test rest upload blueprint`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + + val body = MultipartBodyBuilder().apply { + part("file", object : ByteArrayResource(Files.readAllBytes(Paths.get("./src/test/resources/test-cba.zip"))) { + override fun getFilename(): String { + return "test-cba.zip" + } + }) + }.build() + + webTestClient + .post() + .uri("/api/v1/execution-service/upload") + .body(BodyInserters.fromMultipartData(body)) + .exchange() + .expectStatus().isOk + } + + @Test + fun `test rest process`() { + val file = Paths.get("./src/test/resources/test-cba.zip").toFile() + assertTrue(file.exists(), "couldnt get file ${file.absolutePath}") + blueprintCatalog.saveToDatabase(file) + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/default-input.json", ExecutionServiceInput::class.java)!! + webTestClient + .post() + .uri("/api/v1/execution-service/process") + .body(BodyInserters.fromObject(executionServiceInput)) + .exchange() + .expectStatus().isOk + } +} \ 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/mock/Mock.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt new file mode 100644 index 000000000..85e289ccc --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/mock/Mock.kt @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.mock + +import io.mockk.mockk +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.slf4j.LoggerFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +@Configuration +open class MockComponentConfiguration { + + @Bean(name = ["component-resource-assignment", "component-netconf-executor", "component-jython-executor"]) + open fun createComponentFunction(): AbstractComponentFunction { + return MockComponentFunction() + } +} + +class MockComponentFunction : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing component : $operationInputs") + + bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, + "assignment-params", "params".asJsonPrimitive()) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + log.info("Recovering component..") + } +} + +open class MockResourceSource { + @Bean(name = [ + "rr-processor-source-input", + "rr-processor-source-default", + "rr-processor-source-primary-db", + "rr-processor-source-rest"]) + open fun sourceInstance(): ResourceAssignmentProcessor { + return mockk() + } + +} \ 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/utils/BluePrintMappingTests.kt b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt new file mode 100644 index 000000000..230d1fde1 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/utils/BluePrintMappingTests.kt @@ -0,0 +1,132 @@ +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils + +import org.junit.Assert +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Flags +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.common.api.Flag +import org.springframework.test.context.junit4.SpringRunner +import java.text.SimpleDateFormat + +@RunWith(SpringRunner::class) +class BluePrintMappingsTest { + + val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") + val dateString = "2019-01-16T18:25:43.511Z" + val dateForTest = formatter.parse(dateString) + + val flag = Flag.newBuilder().setIsForce(false).setTtl(1).build() + + fun createFlag(): Flags { + val flag = Flags() + flag.isForce = false + flag.ttl = 1 + return flag + } + + @Test + fun flagToJavaTest() { + val flag2 = flag.toJava() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + @Test + fun flagToProtoTest() { + val flag = createFlag() + val flag2 = flag.toProto() + + Assert.assertEquals(flag.isForce, flag2.isForce) + Assert.assertEquals(flag.ttl, flag2.ttl) + } + + fun createStatus(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status { + val status = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status() + status.code = 400 + status.errorMessage = "Concurrent modification exception" + status.eventType = EventType.EVENT_COMPONENT_PROCESSING.name + status.message = "Error uploading data" + status.timestamp = dateForTest + return status + } + + @Test + fun statusToProtoTest() { + val status = createStatus() + val status2 = status.toProto() + + Assert.assertEquals(status.code, status2.code) + Assert.assertEquals(status.errorMessage, status2.errorMessage) + Assert.assertEquals(status.eventType, status2.eventType.name) + Assert.assertEquals(status.message, status2.message) + Assert.assertEquals(status.timestamp.toString(), status2.timestamp) + } + + @Test + fun commonHeaderToJavaTest() { + val flag = Flag.newBuilder().setIsForce(true).setTtl(2).build() + + val commonHeader = CommonHeader.newBuilder().setOriginatorId("Origin").setRequestId("requestID").setSubRequestId("subRequestID").setTimestamp(dateString).setFlag(flag).build() + val commonHeader2 = commonHeader.toJava() + + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp, formatter.format(commonHeader2.timestamp)) + } + + fun createCommonHeader(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader { + val commonHeader = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.CommonHeader() + commonHeader.flags = createFlag() + commonHeader.originatorId = "1234" + commonHeader.requestId = "2345" + commonHeader.subRequestId = "0123" + commonHeader.timestamp = dateForTest + return commonHeader + } + + @Test + fun commonHeaderToProtoTest() { + val commonHeader = createCommonHeader() + val commonHeader2 = commonHeader.toProto() + Assert.assertEquals(commonHeader.originatorId, commonHeader2.originatorId) + Assert.assertEquals(commonHeader.requestId, commonHeader2.requestId) + Assert.assertEquals(commonHeader.subRequestId, commonHeader2.subRequestId) + Assert.assertEquals(commonHeader.timestamp.toString(), commonHeader2.timestamp) + } + + @Test + fun actionIdentifierToJavaTest() { + val actionIdentifiers = ActionIdentifiers.newBuilder().setActionName("Process Action").setBlueprintName("BlueprintName").setBlueprintVersion("3.0").setMode("Execution").build() + val actionIdentifiers2 = actionIdentifiers.toJava() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } + + fun createActionIdentifier(): org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers { + val ac = org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ActionIdentifiers() + ac.mode = "mode" + ac.blueprintVersion = "version" + ac.blueprintName = "name" + ac.actionName = "action" + return ac + } + + @Test + fun actionIdentifierToProtoTest() { + val actionIdentifiers = createActionIdentifier() + val actionIdentifiers2 = actionIdentifiers.toProto() + + Assert.assertEquals(actionIdentifiers.actionName, actionIdentifiers2.actionName) + Assert.assertEquals(actionIdentifiers.blueprintName, actionIdentifiers2.blueprintName) + Assert.assertEquals(actionIdentifiers.blueprintVersion, actionIdentifiers2.blueprintVersion) + Assert.assertEquals(actionIdentifiers.mode, actionIdentifiers2.mode) + } +} \ 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 new file mode 100644 index 000000000..08da9dc28 --- /dev/null +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/selfservice/api/validation/BluePrintRuntimeValidatorServiceTest.kt @@ -0,0 +1,44 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.validation + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.mock.MockResourceSource +import org.onap.ccsdk.cds.controllerblueprints.validation.BluePrintValidationConfiguration +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertNotNull + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [BluePrintRuntimeValidatorService::class, + BluePrintValidationConfiguration::class, MockResourceSource::class]) +class BluePrintRuntimeValidatorServiceTest { + + @Autowired + lateinit var bluePrintRuntimeValidatorService: BluePrintRuntimeValidatorService + + @Test + fun testBlueprintRuntimeValidation() { + 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/inbounds/selfservice-api/src/test/resources/logback.xml b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/logback.xml index a816a06c5..0c8d93bf0 100644 --- a/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/logback.xml +++ b/ms/blueprintsprocessor/modules/inbounds/selfservice-api/src/test/resources/logback.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/modules/outbounds/pom.xml b/ms/blueprintsprocessor/modules/outbounds/pom.xml index 3fb7e382b..d406462db 100644 --- a/ms/blueprintsprocessor/modules/outbounds/pom.xml +++ b/ms/blueprintsprocessor/modules/outbounds/pom.xml @@ -17,7 +17,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor modules 0.4.2-SNAPSHOT diff --git a/ms/blueprintsprocessor/modules/pom.xml b/ms/blueprintsprocessor/modules/pom.xml index 26500f50d..c67c97882 100644 --- a/ms/blueprintsprocessor/modules/pom.xml +++ b/ms/blueprintsprocessor/modules/pom.xml @@ -19,7 +19,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor parent 0.4.2-SNAPSHOT ../parent diff --git a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml index 913ce4671..9ce5292e8 100644 --- a/ms/blueprintsprocessor/modules/services/execution-service/pom.xml +++ b/ms/blueprintsprocessor/modules/services/execution-service/pom.xml @@ -18,7 +18,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor services 0.4.2-SNAPSHOT @@ -34,31 +34,31 @@ jython-standalone - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-scripts - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor processor-core - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor db-lib - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor rest-lib - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints resource-dict - org.onap.ccsdk.apps.components + org.onap.ccsdk.cds.components proto-definition diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt deleted file mode 100644 index 4c381706a..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractComponentFunction.kt +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution - - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.JsonNodeFactory -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.Status -import org.onap.ccsdk.apps.controllerblueprints.common.api.EventType -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.asObjectNode -import org.onap.ccsdk.apps.controllerblueprints.core.getAsString -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.slf4j.LoggerFactory - -/** - * AbstractComponentFunction - * @author Brinda Santh - */ -abstract class AbstractComponentFunction : BlueprintFunctionNode { - @Transient - private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java) - - lateinit var executionServiceInput: ExecutionServiceInput - var executionServiceOutput = ExecutionServiceOutput() - lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> - 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 operationInputs: MutableMap = hashMapOf() - - override fun getName(): String { - return stepName - } - - override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { - checkNotNull(bluePrintRuntimeService) { "failed to prepare blueprint runtime" } - - check(stepName.isNotEmpty()) { "failed to assign step name" } - - this.executionServiceInput = executionRequest - - processId = executionRequest.commonHeader.requestId - check(processId.isNotEmpty()) { "couldn't get process id for step($stepName)" } - - workflowName = executionRequest.actionIdentifiers.actionName - check(workflowName.isNotEmpty()) { "couldn't get action name for step($stepName)" } - - log.info("preparing request id($processId) for workflow($workflowName) step($stepName)") - - val operationInputs = bluePrintRuntimeService.get("$stepName-step-inputs") - ?: JsonNodeFactory.instance.objectNode() - - operationInputs.fields().forEach { - this.operationInputs[it.key] = it.value - } - - nodeTemplateName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE) - check(nodeTemplateName.isNotEmpty()) { "couldn't get NodeTemplate name for step($stepName)" } - - interfaceName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_INTERFACE) - check(interfaceName.isNotEmpty()) { "couldn't get Interface name for step($stepName)" } - - operationName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_OPERATION) - check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" } - - val operationResolvedProperties = bluePrintRuntimeService - .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) - - this.operationInputs.putAll(operationResolvedProperties) - - return executionRequest - } - - override fun prepareResponse(): ExecutionServiceOutput { - log.info("Preparing Response...") - executionServiceOutput.commonHeader = executionServiceInput.commonHeader - executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers - - // Resolve the Output Expression - val stepOutputs = bluePrintRuntimeService - .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName) - - // FIXME("Not the right place to populate the response payload") - executionServiceOutput.payload = stepOutputs.asObjectNode() - - bluePrintRuntimeService.put("$stepName-step-outputs", executionServiceOutput.payload) - - // FIXME("Not the right place to populate the status") - // Populate Status - val status = Status() - status.eventType = EventType.EVENT_COMPONENT_EXECUTED.name - status.code = 200 - status.message = BluePrintConstants.STATUS_SUCCESS - executionServiceOutput.status = status - return this.executionServiceOutput - } - - override fun apply(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - try { - prepareRequest(executionServiceInput) - process(executionServiceInput) - } catch (runtimeException: RuntimeException) { - recover(runtimeException, executionServiceInput) - } - return prepareResponse() - } - - fun getOperationInput(key: String): JsonNode { - return operationInputs[key] - ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.") - } - - fun setAttribute(key: String, value: JsonNode) { - bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value) - } - - fun addError(type: String, name: String, error: String) { - bluePrintRuntimeService.getBluePrintError().addError(type, name, error) - } - - fun addError(error: String) { - bluePrintRuntimeService.getBluePrintError().addError(error) - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt deleted file mode 100644 index 811ee4a21..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution - -import com.fasterxml.jackson.databind.JsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException - -abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { - - companion object { - const val DYNAMIC_PROPERTIES = "dynamic-properties" - } - - /** - * Store Dynamic Script Dependency Instances, Objects present inside won't be persisted or state maintained. - */ - var functionDependencyInstances: MutableMap = hashMapOf() - - /** - * This will be called from the scripts to serve instance from runtime to scripts. - */ - open fun functionDependencyInstanceAsType(name: String): T { - return functionDependencyInstances[name] as? T - ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") - } - - fun checkDynamicProperties(key: String): Boolean { - return operationInputs[DYNAMIC_PROPERTIES]?.has(key) ?: false - } - - fun getDynamicProperties(key: String): JsonNode { - return operationInputs[DYNAMIC_PROPERTIES]!!.get(key) - } - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt deleted file mode 100644 index 2cf223256..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2018 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution - -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts.BlueprintJythonService -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintScriptsService -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext -import org.slf4j.LoggerFactory -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service - -@Service -class ComponentFunctionScriptingService(private val applicationContext: ApplicationContext, - private val bluePrintScriptsService: BluePrintScriptsService, - private val blueprintJythonService: BlueprintJythonService) { - - private val log = LoggerFactory.getLogger(ComponentFunctionScriptingService::class.java) - - fun scriptInstance(componentFunction: AbstractComponentFunction, scriptType: String, - scriptClassReference: String, - instanceDependencies: List): T { - - log.info("creating component function of script type($scriptType), reference name($scriptClassReference) and " + - "instanceDependencies($instanceDependencies)") - - val scriptComponent: T = scriptInstance(componentFunction.bluePrintRuntimeService.bluePrintContext(), - scriptType, scriptClassReference) - - checkNotNull(scriptComponent) { "failed to initialize script component" } - - scriptComponent.bluePrintRuntimeService = componentFunction.bluePrintRuntimeService - scriptComponent.processId = componentFunction.processId - scriptComponent.workflowName = componentFunction.workflowName - scriptComponent.stepName = componentFunction.stepName - scriptComponent.interfaceName = componentFunction.interfaceName - scriptComponent.operationName = componentFunction.operationName - scriptComponent.nodeTemplateName = componentFunction.nodeTemplateName - scriptComponent.operationInputs = componentFunction.operationInputs - - // Populate Instance Properties - instanceDependencies.forEach { instanceDependency -> - scriptComponent.functionDependencyInstances[instanceDependency] = applicationContext - .getBean(instanceDependency) - } - return scriptComponent - } - - - fun > scriptInstance(bluePrintContext: BluePrintContext, scriptType: String, - scriptClassReference: String): T { - var scriptComponent: T? = null - - when (scriptType) { - BluePrintConstants.SCRIPT_INTERNAL -> { - scriptComponent = bluePrintScriptsService.scriptInstance(scriptClassReference) - } - BluePrintConstants.SCRIPT_KOTLIN -> { - scriptComponent = bluePrintScriptsService.scriptInstance(bluePrintContext, scriptClassReference, false) - } - BluePrintConstants.SCRIPT_JYTHON -> { - scriptComponent = blueprintJythonService.jythonComponentInstance(bluePrintContext, scriptClassReference) as T - } - else -> { - throw BluePrintProcessorException("script type($scriptType) is not supported") - } - } - return scriptComponent - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt deleted file mode 100644 index 3937f27c3..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.node.ArrayNode -import org.apache.commons.io.FilenameUtils -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.checkNotEmptyOrThrow -import org.onap.ccsdk.apps.controllerblueprints.core.data.OperationAssignment -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BlueprintFunctionNode -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintContext -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service -import java.io.File - -@Service -class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty, - private val applicationContext: ApplicationContext) { - - val log: Logger = LoggerFactory.getLogger(BlueprintJythonService::class.java) - - inline fun jythonInstance(blueprintContext: BluePrintContext, pythonClassName: String, content: String, - dependencyInstanceNames: MutableMap?): T { - - val blueprintBasePath: String = blueprintContext.rootPath - val pythonPath: MutableList = arrayListOf() - pythonPath.add(blueprintBasePath) - pythonPath.addAll(pythonExecutorProperty.modulePaths) - - val blueprintPythonConfigurations = BluePrintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf()) - - val blueprintPythonHost = BlueprintPythonHost(blueprintPythonConfigurations) - val pyObject = blueprintPythonHost.getPythonComponent(content, pythonClassName, dependencyInstanceNames) - - log.info("Component Object {}", pyObject) - - return pyObject.__tojava__(T::class.java) as T - } - - fun jythonComponentInstance(bluePrintContext: BluePrintContext, scriptClassReference: String): - BlueprintFunctionNode<*, *> { - val blueprintBasePath: String = bluePrintContext.rootPath - - val pythonFileName = bluePrintContext.rootPath - .plus(File.separator) - .plus(scriptClassReference) - - val pythonClassName = FilenameUtils.getBaseName(pythonFileName) - log.info("Getting Jython Script Class($pythonClassName)") - - val content: String = JacksonUtils.getContent(pythonFileName) - - val pythonPath: MutableList = arrayListOf() - pythonPath.add(blueprintBasePath) - pythonPath.addAll(pythonExecutorProperty.modulePaths) - - val jythonInstances: MutableMap = hashMapOf() - jythonInstances["log"] = LoggerFactory.getLogger(pythonClassName) - - return jythonInstance>(bluePrintContext, pythonClassName, - content, jythonInstances) - } - - fun jythonComponentInstance(abstractComponentFunction: AbstractComponentFunction): AbstractComponentFunction { - - val bluePrintRuntimeService = abstractComponentFunction.bluePrintRuntimeService - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - val nodeTemplateName: String = abstractComponentFunction.nodeTemplateName - val operationInputs: MutableMap = abstractComponentFunction.operationInputs - - val operationAssignment: OperationAssignment = bluePrintContext - .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)") - - val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) - - val pythonFileName = artifactDefinition.file - ?: 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) - - checkNotEmptyOrThrow(content, "artifact ($artifactName) content is empty") - - val pythonPath: MutableList = operationAssignment.implementation?.dependencies ?: arrayListOf() - pythonPath.add(blueprintBasePath) - pythonPath.addAll(pythonExecutorProperty.modulePaths) - - val jythonInstances: MutableMap = hashMapOf() - 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})") - - instanceDependenciesNode.forEach { instanceName -> - jythonInstances[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue()) - } - - val scriptComponentFunction = jythonInstance(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/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt deleted file mode 100644 index e5b248b6c..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts - -import org.python.core.PyObject -import org.python.util.PythonInterpreter - -open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython){ - private val blueprintPythonInterpreterProxy: BlueprintPythonInterpreterProxy - - init { - PythonInterpreter.initialize(System.getProperties(), bluePrintPython.props, bluePrintPython.argv.toTypedArray()) - blueprintPythonInterpreterProxy = BlueprintPythonInterpreterProxy(bluePrintPython) - } - - /** - * getPythonComponent Purpose: execute the python script and return the python interpreter object - * - * @param content String - * @param interfaceName String - * @param properties MutableMap - * @return pyObject PyObject - */ - fun getPythonComponent(content: String?, interfaceName: String, properties: MutableMap?): PyObject { - bluePrintPython.content = content!! - bluePrintPython.pythonClassName = interfaceName - bluePrintPython.moduleName = "Blueprint Python Script [Class Name = $interfaceName]" - - return blueprintPythonInterpreterProxy.getPythonInstance(properties) - } - - //TODO Check potential errors in python scripts -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt deleted file mode 100644 index 735b8d77a..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts - -import org.python.core.PyObject -import org.python.util.PythonInterpreter - -open class BlueprintPythonInterpreterProxy(private val bluePrintPython: BluePrintPython): PythonInterpreter(){ - - fun getPythonInstance(properties: MutableMap?): PyObject{ - properties?.forEach { (name, value) -> - this.set(name, value) - } - - this.exec("import sys") - - bluePrintPython.content.let { - this.exec(bluePrintPython.content) - } - - val initCommand = bluePrintPython.pythonClassName.plus(" = ").plus( - bluePrintPython.pythonClassName).plus("()") - this.exec(initCommand) - - return this.get(bluePrintPython.pythonClassName) - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt deleted file mode 100644 index fa3e3a134..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Modifications Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts - -import org.springframework.beans.factory.annotation.Value -import org.springframework.boot.context.properties.EnableConfigurationProperties -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration -import java.io.File -import java.util.* - -@Configuration -@ComponentScan -@EnableConfigurationProperties -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(',')}") - lateinit var modulePaths: List -} - -class PythonExecutorConstants { - companion object { - const val INPUT_INSTANCE_DEPENDENCIES = "instance-dependencies" - } -} - -open class BluePrintPython(executablePath: String, blueprintPythonPlatform: MutableList, - val argv: MutableList){ - lateinit var moduleName: String - lateinit var pythonClassName: String - lateinit var content: String - var props: Properties = Properties() - - init { - // Build up the python.path - val sb = StringBuilder() - sb.append(System.getProperty("java.class.path")) - - for (p in blueprintPythonPlatform) { - sb.append(File.pathSeparator).append(p) - } - - props["python.import.site"] = "true" - props.setProperty("python.path", sb.toString()) - 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/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 new file mode 100644 index 000000000..d6c1a7c21 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractComponentFunction.kt @@ -0,0 +1,148 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution + + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.JsonNodeFactory +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.Status +import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.asObjectNode +import org.onap.ccsdk.cds.controllerblueprints.core.getAsString +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory + +/** + * AbstractComponentFunction + * @author Brinda Santh + */ +abstract class AbstractComponentFunction : BlueprintFunctionNode { + @Transient + private val log = LoggerFactory.getLogger(AbstractComponentFunction::class.java) + + lateinit var executionServiceInput: ExecutionServiceInput + var executionServiceOutput = ExecutionServiceOutput() + lateinit var bluePrintRuntimeService: BluePrintRuntimeService<*> + 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 operationInputs: MutableMap = hashMapOf() + + override fun getName(): String { + return stepName + } + + override fun prepareRequest(executionRequest: ExecutionServiceInput): ExecutionServiceInput { + checkNotNull(bluePrintRuntimeService) { "failed to prepare blueprint runtime" } + + check(stepName.isNotEmpty()) { "failed to assign step name" } + + this.executionServiceInput = executionRequest + + processId = executionRequest.commonHeader.requestId + check(processId.isNotEmpty()) { "couldn't get process id for step($stepName)" } + + workflowName = executionRequest.actionIdentifiers.actionName + check(workflowName.isNotEmpty()) { "couldn't get action name for step($stepName)" } + + log.info("preparing request id($processId) for workflow($workflowName) step($stepName)") + + val operationInputs = bluePrintRuntimeService.get("$stepName-step-inputs") + ?: JsonNodeFactory.instance.objectNode() + + operationInputs.fields().forEach { + this.operationInputs[it.key] = it.value + } + + nodeTemplateName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE) + check(nodeTemplateName.isNotEmpty()) { "couldn't get NodeTemplate name for step($stepName)" } + + interfaceName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_INTERFACE) + check(interfaceName.isNotEmpty()) { "couldn't get Interface name for step($stepName)" } + + operationName = this.operationInputs.getAsString(BluePrintConstants.PROPERTY_CURRENT_OPERATION) + check(operationName.isNotEmpty()) { "couldn't get Operation name for step($stepName)" } + + val operationResolvedProperties = bluePrintRuntimeService + .resolveNodeTemplateInterfaceOperationInputs(nodeTemplateName, interfaceName, operationName) + + this.operationInputs.putAll(operationResolvedProperties) + + return executionRequest + } + + override fun prepareResponse(): ExecutionServiceOutput { + log.info("Preparing Response...") + executionServiceOutput.commonHeader = executionServiceInput.commonHeader + executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + + // Resolve the Output Expression + val stepOutputs = bluePrintRuntimeService + .resolveNodeTemplateInterfaceOperationOutputs(nodeTemplateName, interfaceName, operationName) + + // FIXME("Not the right place to populate the response payload") + executionServiceOutput.payload = stepOutputs.asObjectNode() + + bluePrintRuntimeService.put("$stepName-step-outputs", executionServiceOutput.payload) + + // FIXME("Not the right place to populate the status") + // Populate Status + val status = Status() + status.eventType = EventType.EVENT_COMPONENT_EXECUTED.name + status.code = 200 + status.message = BluePrintConstants.STATUS_SUCCESS + executionServiceOutput.status = status + return this.executionServiceOutput + } + + override fun apply(executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { + try { + prepareRequest(executionServiceInput) + process(executionServiceInput) + } catch (runtimeException: RuntimeException) { + recover(runtimeException, executionServiceInput) + } + return prepareResponse() + } + + fun getOperationInput(key: String): JsonNode { + return operationInputs[key] + ?: throw BluePrintProcessorException("couldn't get the operation input($key) value.") + } + + fun setAttribute(key: String, value: JsonNode) { + bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, key, value) + } + + fun addError(type: String, name: String, error: String) { + bluePrintRuntimeService.getBluePrintError().addError(type, name, error) + } + + fun addError(error: String) { + bluePrintRuntimeService.getBluePrintError().addError(error) + } + +} \ 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 new file mode 100644 index 000000000..789ba9f5f --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/AbstractScriptComponentFunction.kt @@ -0,0 +1,50 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution + +import com.fasterxml.jackson.databind.JsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException + +abstract class AbstractScriptComponentFunction : AbstractComponentFunction() { + + companion object { + const val DYNAMIC_PROPERTIES = "dynamic-properties" + } + + /** + * Store Dynamic Script Dependency Instances, Objects present inside won't be persisted or state maintained. + */ + var functionDependencyInstances: MutableMap = hashMapOf() + + /** + * This will be called from the scripts to serve instance from runtime to scripts. + */ + open fun functionDependencyInstanceAsType(name: String): T { + return functionDependencyInstances[name] as? T + ?: throw BluePrintProcessorException("couldn't get script property instance ($name)") + } + + fun checkDynamicProperties(key: String): Boolean { + return operationInputs[DYNAMIC_PROPERTIES]?.has(key) ?: false + } + + fun getDynamicProperties(key: String): JsonNode { + return operationInputs[DYNAMIC_PROPERTIES]!!.get(key) + } + + +} \ 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 new file mode 100644 index 000000000..907aae4cd --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/ComponentFunctionScriptingService.kt @@ -0,0 +1,87 @@ +/* + * Copyright © 2018 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution + +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts.BlueprintJythonService +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintScriptsService +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.slf4j.LoggerFactory +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service + +@Service +class ComponentFunctionScriptingService(private val applicationContext: ApplicationContext, + private val bluePrintScriptsService: BluePrintScriptsService, + private val blueprintJythonService: BlueprintJythonService) { + + private val log = LoggerFactory.getLogger(ComponentFunctionScriptingService::class.java) + + fun scriptInstance(componentFunction: AbstractComponentFunction, scriptType: String, + scriptClassReference: String, + instanceDependencies: List): T { + + log.info("creating component function of script type($scriptType), reference name($scriptClassReference) and " + + "instanceDependencies($instanceDependencies)") + + val scriptComponent: T = scriptInstance(componentFunction.bluePrintRuntimeService.bluePrintContext(), + scriptType, scriptClassReference) + + checkNotNull(scriptComponent) { "failed to initialize script component" } + + scriptComponent.bluePrintRuntimeService = componentFunction.bluePrintRuntimeService + scriptComponent.processId = componentFunction.processId + scriptComponent.workflowName = componentFunction.workflowName + scriptComponent.stepName = componentFunction.stepName + scriptComponent.interfaceName = componentFunction.interfaceName + scriptComponent.operationName = componentFunction.operationName + scriptComponent.nodeTemplateName = componentFunction.nodeTemplateName + scriptComponent.operationInputs = componentFunction.operationInputs + + // Populate Instance Properties + instanceDependencies.forEach { instanceDependency -> + scriptComponent.functionDependencyInstances[instanceDependency] = applicationContext + .getBean(instanceDependency) + } + return scriptComponent + } + + + fun > scriptInstance(bluePrintContext: BluePrintContext, scriptType: String, + scriptClassReference: String): T { + var scriptComponent: T? = null + + when (scriptType) { + BluePrintConstants.SCRIPT_INTERNAL -> { + scriptComponent = bluePrintScriptsService.scriptInstance(scriptClassReference) + } + BluePrintConstants.SCRIPT_KOTLIN -> { + scriptComponent = bluePrintScriptsService.scriptInstance(bluePrintContext, scriptClassReference, false) + } + BluePrintConstants.SCRIPT_JYTHON -> { + scriptComponent = blueprintJythonService.jythonComponentInstance(bluePrintContext, scriptClassReference) as T + } + else -> { + throw BluePrintProcessorException("script type($scriptType) is not supported") + } + } + 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/scripts/BlueprintJythonService.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt new file mode 100644 index 000000000..2a4509033 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonService.kt @@ -0,0 +1,131 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.node.ArrayNode +import org.apache.commons.io.FilenameUtils +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.checkNotEmptyOrThrow +import org.onap.ccsdk.cds.controllerblueprints.core.data.OperationAssignment +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BlueprintFunctionNode +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintContext +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service +import java.io.File + +@Service +class BlueprintJythonService(val pythonExecutorProperty: PythonExecutorProperty, + private val applicationContext: ApplicationContext) { + + val log: Logger = LoggerFactory.getLogger(BlueprintJythonService::class.java) + + inline fun jythonInstance(blueprintContext: BluePrintContext, pythonClassName: String, content: String, + dependencyInstanceNames: MutableMap?): T { + + val blueprintBasePath: String = blueprintContext.rootPath + val pythonPath: MutableList = arrayListOf() + pythonPath.add(blueprintBasePath) + pythonPath.addAll(pythonExecutorProperty.modulePaths) + + val blueprintPythonConfigurations = BluePrintPython(pythonExecutorProperty.executionPath, pythonPath, arrayListOf()) + + val blueprintPythonHost = BlueprintPythonHost(blueprintPythonConfigurations) + val pyObject = blueprintPythonHost.getPythonComponent(content, pythonClassName, dependencyInstanceNames) + + log.info("Component Object {}", pyObject) + + return pyObject.__tojava__(T::class.java) as T + } + + fun jythonComponentInstance(bluePrintContext: BluePrintContext, scriptClassReference: String): + BlueprintFunctionNode<*, *> { + val blueprintBasePath: String = bluePrintContext.rootPath + + val pythonFileName = bluePrintContext.rootPath + .plus(File.separator) + .plus(scriptClassReference) + + val pythonClassName = FilenameUtils.getBaseName(pythonFileName) + log.info("Getting Jython Script Class($pythonClassName)") + + val content: String = JacksonUtils.getContent(pythonFileName) + + val pythonPath: MutableList = arrayListOf() + pythonPath.add(blueprintBasePath) + pythonPath.addAll(pythonExecutorProperty.modulePaths) + + val jythonInstances: MutableMap = hashMapOf() + jythonInstances["log"] = LoggerFactory.getLogger(pythonClassName) + + return jythonInstance>(bluePrintContext, pythonClassName, + content, jythonInstances) + } + + fun jythonComponentInstance(abstractComponentFunction: AbstractComponentFunction): AbstractComponentFunction { + + val bluePrintRuntimeService = abstractComponentFunction.bluePrintRuntimeService + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + val nodeTemplateName: String = abstractComponentFunction.nodeTemplateName + val operationInputs: MutableMap = abstractComponentFunction.operationInputs + + val operationAssignment: OperationAssignment = bluePrintContext + .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)") + + val artifactDefinition = bluePrintRuntimeService.resolveNodeTemplateArtifactDefinition(nodeTemplateName, artifactName) + + val pythonFileName = artifactDefinition.file + ?: 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) + + checkNotEmptyOrThrow(content, "artifact ($artifactName) content is empty") + + val pythonPath: MutableList = operationAssignment.implementation?.dependencies ?: arrayListOf() + pythonPath.add(blueprintBasePath) + pythonPath.addAll(pythonExecutorProperty.modulePaths) + + val jythonInstances: MutableMap = hashMapOf() + 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})") + + instanceDependenciesNode.forEach { instanceName -> + jythonInstances[instanceName.textValue()] = applicationContext.getBean(instanceName.textValue()) + } + + val scriptComponentFunction = jythonInstance(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 new file mode 100644 index 000000000..600308959 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonHost.kt @@ -0,0 +1,46 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts + +import org.python.core.PyObject +import org.python.util.PythonInterpreter + +open class BlueprintPythonHost(private val bluePrintPython: BluePrintPython){ + private val blueprintPythonInterpreterProxy: BlueprintPythonInterpreterProxy + + init { + PythonInterpreter.initialize(System.getProperties(), bluePrintPython.props, bluePrintPython.argv.toTypedArray()) + blueprintPythonInterpreterProxy = BlueprintPythonInterpreterProxy(bluePrintPython) + } + + /** + * getPythonComponent Purpose: execute the python script and return the python interpreter object + * + * @param content String + * @param interfaceName String + * @param properties MutableMap + * @return pyObject PyObject + */ + fun getPythonComponent(content: String?, interfaceName: String, properties: MutableMap?): PyObject { + bluePrintPython.content = content!! + bluePrintPython.pythonClassName = interfaceName + bluePrintPython.moduleName = "Blueprint Python Script [Class Name = $interfaceName]" + + return blueprintPythonInterpreterProxy.getPythonInstance(properties) + } + + //TODO Check potential errors in python scripts +} \ 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/BlueprintPythonInterpreterProxy.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt new file mode 100644 index 000000000..8998337c9 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintPythonInterpreterProxy.kt @@ -0,0 +1,40 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts + +import org.python.core.PyObject +import org.python.util.PythonInterpreter + +open class BlueprintPythonInterpreterProxy(private val bluePrintPython: BluePrintPython): PythonInterpreter(){ + + fun getPythonInstance(properties: MutableMap?): PyObject{ + properties?.forEach { (name, value) -> + this.set(name, value) + } + + this.exec("import sys") + + bluePrintPython.content.let { + this.exec(bluePrintPython.content) + } + + val initCommand = bluePrintPython.pythonClassName.plus(" = ").plus( + bluePrintPython.pythonClassName).plus("()") + this.exec(initCommand) + + return this.get(bluePrintPython.pythonClassName) + } +} \ 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/PythonExecutorConfiguration.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt new file mode 100644 index 000000000..430692ce0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/main/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/PythonExecutorConfiguration.kt @@ -0,0 +1,68 @@ +/* + * 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.blueprintsprocessor.services.execution.scripts + +import org.springframework.beans.factory.annotation.Value +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration +import java.io.File +import java.util.* + +@Configuration +@ComponentScan +@EnableConfigurationProperties +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(',')}") + lateinit var modulePaths: List +} + +class PythonExecutorConstants { + companion object { + const val INPUT_INSTANCE_DEPENDENCIES = "instance-dependencies" + } +} + +open class BluePrintPython(executablePath: String, blueprintPythonPlatform: MutableList, + val argv: MutableList){ + lateinit var moduleName: String + lateinit var pythonClassName: String + lateinit var content: String + var props: Properties = Properties() + + init { + // Build up the python.path + val sb = StringBuilder() + sb.append(System.getProperty("java.class.path")) + + for (p in blueprintPythonPlatform) { + sb.append(File.pathSeparator).append(p) + } + + props["python.import.site"] = "true" + props.setProperty("python.path", sb.toString()) + 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/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt deleted file mode 100644 index b48a10e9c..000000000 --- a/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright © 2019 IBM, Bell Canada. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onap.ccsdk.apps.blueprintsprocessor.services.execution.scripts - -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.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 - -@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"]) -class BlueprintJythonServiceTest { - - @Autowired - private lateinit var blueprintJythonService: BlueprintJythonService - - @Test - fun testGetAbstractPythonPlugin() { - val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val dependencies: MutableMap = hashMapOf() - - val content = JacksonUtils.getContent("./../../../../." + - "./components/model-catalog/blueprint-model/test-blueprint/baseconfiguration/Scripts/python/SamplePythonComponentNode.py") - - val abstractComponentFunction = blueprintJythonService.jythonInstance(bluePrintContext, "SamplePythonComponentNode", content, dependencies) - - assertNotNull(abstractComponentFunction, "failed to get python component") - - abstractComponentFunction.process(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/BlueprintJythonServiceTest.kt b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt new file mode 100644 index 000000000..d6c0cf58b --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/execution-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/execution/scripts/BlueprintJythonServiceTest.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2019 IBM, Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.cds.blueprintsprocessor.services.execution.scripts + +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.TestPropertySource +import org.springframework.test.context.junit4.SpringRunner +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"]) +class BlueprintJythonServiceTest { + + @Autowired + private lateinit var blueprintJythonService: BlueprintJythonService + + @Test + fun testGetAbstractPythonPlugin() { + val bluePrintContext = BluePrintMetadataUtils.getBluePrintContext( + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val dependencies: MutableMap = hashMapOf() + + val content = JacksonUtils.getContent("./../../../../." + + "./components/model-catalog/blueprint-model/test-blueprint/baseconfiguration/Scripts/python/SamplePythonComponentNode.py") + + val abstractComponentFunction = blueprintJythonService.jythonInstance(bluePrintContext, "SamplePythonComponentNode", content, dependencies) + + assertNotNull(abstractComponentFunction, "failed to get python component") + + abstractComponentFunction.process(ExecutionServiceInput()) + + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/pom.xml b/ms/blueprintsprocessor/modules/services/pom.xml index ee5b73cc7..751ad94d4 100755 --- a/ms/blueprintsprocessor/modules/services/pom.xml +++ b/ms/blueprintsprocessor/modules/services/pom.xml @@ -20,7 +20,7 @@ 4.0.0 - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor modules 0.4.2-SNAPSHOT diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml index 4331eec77..c48ff250f 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml +++ b/ms/blueprintsprocessor/modules/services/workflow-service/pom.xml @@ -17,7 +17,7 @@ --> - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor services 0.4.2-SNAPSHOT @@ -29,11 +29,11 @@ - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor execution-service diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt deleted file mode 100644 index 73f6f497e..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintProcessorException -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service - -@Service("bluePrintWorkflowExecutionService") -open class BluePrintWorkflowExecutionServiceImpl( - private val componentWorkflowExecutionService: ComponentWorkflowExecutionService, - private val dgWorkflowExecutionService: DGWorkflowExecutionService -) : BluePrintWorkflowExecutionService { - - private val log = LoggerFactory.getLogger(BluePrintWorkflowExecutionServiceImpl::class.java)!! - - override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, - executionServiceInput: ExecutionServiceInput, - properties: MutableMap): ExecutionServiceOutput { - - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val workflowName = executionServiceInput.actionIdentifiers.actionName - - // Get the DG Node Template - val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) - - val derivedFrom = bluePrintContext.nodeTemplateNodeType(nodeTemplateName).derivedFrom - - log.info("Executing workflow($workflowName) NodeTemplate($nodeTemplateName), derived from($derivedFrom)") - - val executionServiceOutput: ExecutionServiceOutput = when { - derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { - componentWorkflowExecutionService - .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) - } - derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_DG, true) -> { - dgWorkflowExecutionService - .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) - } - else -> { - throw BluePrintProcessorException("couldn't execute workflow($workflowName) step mapped " + - "to node template($nodeTemplateName) derived from($derivedFrom)") - } - } - - executionServiceOutput.commonHeader = executionServiceInput.commonHeader - executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers - // TODO("Populate Response Payload and status") - return executionServiceOutput - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt deleted file mode 100644 index d2648c079..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.onap.ccsdk.sli.core.sli.SvcLogicContext - -class BlueprintSvcLogicContext : SvcLogicContext() { - - private var bluePrintRuntimeService: BluePrintRuntimeService<*>? = null - private var request: Any? = null - private var response: Any? = null - - fun getBluePrintService(): BluePrintRuntimeService<*> { - return this.bluePrintRuntimeService!! - } - - fun setBluePrintRuntimeService(bluePrintRuntimeService: BluePrintRuntimeService<*>) { - this.bluePrintRuntimeService = bluePrintRuntimeService - } - - fun setRequest(request: Any) { - this.request = request - } - - fun getRequest(): Any { - return this.request!! - } - - fun setResponse(response: Any) { - this.response = response - } - - 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/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt deleted file mode 100644 index fd7ec45b3..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.onap.ccsdk.sli.core.sli.* -import org.onap.ccsdk.sli.core.sli.provider.base.* -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 javax.annotation.PostConstruct - -interface BlueprintSvcLogicService : SvcLogicServiceBase { - - fun registerDefaultExecutors() - - fun registerExecutors(name: String, svcLogicNodeExecutor: AbstractSvcLogicNodeExecutor) - - fun unRegisterExecutors(name: String) - - suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: Any): Any - - @Deprecated("Populate Graph Dynamically from Blueprints, No need to get from Database Store ") - override fun getStore(): SvcLogicStore { - TODO("not implemented") - } - - @Deprecated("Not used in Micro service Implementation") - override fun hasGraph(module: String, rpc: String, version: String?, mode: String): Boolean { - TODO("not implemented") - } - - @Deprecated("Not used in Micro service Implementation") - override fun execute(p0: String?, p1: String?, p2: String?, p3: String?, p4: Properties?): Properties { - TODO("not implemented") - } -} - - -@Service -class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService { - - private val log = LoggerFactory.getLogger(DefaultBlueprintSvcLogicService::class.java) - - private val nodeExecutors: MutableMap = hashMapOf() - - @Autowired - private lateinit var context: ApplicationContext - - @PostConstruct - override fun registerDefaultExecutors() { - - val executeNodeExecutor = context.getBean(ExecuteNodeExecutor::class.java) - registerExecutors("execute", executeNodeExecutor) - registerExecutors("block", BlockNodeExecutor()) - registerExecutors("return", ReturnNodeExecutor()) - registerExecutors("break", BreakNodeExecutor()) - registerExecutors("exit", ExitNodeExecutor()) - } - - override fun registerExecutors(name: String, svcLogicNodeExecutor: AbstractSvcLogicNodeExecutor) { - log.info("Registering executors($name) with type(${svcLogicNodeExecutor.javaClass}") - nodeExecutors[name] = svcLogicNodeExecutor - } - - override fun unRegisterExecutors(name: String) { - if (nodeExecutors.containsKey(name)) { - log.info("UnRegistering executors($name)") - nodeExecutors.remove(name) - } - } - - 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) - // Execute the Graph - execute(graph, blueprintSvcLogicContext) - // Get the Response - return blueprintSvcLogicContext.getResponse() - } - - override fun executeNode(node: SvcLogicNode?, ctx: SvcLogicContext): SvcLogicNode? { - if (node == null) { - return null - } else { - if (log.isDebugEnabled) { - log.debug("Executing node {}", node.nodeId) - } - - val executor = this.nodeExecutors[node.nodeType] - - if (executor != null) { - log.debug("Executing node executor for node type {} - {}", node.nodeType, executor.javaClass.name) - return executor.execute(this, node, ctx) - } else { - throw SvcLogicException("Attempted to execute a node of type " + node.nodeType + ", but no executor was registered for this type") - } - } - } - - override fun execute(graph: SvcLogicGraph, svcLogicContext: SvcLogicContext): SvcLogicContext { - MDC.put("currentGraph", graph.toString()) - - var curNode: SvcLogicNode? = graph.rootNode - log.info("About to execute graph {}", graph.toString()) - - try { - while (curNode != null) { - MDC.put("nodeId", curNode.nodeId.toString() + " (" + curNode.nodeType + ")") - log.info("About to execute node # {} ({})", curNode.nodeId, curNode.nodeType) - val nextNode = this.executeNode(curNode, svcLogicContext) - curNode = nextNode - } - } catch (var5: ExitNodeException) { - log.debug("SvcLogicServiceImpl caught ExitNodeException") - } - - MDC.remove("nodeId") - 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/apps/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt deleted file mode 100644 index 76d0c46b5..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.springframework.stereotype.Service - -@Service("componentWorkflowExecutionService") -open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) - : BluePrintWorkflowExecutionService { - - override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, - executionServiceInput: ExecutionServiceInput, - properties: MutableMap): ExecutionServiceOutput { - - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val workflowName = executionServiceInput.actionIdentifiers.actionName - - // Get the DG Node Template - val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) - - // Assign Workflow inputs - val input = executionServiceInput.payload.get("$workflowName-request") - bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) - - 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/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt deleted file mode 100644 index 262b1be19..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.utils.SvcGraphUtils -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service -import java.io.File - - -@Service("dgWorkflowExecutionService") -open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService) - : BluePrintWorkflowExecutionService { - - private val log = LoggerFactory.getLogger(DGWorkflowExecutionService::class.java) - - override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, - executionServiceInput: ExecutionServiceInput, - properties: MutableMap): ExecutionServiceOutput { - - val bluePrintContext = bluePrintRuntimeService.bluePrintContext() - - val workflowName = executionServiceInput.actionIdentifiers.actionName - - // Get the DG Node Template - val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) - - log.info("Executing workflow($workflowName) directed graph NodeTemplate($nodeTemplateName)") - - // Get the DG file info - val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(nodeTemplateName, - WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH) - - // Populate the DG Path - val dgFilePath = bluePrintContext.rootPath.plus(File.separator).plus(artifactDefinition.file) - - log.info("Executing directed graph ($dgFilePath)") - - // Create DG instance - val graph = SvcGraphUtils.getSvcGraphFromFile(dgFilePath) - - // Assign Workflow inputs - val input = executionServiceInput.payload.get("$workflowName-request") - bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) - - // Execute the DG - return blueprintSvcLogicService.execute(graph, bluePrintRuntimeService, executionServiceInput) as ExecutionServiceOutput - - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt deleted file mode 100644 index 6ce4753b8..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import com.fasterxml.jackson.databind.JsonNode -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.BluePrintConstants -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonNode -import org.onap.ccsdk.apps.controllerblueprints.core.putJsonElement -import org.onap.ccsdk.apps.controllerblueprints.core.service.BluePrintRuntimeService -import org.slf4j.LoggerFactory -import org.springframework.context.ApplicationContext -import org.springframework.stereotype.Service - -@Service -open class NodeTemplateExecutionService(private val applicationContext: ApplicationContext) { - - private val log = LoggerFactory.getLogger(NodeTemplateExecutionService::class.java)!! - - suspend fun executeNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, - executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { - // Get the Blueprint Context - val blueprintContext = bluePrintRuntimeService.bluePrintContext() - // Get the Component Name, NodeTemplate type is mapped to Component Name - val componentName = blueprintContext.nodeTemplateByName(nodeTemplateName).type - - val interfaceName = blueprintContext.nodeTemplateFirstInterfaceName(nodeTemplateName) - - val operationName = blueprintContext.nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName) - - log.info("executing node template($nodeTemplateName) component($componentName) " + - "interface($interfaceName) operation($operationName)") - - // Get the Component Instance - val plugin = applicationContext.getBean(componentName, AbstractComponentFunction::class.java) - // Set the Blueprint Service - plugin.bluePrintRuntimeService = bluePrintRuntimeService - plugin.stepName = nodeTemplateName - - // Populate Step Meta Data - val stepInputs: MutableMap = hashMapOf() - stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, nodeTemplateName) - stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, interfaceName) - stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, operationName) - - plugin.bluePrintRuntimeService.put("$nodeTemplateName-step-inputs", stepInputs.asJsonNode()) - - // Get the Request from the Context and Set to the Function Input and Invoke the function - return withContext(Dispatchers.Default) { - plugin.apply(executionServiceInput) - } - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt deleted file mode 100644 index b3186e849..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import org.springframework.context.annotation.ComponentScan -import org.springframework.context.annotation.Configuration - -@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/apps/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt deleted file mode 100644 index 1e856b689..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.executor - -import kotlinx.coroutines.runBlocking -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.BlueprintSvcLogicContext -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.NodeTemplateExecutionService -import org.onap.ccsdk.sli.core.sli.SvcLogicContext -import org.onap.ccsdk.sli.core.sli.SvcLogicException -import org.onap.ccsdk.sli.core.sli.SvcLogicNode -import org.onap.ccsdk.sli.core.sli.provider.base.ExecuteNodeExecutor -import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicExpressionResolver -import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase -import org.slf4j.LoggerFactory -import org.springframework.stereotype.Service - -@Service -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 { - - var outValue: String - - val ctx = svcLogicContext as BlueprintSvcLogicContext - - val nodeTemplateName = SvcLogicExpressionResolver.evaluate(node.getAttribute("plugin"), node, ctx) - - 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) - - 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" - ctx.status = "failure" - } - - getNextNode(node, outValue) - } - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt deleted file mode 100644 index ada36ac0b..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.utils - -import org.onap.ccsdk.sli.core.sli.SvcLogicGraph -import org.onap.ccsdk.sli.core.sli.SvcLogicParser - -object SvcGraphUtils { - - @JvmStatic - fun getSvcGraphFromClassPathFile(fileName: String): SvcLogicGraph { - val url = SvcGraphUtils::class.java.classLoader.getResource(fileName) - return getSvcGraphFromFile(url.path) - } - - @JvmStatic - fun getSvcGraphFromFile(fileName: String): SvcLogicGraph { - val svcLogicParser = SvcLogicParser() - return svcLogicParser.parse(fileName).first - } -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt new file mode 100644 index 000000000..fbd9f4c8b --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImpl.kt @@ -0,0 +1,72 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service + +@Service("bluePrintWorkflowExecutionService") +open class BluePrintWorkflowExecutionServiceImpl( + private val componentWorkflowExecutionService: ComponentWorkflowExecutionService, + private val dgWorkflowExecutionService: DGWorkflowExecutionService +) : BluePrintWorkflowExecutionService { + + private val log = LoggerFactory.getLogger(BluePrintWorkflowExecutionServiceImpl::class.java)!! + + override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: ExecutionServiceInput, + properties: MutableMap): ExecutionServiceOutput { + + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val workflowName = executionServiceInput.actionIdentifiers.actionName + + // Get the DG Node Template + val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) + + val derivedFrom = bluePrintContext.nodeTemplateNodeType(nodeTemplateName).derivedFrom + + log.info("Executing workflow($workflowName) NodeTemplate($nodeTemplateName), derived from($derivedFrom)") + + val executionServiceOutput: ExecutionServiceOutput = when { + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_COMPONENT, true) -> { + componentWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) + } + derivedFrom.startsWith(BluePrintConstants.MODEL_TYPE_NODE_DG, true) -> { + dgWorkflowExecutionService + .executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, properties) + } + else -> { + throw BluePrintProcessorException("couldn't execute workflow($workflowName) step mapped " + + "to node template($nodeTemplateName) derived from($derivedFrom)") + } + } + + executionServiceOutput.commonHeader = executionServiceInput.commonHeader + executionServiceOutput.actionIdentifiers = executionServiceInput.actionIdentifiers + // TODO("Populate Response Payload and status") + return executionServiceOutput + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt new file mode 100644 index 000000000..a2db8aab7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicContext.kt @@ -0,0 +1,52 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.onap.ccsdk.sli.core.sli.SvcLogicContext + +class BlueprintSvcLogicContext : SvcLogicContext() { + + private var bluePrintRuntimeService: BluePrintRuntimeService<*>? = null + private var request: Any? = null + private var response: Any? = null + + fun getBluePrintService(): BluePrintRuntimeService<*> { + return this.bluePrintRuntimeService!! + } + + fun setBluePrintRuntimeService(bluePrintRuntimeService: BluePrintRuntimeService<*>) { + this.bluePrintRuntimeService = bluePrintRuntimeService + } + + fun setRequest(request: Any) { + this.request = request + } + + fun getRequest(): Any { + return this.request!! + } + + fun setResponse(response: Any) { + this.response = response + } + + 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/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt new file mode 100644 index 000000000..6712a7ff4 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/BlueprintSvcLogicService.kt @@ -0,0 +1,143 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.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.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 javax.annotation.PostConstruct + +interface BlueprintSvcLogicService : SvcLogicServiceBase { + + fun registerDefaultExecutors() + + fun registerExecutors(name: String, svcLogicNodeExecutor: AbstractSvcLogicNodeExecutor) + + fun unRegisterExecutors(name: String) + + suspend fun execute(graph: SvcLogicGraph, bluePrintRuntimeService: BluePrintRuntimeService<*>, input: Any): Any + + @Deprecated("Populate Graph Dynamically from Blueprints, No need to get from Database Store ") + override fun getStore(): SvcLogicStore { + TODO("not implemented") + } + + @Deprecated("Not used in Micro service Implementation") + override fun hasGraph(module: String, rpc: String, version: String?, mode: String): Boolean { + TODO("not implemented") + } + + @Deprecated("Not used in Micro service Implementation") + override fun execute(p0: String?, p1: String?, p2: String?, p3: String?, p4: Properties?): Properties { + TODO("not implemented") + } +} + + +@Service +class DefaultBlueprintSvcLogicService : BlueprintSvcLogicService { + + private val log = LoggerFactory.getLogger(DefaultBlueprintSvcLogicService::class.java) + + private val nodeExecutors: MutableMap = hashMapOf() + + @Autowired + private lateinit var context: ApplicationContext + + @PostConstruct + override fun registerDefaultExecutors() { + + val executeNodeExecutor = context.getBean(ExecuteNodeExecutor::class.java) + registerExecutors("execute", executeNodeExecutor) + registerExecutors("block", BlockNodeExecutor()) + registerExecutors("return", ReturnNodeExecutor()) + registerExecutors("break", BreakNodeExecutor()) + registerExecutors("exit", ExitNodeExecutor()) + } + + override fun registerExecutors(name: String, svcLogicNodeExecutor: AbstractSvcLogicNodeExecutor) { + log.info("Registering executors($name) with type(${svcLogicNodeExecutor.javaClass}") + nodeExecutors[name] = svcLogicNodeExecutor + } + + override fun unRegisterExecutors(name: String) { + if (nodeExecutors.containsKey(name)) { + log.info("UnRegistering executors($name)") + nodeExecutors.remove(name) + } + } + + 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) + // Execute the Graph + execute(graph, blueprintSvcLogicContext) + // Get the Response + return blueprintSvcLogicContext.getResponse() + } + + override fun executeNode(node: SvcLogicNode?, ctx: SvcLogicContext): SvcLogicNode? { + if (node == null) { + return null + } else { + if (log.isDebugEnabled) { + log.debug("Executing node {}", node.nodeId) + } + + val executor = this.nodeExecutors[node.nodeType] + + if (executor != null) { + log.debug("Executing node executor for node type {} - {}", node.nodeType, executor.javaClass.name) + return executor.execute(this, node, ctx) + } else { + throw SvcLogicException("Attempted to execute a node of type " + node.nodeType + ", but no executor was registered for this type") + } + } + } + + override fun execute(graph: SvcLogicGraph, svcLogicContext: SvcLogicContext): SvcLogicContext { + MDC.put("currentGraph", graph.toString()) + + var curNode: SvcLogicNode? = graph.rootNode + log.info("About to execute graph {}", graph.toString()) + + try { + while (curNode != null) { + MDC.put("nodeId", curNode.nodeId.toString() + " (" + curNode.nodeType + ")") + log.info("About to execute node # {} ({})", curNode.nodeId, curNode.nodeType) + val nextNode = this.executeNode(curNode, svcLogicContext) + curNode = nextNode + } + } catch (var5: ExitNodeException) { + log.debug("SvcLogicServiceImpl caught ExitNodeException") + } + + MDC.remove("nodeId") + 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/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt new file mode 100644 index 000000000..3b2fc3368 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/ComponentWorkflowExecutionService.kt @@ -0,0 +1,49 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + + +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.springframework.stereotype.Service + +@Service("componentWorkflowExecutionService") +open class ComponentWorkflowExecutionService(private val nodeTemplateExecutionService: NodeTemplateExecutionService) + : BluePrintWorkflowExecutionService { + + override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: ExecutionServiceInput, + properties: MutableMap): ExecutionServiceOutput { + + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val workflowName = executionServiceInput.actionIdentifiers.actionName + + // Get the DG Node Template + val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) + + // Assign Workflow inputs + val input = executionServiceInput.payload.get("$workflowName-request") + bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) + + 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/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt new file mode 100644 index 000000000..571b6c7c0 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionService.kt @@ -0,0 +1,70 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.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.blueprintsprocessor.services.workflow.utils.SvcGraphUtils +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service +import java.io.File + + +@Service("dgWorkflowExecutionService") +open class DGWorkflowExecutionService(private val blueprintSvcLogicService: BlueprintSvcLogicService) + : BluePrintWorkflowExecutionService { + + private val log = LoggerFactory.getLogger(DGWorkflowExecutionService::class.java) + + override suspend fun executeBluePrintWorkflow(bluePrintRuntimeService: BluePrintRuntimeService<*>, + executionServiceInput: ExecutionServiceInput, + properties: MutableMap): ExecutionServiceOutput { + + val bluePrintContext = bluePrintRuntimeService.bluePrintContext() + + val workflowName = executionServiceInput.actionIdentifiers.actionName + + // Get the DG Node Template + val nodeTemplateName = bluePrintContext.workflowFirstStepNodeTemplate(workflowName) + + log.info("Executing workflow($workflowName) directed graph NodeTemplate($nodeTemplateName)") + + // Get the DG file info + val artifactDefinition = bluePrintContext.nodeTemplateArtifactForArtifactType(nodeTemplateName, + WorkflowServiceConstants.ARTIFACT_TYPE_DIRECTED_GRAPH) + + // Populate the DG Path + val dgFilePath = bluePrintContext.rootPath.plus(File.separator).plus(artifactDefinition.file) + + log.info("Executing directed graph ($dgFilePath)") + + // Create DG instance + val graph = SvcGraphUtils.getSvcGraphFromFile(dgFilePath) + + // Assign Workflow inputs + val input = executionServiceInput.payload.get("$workflowName-request") + bluePrintRuntimeService.assignWorkflowInputs(workflowName, input) + + // Execute the DG + return blueprintSvcLogicService.execute(graph, bluePrintRuntimeService, executionServiceInput) as ExecutionServiceOutput + + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt new file mode 100644 index 000000000..67be26e6d --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/NodeTemplateExecutionService.kt @@ -0,0 +1,72 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import com.fasterxml.jackson.databind.JsonNode +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +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.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonNode +import org.onap.ccsdk.cds.controllerblueprints.core.putJsonElement +import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintRuntimeService +import org.slf4j.LoggerFactory +import org.springframework.context.ApplicationContext +import org.springframework.stereotype.Service + +@Service +open class NodeTemplateExecutionService(private val applicationContext: ApplicationContext) { + + private val log = LoggerFactory.getLogger(NodeTemplateExecutionService::class.java)!! + + suspend fun executeNodeTemplate(bluePrintRuntimeService: BluePrintRuntimeService<*>, nodeTemplateName: String, + executionServiceInput: ExecutionServiceInput): ExecutionServiceOutput { + // Get the Blueprint Context + val blueprintContext = bluePrintRuntimeService.bluePrintContext() + // Get the Component Name, NodeTemplate type is mapped to Component Name + val componentName = blueprintContext.nodeTemplateByName(nodeTemplateName).type + + val interfaceName = blueprintContext.nodeTemplateFirstInterfaceName(nodeTemplateName) + + val operationName = blueprintContext.nodeTemplateFirstInterfaceFirstOperationName(nodeTemplateName) + + log.info("executing node template($nodeTemplateName) component($componentName) " + + "interface($interfaceName) operation($operationName)") + + // Get the Component Instance + val plugin = applicationContext.getBean(componentName, AbstractComponentFunction::class.java) + // Set the Blueprint Service + plugin.bluePrintRuntimeService = bluePrintRuntimeService + plugin.stepName = nodeTemplateName + + // Populate Step Meta Data + val stepInputs: MutableMap = hashMapOf() + stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_NODE_TEMPLATE, nodeTemplateName) + stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_INTERFACE, interfaceName) + stepInputs.putJsonElement(BluePrintConstants.PROPERTY_CURRENT_OPERATION, operationName) + + plugin.bluePrintRuntimeService.put("$nodeTemplateName-step-inputs", stepInputs.asJsonNode()) + + // Get the Request from the Context and Set to the Function Input and Invoke the function + return withContext(Dispatchers.Default) { + plugin.apply(executionServiceInput) + } + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.kt new file mode 100644 index 000000000..67f13f760 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/WorkflowServiceConfiguration.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.blueprintsprocessor.services.workflow + +import org.springframework.context.annotation.ComponentScan +import org.springframework.context.annotation.Configuration + +@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/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt new file mode 100644 index 000000000..cfba5becd --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/executor/ComponentExecuteNodeExecutor.kt @@ -0,0 +1,69 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.executor + +import kotlinx.coroutines.runBlocking +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.BlueprintSvcLogicContext +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.NodeTemplateExecutionService +import org.onap.ccsdk.sli.core.sli.SvcLogicContext +import org.onap.ccsdk.sli.core.sli.SvcLogicException +import org.onap.ccsdk.sli.core.sli.SvcLogicNode +import org.onap.ccsdk.sli.core.sli.provider.base.ExecuteNodeExecutor +import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicExpressionResolver +import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase +import org.slf4j.LoggerFactory +import org.springframework.stereotype.Service + +@Service +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 { + + var outValue: String + + val ctx = svcLogicContext as BlueprintSvcLogicContext + + val nodeTemplateName = SvcLogicExpressionResolver.evaluate(node.getAttribute("plugin"), node, ctx) + + 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) + + 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" + ctx.status = "failure" + } + + getNextNode(node, outValue) + } + +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt new file mode 100644 index 000000000..8f9579230 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/main/kotlin/org/onap/cds/blueprintsprocessor/services/workflow/utils/SvcGraphUtils.kt @@ -0,0 +1,35 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.utils + +import org.onap.ccsdk.sli.core.sli.SvcLogicGraph +import org.onap.ccsdk.sli.core.sli.SvcLogicParser + +object SvcGraphUtils { + + @JvmStatic + fun getSvcGraphFromClassPathFile(fileName: String): SvcLogicGraph { + val url = SvcGraphUtils::class.java.classLoader.getResource(fileName) + return getSvcGraphFromFile(url.path) + } + + @JvmStatic + fun getSvcGraphFromFile(fileName: String): SvcLogicGraph { + 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/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt deleted file mode 100644 index 7ac9bc33d..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceOutput -import org.onap.ccsdk.apps.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner - - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [WorkflowServiceConfiguration::class]) -class BluePrintWorkflowExecutionServiceImplTest { - - @Autowired - lateinit var bluePrintWorkflowExecutionService: BluePrintWorkflowExecutionService - - @Test - fun testBluePrintWorkflowExecutionService() { - - 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)!! - - runBlocking { - bluePrintWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, - hashMapOf()) - } - } - -} diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt deleted file mode 100644 index b374e7d44..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.mock.PrototypeComponentFunction -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.mock.SingletonComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.context.ApplicationContext -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner -import kotlin.test.assertEquals - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [WorkflowServiceConfiguration::class, ComponentExecuteNodeExecutor::class]) -class BlueprintServiceLogicTest { - - private val log = LoggerFactory.getLogger(BlueprintServiceLogicTest::class.java) - - @Autowired - lateinit var applicationContext: ApplicationContext - - @Autowired - lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService - - @Test - fun testExecuteGraphWithSingleComponent() { - - 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)!! - - runBlocking { - dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) - } - - - } - - @Test - fun testExecuteGraphWithMultipleComponents() { - - val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", - "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") - - val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!! - - runBlocking { - dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) - } - - } - - @Test - fun testSingleton() { - val singleton1 = applicationContext.getBean(SingletonComponentFunction::class.java) - singleton1.stepName = "step1" - val singleton2 = applicationContext.getBean(SingletonComponentFunction::class.java) - assertEquals(singleton1.stepName, singleton2.stepName, " failed to get singleton data") - } - - @Test - fun testProtoTypeFunction() { - val stepName1 = "step1" - val stepName2 = "step2" - val proto1 = applicationContext.getBean(PrototypeComponentFunction::class.java) - proto1.stepName = stepName1 - - val proto2 = applicationContext.getBean(PrototypeComponentFunction::class.java) - proto2.stepName = stepName2 - - 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/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt deleted file mode 100644 index 2e36fb5ff..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * Modifications Copyright © 2019 IBM. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow - -import kotlinx.coroutines.runBlocking -import org.junit.Test -import org.junit.runner.RunWith -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor -import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintMetadataUtils -import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.test.context.ContextConfiguration -import org.springframework.test.context.junit4.SpringRunner - -@RunWith(SpringRunner::class) -@ContextConfiguration(classes = [WorkflowServiceConfiguration::class, ComponentExecuteNodeExecutor::class]) -class DGWorkflowExecutionServiceTest { - - private val log = LoggerFactory.getLogger(BlueprintServiceLogicTest::class.java) - - @Autowired - lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService - - - @Test - fun testExecuteDirectedGraph() { - - 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)!! - - runBlocking { - dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) - } - - } - - -} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt deleted file mode 100644 index 4c1245621..000000000 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/apps/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright © 2017-2018 AT&T Intellectual Property. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.onap.ccsdk.apps.blueprintsprocessor.services.workflow.mock - -import org.onap.ccsdk.apps.blueprintsprocessor.core.api.data.ExecutionServiceInput -import org.onap.ccsdk.apps.blueprintsprocessor.services.execution.AbstractComponentFunction -import org.onap.ccsdk.apps.controllerblueprints.core.asJsonPrimitive -import org.slf4j.LoggerFactory -import org.springframework.beans.factory.config.ConfigurableBeanFactory -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import org.springframework.context.annotation.Scope -import org.springframework.stereotype.Component - -@Configuration -open class MockComponentConfiguration { - - @Bean(name = ["component-resource-resolution", "component-netconf-executor", "component-jython-executor"]) - open fun createComponentFunction(): AbstractComponentFunction { - return MockComponentFunction() - } -} - -class MockComponentFunction : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) - - override fun process(executionRequest: ExecutionServiceInput) { - log.info("Processing component : $operationInputs") - - bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, - "assignment-params", "params".asJsonPrimitive()) - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recovering component..") - } -} - -@Component("singleton-function") -@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) -class SingletonComponentFunction : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) - - override fun process(executionRequest: ExecutionServiceInput) { - log.info("Processing component : $operationInputs") - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recovering component..") - } -} - -@Component("prototype-function") -@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) -class PrototypeComponentFunction : AbstractComponentFunction() { - - private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) - - override fun process(executionRequest: ExecutionServiceInput) { - log.info("Processing component : $operationInputs") - } - - override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { - log.info("Recovering component..") - } -} \ 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 new file mode 100644 index 000000000..3958f0c15 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BluePrintWorkflowExecutionServiceImplTest.kt @@ -0,0 +1,54 @@ +/* + * Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceOutput +import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintWorkflowExecutionService +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner + + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [WorkflowServiceConfiguration::class]) +class BluePrintWorkflowExecutionServiceImplTest { + + @Autowired + lateinit var bluePrintWorkflowExecutionService: BluePrintWorkflowExecutionService + + @Test + fun testBluePrintWorkflowExecutionService() { + + 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)!! + + runBlocking { + bluePrintWorkflowExecutionService.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 new file mode 100644 index 000000000..ad2ee57d7 --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/BlueprintServiceLogicTest.kt @@ -0,0 +1,99 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.PrototypeComponentFunction +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock.SingletonComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.context.ApplicationContext +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner +import kotlin.test.assertEquals + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [WorkflowServiceConfiguration::class, ComponentExecuteNodeExecutor::class]) +class BlueprintServiceLogicTest { + + private val log = LoggerFactory.getLogger(BlueprintServiceLogicTest::class.java) + + @Autowired + lateinit var applicationContext: ApplicationContext + + @Autowired + lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService + + @Test + fun testExecuteGraphWithSingleComponent() { + + 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)!! + + runBlocking { + dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) + } + + + } + + @Test + fun testExecuteGraphWithMultipleComponents() { + + val bluePrintRuntimeService = BluePrintMetadataUtils.getBluePrintRuntime("1234", + "./../../../../../components/model-catalog/blueprint-model/test-blueprint/baseconfiguration") + + val executionServiceInput = JacksonUtils.readValueFromClassPathFile("execution-input/assign-activate-input.json", ExecutionServiceInput::class.java)!! + + runBlocking { + dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) + } + + } + + @Test + fun testSingleton() { + val singleton1 = applicationContext.getBean(SingletonComponentFunction::class.java) + singleton1.stepName = "step1" + val singleton2 = applicationContext.getBean(SingletonComponentFunction::class.java) + assertEquals(singleton1.stepName, singleton2.stepName, " failed to get singleton data") + } + + @Test + fun testProtoTypeFunction() { + val stepName1 = "step1" + val stepName2 = "step2" + val proto1 = applicationContext.getBean(PrototypeComponentFunction::class.java) + proto1.stepName = stepName1 + + val proto2 = applicationContext.getBean(PrototypeComponentFunction::class.java) + proto2.stepName = stepName2 + + 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 new file mode 100644 index 000000000..0980f84aa --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/DGWorkflowExecutionServiceTest.kt @@ -0,0 +1,57 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * Modifications Copyright © 2019 IBM. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow + +import kotlinx.coroutines.runBlocking +import org.junit.Test +import org.junit.runner.RunWith +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.executor.ComponentExecuteNodeExecutor +import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintMetadataUtils +import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.test.context.ContextConfiguration +import org.springframework.test.context.junit4.SpringRunner + +@RunWith(SpringRunner::class) +@ContextConfiguration(classes = [WorkflowServiceConfiguration::class, ComponentExecuteNodeExecutor::class]) +class DGWorkflowExecutionServiceTest { + + private val log = LoggerFactory.getLogger(BlueprintServiceLogicTest::class.java) + + @Autowired + lateinit var dgWorkflowExecutionService: DGWorkflowExecutionService + + + @Test + fun testExecuteDirectedGraph() { + + 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)!! + + runBlocking { + dgWorkflowExecutionService.executeBluePrintWorkflow(bluePrintRuntimeService, executionServiceInput, mutableMapOf()) + } + + } + + +} \ 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 new file mode 100644 index 000000000..1cae01ffa --- /dev/null +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/services/workflow/mock/MockComponentFunction.kt @@ -0,0 +1,82 @@ +/* + * Copyright © 2017-2018 AT&T Intellectual Property. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.ccsdk.cds.blueprintsprocessor.services.workflow.mock + +import org.onap.ccsdk.cds.blueprintsprocessor.core.api.data.ExecutionServiceInput +import org.onap.ccsdk.cds.blueprintsprocessor.services.execution.AbstractComponentFunction +import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive +import org.slf4j.LoggerFactory +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.Scope +import org.springframework.stereotype.Component + +@Configuration +open class MockComponentConfiguration { + + @Bean(name = ["component-resource-resolution", "component-netconf-executor", "component-jython-executor"]) + open fun createComponentFunction(): AbstractComponentFunction { + return MockComponentFunction() + } +} + +class MockComponentFunction : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing component : $operationInputs") + + bluePrintRuntimeService.setNodeTemplateAttributeValue(nodeTemplateName, + "assignment-params", "params".asJsonPrimitive()) + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + log.info("Recovering component..") + } +} + +@Component("singleton-function") +@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) +class SingletonComponentFunction : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing component : $operationInputs") + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + log.info("Recovering component..") + } +} + +@Component("prototype-function") +@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) +class PrototypeComponentFunction : AbstractComponentFunction() { + + private val log = LoggerFactory.getLogger(MockComponentFunction::class.java) + + override fun process(executionRequest: ExecutionServiceInput) { + log.info("Processing component : $operationInputs") + } + + override fun recover(runtimeException: RuntimeException, executionRequest: ExecutionServiceInput) { + log.info("Recovering component..") + } +} \ No newline at end of file diff --git a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/resources/logback.xml b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/resources/logback.xml index 95947ad3e..56e662286 100644 --- a/ms/blueprintsprocessor/modules/services/workflow-service/src/test/resources/logback.xml +++ b/ms/blueprintsprocessor/modules/services/workflow-service/src/test/resources/logback.xml @@ -26,7 +26,7 @@ - + diff --git a/ms/blueprintsprocessor/parent/pom.xml b/ms/blueprintsprocessor/parent/pom.xml index f1c601ffe..0b2ac7061 100755 --- a/ms/blueprintsprocessor/parent/pom.xml +++ b/ms/blueprintsprocessor/parent/pom.xml @@ -20,11 +20,11 @@ 4.0.0 - org.onap.ccsdk.apps + org.onap.ccsdk.cds blueprintsprocessor 0.4.2-SNAPSHOT - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor parent pom Blueprints Processor Parent @@ -216,7 +216,7 @@ ${protobuff.java.utils.version} - org.onap.ccsdk.apps.components + org.onap.ccsdk.cds.components proto-definition ${project.version} @@ -281,96 +281,96 @@ - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor processor-core ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor db-lib ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor rest-lib ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor dmaap-lib ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor execution-service ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor workflow-service ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor resource-api ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor selfservice-api ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor + org.onap.ccsdk.cds.blueprintsprocessor application ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions resource-resolution ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions python-executor ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions netconf-executor ${project.version} - org.onap.ccsdk.apps.blueprintsprocessor.functions + org.onap.ccsdk.cds.blueprintsprocessor.functions restconf-executor ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints resource-dict ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-core ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-scripts ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints db-resources ${project.version} - org.onap.ccsdk.apps.controllerblueprints + org.onap.ccsdk.cds.controllerblueprints blueprint-validation ${project.version} diff --git a/ms/blueprintsprocessor/pom.xml b/ms/blueprintsprocessor/pom.xml index 2f2576786..ffdb877e4 100755 --- a/ms/blueprintsprocessor/pom.xml +++ b/ms/blueprintsprocessor/pom.xml @@ -18,9 +18,10 @@ 4.0.0 - org.onap.ccsdk.apps - ccsdk-apps-ms + org.onap.ccsdk.cds + ms 0.4.2-SNAPSHOT + .. blueprintsprocessor pom -- cgit 1.2.3-korg